Checking a checkbox with jQuery?
I'd like to do something like this to tick a checkbox using jQuery:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
Does such a thing exist?
Javascript
jQuery
- asked 9 years ago
- B Butts
3Answer
jQuery 1.6+
Use the new .prop()
function:
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
jQuery 1.5.x and below
The .prop()
function is not available, so you need to use .attr()
.
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using
$('.myCheckbox').removeAttr('checked');
since the latter will, if the box was initially checked, change the behaviour of a call to .reset()
on any form that contains it - a subtle but probably unwelcome behaviour change.
For more context, some incomplete discussion of the changes to the handling of the checked
attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop()
documentation.
Any version of jQuery
If you're working with just one element, you can always just modify the HTMLInputElement
's .checked
property:
$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;
The benefit to using the .prop()
and .attr()
functions instead of this is that they will operate on all matched elements.
- answered 8 years ago
- Gul Hafiz
$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);
And if you want to check if a checkbox is checked or not:
$('.myCheckbox').is(':checked');
- answered 8 years ago
- Gul Hafiz
You can do
$('.myCheckbox').attr('checked',true) //Standards compliant
or
$("form #mycheckbox").attr('checked', true)
If you have custom code in the onclick event for the checkbox that you want to fire, use this one instead:
$("#mycheckbox").click();
You can uncheck by removing the attribute entirely:
$('.myCheckbox').removeAttr('checked')
You can check all checkboxes like this:
$(".myCheckbox").each(function(){
$("#mycheckbox").click()
});
- answered 8 years ago
- Gul Hafiz
Your Answer