Reputation: 3080
I've noticed that after a upgrade to the latest version of jquery (1.7.1) that the following code no longer evalulates
if( $('#item').attr('checked') === true ){
//do something
}
I sort of understand why they may have made this change but does anyone have a link to documentation of why they have done this? I want to ensure my code works correctly.. and it seems that maybe I have been incorrectly using the above for quite a while.
Upvotes: 3
Views: 1148
Reputation: 79830
Use .is
to check if a checkbox is checked. See below,
if( $('#item').is(':checked')){
..
Edit:
As far as I know, jQuery's $('#item').attr('checked')
never returned true. It returns checked
or undefined
.
As Kevin pointed out,
.attr('checked') after 1.6 properly returns a string (all attributes are strings). If you want a boolean property, use the new .prop() method
If you want to compare true
, then use this.checked
. See below, <-- I prefer using this.checked
as this is faster than any other method.
if (this.checked === true) {
..
or
Use .prop
like below, DEMO
if($(this).prop('checked') === true) {
..
Upvotes: 4
Reputation: 1898
It's not working because every browser have their own way to make it checked for example:
checked, checked="checked", checked="true".
so you should use selector :checked intead of attribute. and jQuery will take care about all browsers :)
Upvotes: 1