简体   繁体   中英

Disable text area if radio button is selected?

I have a form where I would like to "grey out" the textArea until the "No" radio button is selected.

@Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, true, new { id="radio1" }) Yes
@Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, false, new { id="radio2" }) No
@Html.TextAreaFor(p => Model.Questions[i].ActionToTake, new { id="textArea" })

Whats a good way to approach this? I'm fairly new to javascript a bit of additional text explaining what you're doing would be nice.

EDIT2: $("input[name='group1']").change listens for changes in the radio group with name "group1". When it fires you check where the change happened ("$(this).val() == 'no'" means that the change was triggered in the second radio button that has a value of "no") and then you do your logic.

EDIT(Better):

$("input[name='group1']").change(function(e){
    if($(this).val() == 'no') {
        $("#text1").prop('readonly', true); 
        $("#text1").css('background-color', '#EBEBE4');
    } else if($(this).val() == 'yes') {
        $("#text1").prop('readonly', false);
        $("#text1").css('background-color', '#FFFFFF');
    }
});

@Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, true, new { id="radio1", name="group1", value="yes" }) Yes
@Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, false, new { id="radio2", name="group1", value="no" }) No

https://jsfiddle.net/vaxc3eo5/3/

ORIGINAL:

Using JQuery:

Using the readonly and adding background color to have the same look as disabled.

$("#radio2").change(function(){
    $("#text1").prop('readonly', true); 
    $("#text1").css('background-color', '#EBEBE4');
});
$("#radio1").change(function(){
    $("#text1").prop('readonly', false);
    $("#text1").css('background-color', '#FFFFFF');
});

https://jsfiddle.net/vaxc3eo5/2/

A Javascript function could do this for you, something like this:

<script type="text/javascript">
  function enableTextArea() {
     var el = document.getElementById("radio2");
     document.getElementById("textArea").readOnly = !el.checked;
  }  
</script>

HTML:

@Html.RadioButtonFor(p => Model.Questions[i].AnswerSelected, false, new { id="radio2", onclick = "enableTextArea()" }) No

In JQuery it can also be done like this:

$('#radio2').click(function(){
    $('#textArea').attr("disabled", false);
})

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