Reputation: 157
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.
Upvotes: 1
Views: 2980
Reputation: 471
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
Upvotes: 1
Reputation: 669
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/
Upvotes: 3
Reputation: 555
In JQuery it can also be done like this:
$('#radio2').click(function(){
$('#textArea').attr("disabled", false);
})
Upvotes: 0