How to detect radio button deselect event?

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

    Why don't you simply create a custom event like, lets say, deselect and let it trigger on all the members of the clicked radio group except the element itself that was clicked? Its way easier to make use of the event handling API that jQuery provides that way.

    HTML

    
    
    
    
    
    

    jQuery

    // Attaching click event handlers to all radio buttons...
    $('input[type="radio"]').bind('click', function(){
        // Processing only those that match the name attribute of the currently clicked button...
        $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); // Every member of the current radio group except the clicked one...
    });
    
    $('input[type="radio"]').bind('deselect', function(){
        console.log($(this));
    })
    

    ​Deselection events will trigger only among members of the same radio group (elements that have the same name attribute).

    jsFiddle solution

    EDIT: In order to account for all possible placements of the attached label tag (wrapping the radio element or being attached through an id selector) it is perhaps better to use onchange event to trigger the handlers. Thanks to Faust for pointing that out.

    $('input[type="radio"]').on('change', function(){
        // ...
    }
    

提交回复
热议问题