jQuery Tutorial: Toggle enabled/disabled attribute for multiple radio buttons
So today I spent 10 minutes thinking about how to write something in jQuery that would go through and toggle the disable status for a group of radio buttons that have been dynamically generated and then it suddenly hit me — duh, just add a class to all of them and toggle based on the class. So I hope this code prevents you from having the same “brain fart” moment I did.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script language="Javascript">
$(document).ready(function() {
/* they've entered/removed something into my input field, toggle the radio buttons */
$("#myInputValue").keyup( function() { toggleDisableFields($('#myInputValue').val())});
});
function toggleDisabledRadioButtons(value)
{
/* check to see if they've entered a value in the field you want to toggle against */
if (value) {
$('.radioButtonClass').attr('disabled','disabled');
}
/* the radio buttons shouldn't be disabled yet */
else {
$('.radioButtonClass').attr('disabled','');
}
}
</script>
</head>
<body>
<input type="text" id="myInputValue" /><br/>
Enter something to disable my radio buttons, clear it out to use them again
<br/><br/>
Radio One: <input type="radio" name="myoption" class="radioButtonClass" value="1" /><br/>
Radio Two: <input type="radio" name="myoption" class="radioButtonClass" value="2" /><br/>
Radio Three: <input type="radio" name="myoption" class="radioButtonClass" value="3" /><br/>
Radio Exception: <input type="radio" name="myoption" value="4" /><br/>
(leave off the class and it won't toggle with the rest)
</body>
</html>
