How to detect radio button deselect event?

后端 未结 9 1727
不思量自难忘°
不思量自难忘° 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题