antwarpes antwarpes - 1 month ago 11
HTML Question

JQuery $(#radioButton).change(...) not firing during de-selection

About a month ago Mitt's question went unanswered. Sadly, I'm running into the same situation now.

http://api.jquery.com/change/#comment-133939395

Here's the situation. I'm using JQuery to capture the changes in a radio button. When the radio button is selected I enable an edit box. When the radio button is de-selected, I would like the edit box to be disabled.

The enabling works. When I choose a different radio button in the group, the Change event is NOT fired. Does anyone know how to fix this?

<input type="radio" id="r1" name="someRadioGroup"/>


<script type="text/javascript">
$("#r1").change(function () {
if ($("#r1").attr("checked")) {
$('#r1edit:input').removeAttr('disabled');
}
else {
$('#r1edit:input').attr('disabled', true);
}
});
</script>

Answer

Looks like the change() function is only called when you check a radio button, not when you uncheck it. The solution I used is to bind the change event to every radio button:

$("#r1, #r2, #r3").change(function () {

Or you could give all the radio buttons the same name:

$("input[name=someRadioGroup]:radio").change(function () {

Here's a working jsfiddle example (updated from Chris Porter's comment.)

Per @Ray's comment, you should avoid using names with . in them. Those names work in jQuery 1.7.2 but not in other versions (jsfiddle example.).