How to detect radio button deselect event?

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

    Note: I'm using the most recent version of jquery: version 3.4.1. But this should work for older versions as well.

    The major challenge here is that the change event is only triggered for the radio button that was checked. The code below confirms this.

    $("input[name^='account']").change(function() {
        console.log($(this).prop('id') + " was checked");
    });
    
    
    





    My Solution: Handle everything inside the change event handler in 3 simple steps:

    1. handle the changes for the currently checked radio button.
    2. attach custom event and handler to all other radio buttons in the same group.
    3. immediately trigger this custom event.

    No need to play around with click events here. simple!

    var radioBtns = $("input[name^='account']");
    radioBtns.change(function() {
        // 1. handle changes for the currently checked radio button.
        console.log($(this).prop('id') + " was checked");
        // 2. attach custom event and handler to all other radio buttons in the same group.
        radioBtns.not(':checked').off('deselect').on('deselect', function() {
            $(this).each(function(i, e) {
                console.log($(e).prop('id') + " was not checked");
            });
        }).trigger('deselect'); // 3. immediately trigger this custom event.
         
    });
    
    
    





提交回复
热议问题