How to detect radio button deselect event?

后端 未结 9 1719
不思量自难忘°
不思量自难忘° 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: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.)

提交回复
热议问题