How to detect radio button deselect event?

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

提交回复
热议问题