简体   繁体   中英

Script to disable a text box on selecting a radio button

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 ?

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');
     }
  }); 

}

使用jQuery,我们可以这样做:

function(){ if($('#mailForOrder_no:checked')){$("mailForOrder").attr()"disabled","disabled"}   }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM