Lets say I have a checkbox with id 'test' and its on a page loaded with jQuery 1.5.2.
<input id="test" type="checkbox"/>
Now if I click on the checkbox to set it in the checked
state...
Why does $("#test").is(":checked")
return true
and $("#test").is("*[checked]")
return false
.
Here's a jsFiddle with the described scenario
The checkedness of a checkbox is reflected in the object property
checked
. It can be set by the DOM attributechecked
, but the direction is one-way: the DOM attribute does not get updated when the object's property changes.:checked
is a dedicated pseudoselector which will check the object's property;[checked]
is a selector which checks for the existence of the DOM attribute.See the discussion of the checked property on the jQuery property page:
http://api.jquery.com/prop/
The
[checked]
is a selector that picks elements that are currently checked with thechecked
attribute not the property - in other words "if the element has the checked attribute, pick it up".If you want to check if the checkbox is checked or not, you must use
:checked
.Example usage:
With jQuery 1.6 and higher you can use the
.prop()
function for performance reasons.Because
checked
isn't an attribute of aninput
element. It is a property. Your*[checked]
selector checks to see if it has thechecked
attribute, which would never exist on an element. You can add thechecked="checked"
to aninput
element which sets thechecked
property of that object, but that attribute will always be there even when unchecking the box. This is because checking and unchecking only changes thechecked
property of the checkbox, not thechecked
attribute.check this http://jsfiddle.net/2QZvU/5/
it must be *[:checked]
As Matt said checked is a property not an attribute