jQuery check/uncheck radio button onclick
I have this code to check/uncheck a radio button onclick.
I know it is not good for the UI, but I need this.
$('#radioinstant').click(function() {
var checked = $(this).attr('checked', true);
if(checked){
$(this).attr('checked', false);
}
else{
$(this).attr('checked', true);
}
});
The above function is not working.
If I click on the button, nothing changes. It remain checked. Why? Where is the error? I am not a jQuery expert. I am on jQuery 1.3.2
Just to be clear
#radioinstant
is the ID of the radio button.
Best Answer :
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 :
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: http://jsfiddle.net/EtNXP/1467/
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'));
});
};
source : http://stackoverflow.com/questions/6191621/jquery-check-uncheck-radio-button-onclick