First you need to understand difference between "attr"
and "prop"
Here's a user's answer, with the main part being:
I'll summarize the main issues:
- You usually want
prop()
rather than attr()
.
- In the majority of cases,
prop()
does what attr()
used to do. Replacing calls to attr()
with prop()
in your code will generally
work.
- Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any
type. For example, the
checked
property is a Boolean, the style
property is an object with individual properties for each style, the
size
property is a number.
- Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case
for certain attributes of inputs, such as
value
and checked
: for
these attributes, the property always represents the current state
while the attribute (except in old versions of IE) corresponds to the
default value/checkedness of the input (reflected in the
defaultValue
/ defaultChecked
property).
- This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to
learn a bit about the difference between properties and attributes.
This is a good thing.
Now there is no function called "removeattr"
, it should be "removeAttr"
, this will work if you are using older version of jquery(i.e <1.5).
Since checked
is the property of element so its safe and correct to use .prop("checked",false)
to make working in all browser.
Another answer gets a bit more practical:
jQuery 1.6+
Use the new .prop()
method:
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
jQuery 1.5.x and below
The .prop()
method 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');