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.
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.
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 .
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.
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
try this:
$('input[type=radio]').click(function(){ if (this.previous) { this.checked = false; } this.previous = this.checked; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With