views:

102

answers:

1

Let's say I have a group of two radio buttons:

<input type="radio" name="radioButtonGroup" value="button1" checked="true"/>
<input type="radio" name="radioButtonGroup" value="button2"/>

It seems that clicking the second button triggers an event handler on that button only. However, the first button does become deselected, and visually does change. Can anyone verify that events are fired only on the button that was selected, and not any of the other buttons in the group which become deselected as a result of the click? Any clever ways to watch a radio button for a deselecting event?

A: 

I can't confirm that an event is only fired for the selected button, but if you needed to do something with the button that was just deselected, the following would work:

$(document).ready(function(){   
    var selectedRadio = null;
    $("input:radio").change(function(){        
        if(selectedRadio != null){
           alert(selectedRadio.val());   
        }
        selectedRadio = $(this);
    });
});

In action here.

If you need to keep track of multiple groups of radio buttons, you could do it with an array of currently selected buttons and match within that array when a change is detected.

Pat
Thanks Pat. I'll probably build my own radio group reprentation in JS, which will work, just not as pretty as being able to hook in to event handlers for each button.
morgancodes