Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 404
Richard Knop Avatar asked Feb 10 '11 12:02

Richard Knop


People also ask

How do you checked a radio button when a button is clicked?

One solution is to assign on mousedown the value you are going to assign to it (the opposite of what it has) in a variable on the node like this. __rval and check for its existence in your onclick handler. If it exists, you know the value in it is correct, though the this.

How can I tell if a radio button is unchecked?

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true .

Can we uncheck radio button?

It is not a mandatory field. Radio button helps in ensuring only one option is selected. However, it doesn't allow user to deselect the option.


2 Answers

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

like image 178
HexInteractive Avatar answered Sep 28 '22 10:09

HexInteractive


try this:

$('input[type=radio]').click(function(){     if (this.previous) {         this.checked = false;     }     this.previous = this.checked; }); 
like image 40
Stephen Avatar answered Sep 28 '22 11:09

Stephen