How to detect radio button deselect event?

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

    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.
        }
    });​
    

提交回复
热议问题