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
Advertisement
Answer
Why don’t you simply create a custom event like, lets say, deselect
and 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
<!-- First group of radio buttons --> <label for="btn_red">Red:</label><input id="btn_red" type="radio" name="radio_btn" /> <label for="btn_blue">Blue:</label><input id="btn_blue" type="radio" name="radio_btn" /> <label for="btn_yellow">Yellow:</label><input id="btn_yellow" type="radio" name="radio_btn" /> <label for="btn_pink">Pink:</label><input id="btn_pink" type="radio" name="radio_btn" /> <hr /> <!-- Second group of radio buttons --> <label for="btn_red_group2">Red 2:</label><input id="btn_red_group2" type="radio" name="radio_btn_group2" /> <label for="btn_blue_group2">Blue 2:</label><input id="btn_blue_group2" type="radio" name="radio_btn_group2" /> <label for="btn_yellow_group2">Yellow 2:</label><input id="btn_yellow_group2" type="radio" name="radio_btn_group2" /> <label for="btn_pink_group2">Pink 2:</label><input id="btn_pink_group2" type="radio" name="radio_btn_group2" />
jQuery
// Attaching click event handlers to all radio buttons... $('input[type="radio"]').bind('click', function(){ // Processing only those that match the name attribute of the currently clicked button... $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); // Every member of the current radio group except the clicked one... }); $('input[type="radio"]').bind('deselect', function(){ console.log($(this)); })
Deselection events will trigger only among members of the same radio group (elements that have the same name
attribute).
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 onchange
event to trigger the handlers. Thanks to Faust for pointing that out.
$('input[type="radio"]').on('change', function(){ // ... }