jQuery check/uncheck radio button onclick
I have expanded on the previous suggestions. This works for me, with multiple radios coupled by the same name.
$("input[type='radio']").click(function()
{
var previousValue = $(this).attr('previousValue');
var name = $(this).attr('name');
if (previousValue == 'checked')
{
$(this).removeAttr('checked');
$(this).attr('previousValue', false);
}
else
{
$("input[name="+name+"]:radio").attr('previousValue', false);
$(this).attr('previousValue', 'checked');
}
});
If all you want to do is have a checkbox that checks, don't worry about doing it with JQuery. That is default functionality of a checkbox on click. However, if you want to do additional things, you can add them with JQuery. Prior to jQuery 1.9, you can use use $(this).attr('checked');
to get the value instead of $(this).attr('checked', true);
, as the second will set the value.
Here is a fiddle demonstration that shows the default checkbox functionality vs. what you are doing with JQuery.
Note: After JQuery 1.6, you should use $(this).prop;
instead of $(this).attr
in all three places (thanks @Whatevo for pointing this out and see here for further details).
UPDATE:
Sorry, missed the requirement that it had to be a radio button. You still may want to consider the checkbox, but here is the updated code for the radio input version. It works by setting the previousValue
as an attribute on the checkbox, as I don't think prop
is supported in 1.3.2. You could also do this in a scoped variable, as some people don't like setting random attributes on fields. Here is the new example.
UPDATE 2:
As Josh pointed out, the previous solution only worked with one radio button. Here's a function that makes a group of radios deselectable by their name, and a fiddle:
var makeRadiosDeselectableByName = function(name){
$('input[name=' + name + ']').click(function() {
if($(this).attr('previousValue') == 'true'){
$(this).attr('checked', false)
} else {
$('input[name=' + name + ']').attr('previousValue', false);
}
$(this).attr('previousValue', $(this).attr('checked'));
});
};