How to detect radio button deselect event?

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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).

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 onchange event to trigger the handlers. Thanks to Faust for pointing that out.

$('input[type="radio"]').on('change', function(){
    // ...
}

Solution 2 - Javascript

You can create a custom "deselect" event relatively painlessly, but as you've already discovered the standard change event is only triggered on the newly checked radio button, not on the previously checked one that has just been unchecked.

If you'd like to be able to say something like:

$("#one").on("deselect", function() {
    alert("Radio button one was just deselected");
});

Then run something like the following function from your document ready handler (or put the code directly in your document ready handler):

function setupDeselectEvent() {
    var selected = {};
    $('input[type="radio"]').on('click', function() {
        if (this.name in selected && this != selected[this.name])
            $(selected[this.name]).trigger("deselect");
        selected[this.name] = this;
    }).filter(':checked').each(function() {
        selected[this.name] = this;
    });
}

Working demo: http://jsfiddle.net/s7f9s/2

What this does is puts a click handler on all the radios on the page (this doesn't stop you adding your own click event handlers to the same radios) that will check if there was a previously selected radio in the same group (i.e., with the same name) and if so trigger a "deselect" event on that radio. Then it saves the just-clicked one as the current one. The "deselect" event is not triggered if you click the already checked radio or if there was no previously checked one. The .filter().each() bit at the end is to make note of which radios are already selected. (If you need to cater for more than one form on the same page having independent radio groups of the same name then update the function above accordingly.)

Solution 3 - Javascript

I found that the simplest way to do this without putting in a new framework to create a deselected event, is to make changing any radio button trigger an update event on all of the radio buttons in its group and then define the behavior you want in the update event.

The downside is that the code in the deselection branch will run even if the radio button was not previously selected. If all you're doing is simple showing, hiding, or disabling UI elements, that shouldn't matter much.

To use your example:

buttons = $('input[name="a"]');
buttons.change(function() {
    buttons.trigger('update:groupA');

}).bind('update:groupA', function(){
    if(this.checked) {
        //Do your checked things
    } else {
        //Do your unchecked things. Gets called whenever any other button is selected, so don't toggle or do heavy computation in here.
    }
});​

Solution 4 - Javascript

I think you need to add the change function on the input level, rather than on each radio button.

Try this:

$("input[name='a']").change(function() {
  $("input[name='a']").each(function(){
    if(this.checked) {
        // do something when selected
    } else {
        // do something when deselected
    }
  });   
});​

Solution 5 - Javascript

I think this could be happening because the focus event triggers before the change event so the next radio you click will be focused before the previous checked radio triggers a change event. Don't quote me on this though...

You could do it like this:

var isChecked = function(id) { alert(id + ': ' + $('#' + id).is(':checked')) }
$('input[name="a"]').change(function(){ isChecked('one') })

Demo: http://jsfiddle.net/elclanrs/cD5ww/

Solution 6 - Javascript

You can trigger the 'change' event yourself. It's a bit tricky to avoid radio buttons infinitely triggering 'change' event on each other, but it can be done like this:

$('input[type="radio"]').each(function() {
    var name = $(this).attr('name');
    var that = this;
    $('input[name="'+name+'"][type="radio"]').not(that)
        .on('change', function(e, alreadyTriggered) {
            if(!alreadyTriggered || alreadyTriggered.indexOf(this) == -1) {
                if(!alreadyTriggered) {
                    alreadyTriggered = [that];
                }
                alreadyTriggered.push(this);
                $(that).trigger('change', [alreadyTriggered]);
            }
    });
});

Here's the demo of the above code at work.

Solution 7 - Javascript

I found a workaround for my specific case that might help. This works when the "deselect" event can be applied to all radio buttons that aren't selected.

I wanted to:

  1. add a class to the element when the radiobutton was selected, and
  2. remove that class when the button was "deselected".

I happened to find this question, because I had the same problem:

$('input:radio').on('change', function() {
    if( $(this).is(':checked') ) {
        $(this).addClass('my-class-for-selected-buttons')
    } else { // THIS WILL NEVER HAPPEN
        $(this).removeClass('my-class-for-selected-buttons')
    }
});​

But, in my case, the solution was pretty much easier, because I can try to remove the class from all the radio-buttons pretty simply with jQuery, and then add the class to the selected one:

$('input:radio').on('change', function() {
    $('input:radio').removeClass('my-class-for-selected-buttons') // Here!
    
    if( $(this).is(':checked') ) {
        $(this).addClass('my-class-for-selected-buttons')
    }
});​

With this simple tweak, I didn't need to find a way to trigger the "deselect" event.

So, if in your case you can apply the event to all the radio buttons that aren't selected, and not only to the one that's just been "deselected", you can use this measure!

Solution 8 - Javascript

Note: I'm using the most recent version of jquery: version 3.4.1. But this should work for older versions as well.

The major challenge here is that the change event is only triggered for the radio button that was checked. The code below confirms this.

$("input[name^='account']").change(function() {
    console.log($(this).prop('id') + " was checked");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<form action='#'>
    <input id='john' type='radio' name='account[]' value=''><label for='john'>John</label><br>
    <input id='jane' type='radio' name='account[]' value=''><label for='jane'>Jane</label><br>
    <input id='jeff' type='radio' name='account[]' value=''><label for='jeff'>Jeff</label><br>
    <input id='jude' type='radio' name='account[]' value=''><label for='jude'>Jude</label><br>
    <input type='text' name='amount' value=''><br>
    <input type='submit' value='submit'>
</form>

My Solution: Handle everything inside the change event handler in 3 simple steps:

  1. handle the changes for the currently checked radio button.
  2. attach custom event and handler to all other radio buttons in the same group.
  3. immediately trigger this custom event.

No need to play around with click events here. simple!

var radioBtns = $("input[name^='account']");
radioBtns.change(function() {
    // 1. handle changes for the currently checked radio button.
    console.log($(this).prop('id') + " was checked");
    // 2. attach custom event and handler to all other radio buttons in the same group.
    radioBtns.not(':checked').off('deselect').on('deselect', function() {
        $(this).each(function(i, e) {
            console.log($(e).prop('id') + " was not checked");
        });
    }).trigger('deselect'); // 3. immediately trigger this custom event.
     
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<form action='#'>
    <input id='john' type='radio' name='account[]' value=''><label for='john'>John</label><br>
    <input id='jane' type='radio' name='account[]' value=''><label for='jane'>Jane</label><br>
    <input id='jeff' type='radio' name='account[]' value=''><label for='jeff'>Jeff</label><br>
    <input id='jude' type='radio' name='account[]' value=''><label for='jude'>Jude</label><br>
    <input type='text' name='amount' value=''><br>
    <input type='submit' value='submit'>
</form>

Solution 9 - Javascript

I played a bit with the ids. That is probably an inefficient solution to be fair.

<input type="radio" id="radio-1" name="a" value="initial 1"/>
<input type="radio" id="radio-2" name="a" value="initial 2"/>
let id;
$('input[id*="radio-"]').on('click', (function() {
      if (this.id != id && this.checked) {
        id = this.id;
        this.checked = true;
        console.log('selected');
      } else if (this.id == id && this.checked) {
        id = undefined;
        this.checked = false;
        console.log('deselected');
      }
}));

JSFiddle

Solution 10 - Javascript

hows this for ya?

http://jsfiddle.net/WZND9/6/

 $('input').change(function() {
    if ($('#one').is(':checked')) {
        alert('checked');
    } else { 
        alert('not checked');
    }
 }); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontskuzzyView Question on Stackoverflow
Solution 1 - JavascriptbrezanacView Answer on Stackoverflow
Solution 2 - JavascriptnnnnnnView Answer on Stackoverflow
Solution 3 - JavascriptTacroyView Answer on Stackoverflow
Solution 4 - JavascriptDavid CheungView Answer on Stackoverflow
Solution 5 - JavascriptelclanrsView Answer on Stackoverflow
Solution 6 - JavascriptKamil SzotView Answer on Stackoverflow
Solution 7 - JavascriptMauricio MoraesView Answer on Stackoverflow
Solution 8 - JavascriptUdo E.View Answer on Stackoverflow
Solution 9 - Javascriptdevoid_of_chillView Answer on Stackoverflow
Solution 10 - JavascriptowenmelbzView Answer on Stackoverflow