Issue
How do I disable the second set of radio buttons if the radio button on the first set is set to Yes? And enable if set to No?
First set:
<input type="radio" id="firstsetno" name="xfirstset" value="0" checked>No
<input type="radio" id="firstsetyes" name="xfirstset" value="1">Yes
Second set:
<input type="radio" id="secondsetno" name="xsecondset" value="0" checked>No
<input type="radio" id="secondsetyes" name="xsecondset" value="1">Yes
Solution
I know Jain answered this already but I figured I'd provide a solution that's slightly easier to read. I used jQuery (as did Jain) but you could accomplish the same thing using vanilla JavaScript if you prefer.
//Fire when the status of the radio button #firstsetyes changes
$("input[type=radio][name='xfirstset']").change(function() {
// Get the radio buttons in the second set
var secondSet = $("input[type=radio][name='xsecondset']");
for (var i = 0; i< secondSet.length; i++){
console.log(secondSet[i]);
}
if( $('#firstsetyes').prop('checked') ) {
// Loop through the second set and disable the buttons
for (var i = 0; i< secondSet.length; i++){
secondSet[i].disabled = true;
}
}
else {
for (var i = 0; i< secondSet.length; i++){
secondSet[i].disabled = false;
}
}
});
Here's also link to the CodePen where I wrote and tested the code: https://codepen.io/Rikkokiri/pen/OvpzYg?editors=1011
Update
To make second set default to 'no', you just need checked
in your input tag corressponding to answer 'no' (like you had in your code, I just took it out while I was testing. I've now updated my pen in Codepen to have it.)
<form>
<p>
<input type="radio" id="firstsetno" name="xfirstset" value="0" checked>No
<br>
<input type="radio" id="firstsetyes" name="xfirstset" value="1">Yes
</p>
<p>
Second set:
<br>
<input type="radio" id="secondsetno" name="xsecondset" value="0" checked>No
<br>
<input type="radio" id="secondsetyes" name="xsecondset" value="1">Yes
</form>
Update 2
If you'd like it to just disable the 'no' button in the second set, instead of looping through all the buttons in the second set, you simply target the no button.
$("input[type=radio][name='xfirstset']").change(function() {
if( $('#firstsetyes').prop('checked') ) {
$('#secondsetno').prop('disabled', true);
}
else {
$('#secondsetno').prop('disabled', false);
}
});
Answered By - Rikkokiri
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.