How to detect radio button deselect event?

后端 未结 9 1695
不思量自难忘°
不思量自难忘° 2020-11-29 07:47

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

&l         


        
相关标签:
9条回答
  • 2020-11-29 08:19

    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!

    0 讨论(0)
  • 2020-11-29 08:20

    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
        }
      });   
    });​
    
    0 讨论(0)
  • 2020-11-29 08:22

    hows this for ya?

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

     $('input').change(function() {
        if ($('#one').is(':checked')) {
            alert('checked');
        } else { 
            alert('not checked');
        }
     }); 
    
    0 讨论(0)
  • 2020-11-29 08:33

    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/

    0 讨论(0)
  • 2020-11-29 08:33

    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.

    0 讨论(0)
  • 2020-11-29 08:34

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

    0 讨论(0)
提交回复
热议问题