How to check/uncheck radio button on click?

后端 未结 18 1460
情深已故
情深已故 2020-11-29 02:16

I want to be able to uncheck a radio button by clicking on it.

So, if a radio button is unchecked, I want to check it, if it is checked, I want to uncheck it.

<
18条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 02:25

    This is not to replace a checkbox, it's to allow a radio group to go back to an unselected state. This was tricky because the radio selection doesn't act like a normal event.

    The browser handles radio buttons outside the normal event chain. So, a click handler on a radiobutton with event.preventDefault() or event.stopPropagation() will NOT prevent the radiobutton from being checked. The .removeAttr('checked') must be done in a setTimeout to allow the event to finish, and the browser to check the radiobutton (again), and then the setTimeout will fire.

    This also correctly handles the case where a user starts the mousedown but leaves the radiobutton before mouseup.

    //$ = jQuery;
    $(':radio').mousedown(function(e){
      var $self = $(this);
      if( $self.is(':checked') ){
        var uncheck = function(){
          setTimeout(function(){$self.removeAttr('checked');},0);
        };
        var unbind = function(){
          $self.unbind('mouseup',up);
        };
        var up = function(){
          uncheck();
          unbind();
        };
        $self.bind('mouseup',up);
        $self.one('mouseout', unbind);
      }
    });
    

    I hope this helps

提交回复
热议问题