Richard Knop Richard Knop - 5 months ago 22
jQuery Question

How to check/uncheck radio button on click?

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.

This does not work:

$('input[type=radio]:checked').click(function(){
$(this).attr('checked', false);
});


I am not able to check a radio button now.

Answer

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 radiobuuton (again), and then the setTimeout will fire.

This also correctly handles the when 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

Comments