Richard Knop Richard Knop -5 years ago 219
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:

$(this).attr('checked', false);

I am not able to check a radio button now.

Answer Source

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;
  var $self = $(this);
  if( $':checked') ){
    var uncheck = function(){
    var unbind = function(){
    var up = function(){
    $'mouseout', unbind);

I hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download