Is there an easy way to attach a “deselect” event on a radio button? It seems that the change event only fires when the button is selected.
HTML
<input type="radio" id="one" name="a" />
<input type="radio" id="two" name="a" />
JavaScript
$('#one').change(function() {
if(this.checked) {
// do something when selected
} else { // THIS WILL NEVER HAPPEN
// do something when deselected
}
});
jsFiddle
Why don’t you simply create a custom event like, lets say,
deselectand let it trigger on all the members of the clicked radio group except the element itself that was clicked? Its way easier to make use of the event handling API that jQuery provides that way.HTML
jQuery
Deselection events will trigger only among members of the same radio group (elements that have the same
nameattribute).jsFiddle solution
EDIT: In order to account for all possible placements of the attached label tag (wrapping the radio element or being attached through an id selector) it is perhaps better to use
onchangeevent to trigger the handlers. Thanks to Faust for pointing that out.