質問

I have two radio buttons

 <div class="col-md-2">

                @Html.RadioButtonFor(model => model.ReceiveCopyOrders, "true") Yes

            </div>
            <div class="col-md-3">

                @Html.RadioButtonFor(model => model.ReceiveCopyOrders, "false", new { @id = "mailForOrder_no" }) No
            </div>

and a text box

      <div class="col-md-10">
                @Html.TextBoxFor(m => m.OrderEmail, new { @class = "form-control",@id="

mailForOrder" })
        </div>

If the radio NO is checked I want the textbox to be disabled.

I tried the script below

<script>

    $(document.getElementById('mailForOrder_no')).checked(function () {

        document.getElementById('mailForOrder').disabled = true;

        });

But the checkbox is not disabled.

What am I doing wrong ?

役に立ちましたか?

解決 2

Something like this as you are not using jQuery:

Sample fiddle

// Get radios
var rad = document.getElementsByName('mailForOrder_no');

// Disable / Enable element based on value
function disable_by_radio(w, id) {
    document.getElementById(id).disabled = 
        w.checked && w.value === "No";
}

// Update by event
rad[0].onchange = function (e) { disable_by_radio(this, 'mailForOrder'); };
rad[1].onchange = function (e) { disable_by_radio(this, 'mailForOrder'); };

// Initial update
disable_by_radio(rad[1], 'mailForOrder');

With this HTML:

<input type="text" id="mailForOrder" />
<input name="mailForOrder_no" type="radio" value="Yes" />Yes
<input name="mailForOrder_no" type="radio" value="No" checked />No

As you are not using jQuery, the $() part, and why your code does not work, is impossible to explain as it is not part of pure Javascript.

In short, a wild guess:

Radio buttons does not have a function named checked() but an attribute. If the $() part of your code only passes the object on, then trying to call an attribute would result in an error.

他のヒント

Are you trying to do something like this.

<input type="radio" name = "rad" class="rad" value="Yes"/>Yes
<input type="radio" name = "rad" class="rad" value="No"/>No

<input type="text" id="txt" />
<input type="button" onclick="disableTextBox()" />

JavaScript Code:

function disableTextBox() { 
  $(".rad").each(function() {
     if (this.checked && this.value == "No") {
         $("#txt").attr('disabled','disabled');
     }
  }); 

}

Using jQuery we can do it like this:

function(){ if($('#mailForOrder_no:checked')){$("mailForOrder").attr()"disabled","disabled"}   }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top