JQuery no longer accepts attr ("Checked") === true Logic

I noticed that after upgrading to the latest jquery (1.7.1) version, the following code no longer evaluates

if( $('#item').attr('checked') === true ){
    //do something
}

I understand why they may have made this change, but does anyone have a link to the documentation about why they did it? I want my code to work correctly .. and it seems like I may have misused the above for quite some time.

+3
source share
3 answers

It does not work, because each browser has its own way of making it checked, for example:

checked, checked = "checked", checked = "true".

therefore you should use the: checked intead of attribute selector. and jQuery will take care of all browsers :)

+1

if( $('#item').is(':checked')){
    //do something
}
+4

.is, , . . ,

if( $('#item').is(':checked')){
..

Edit:

, jQuery $('#item').attr('checked') true. checked undefined.

,

.attr ('checked') after 1.6 correctly returns a string (all attributes are strings). If you want a boolean property, use the new .prop () Method

If you want to compare true, use this.checked. See below, <- I prefer to use this.checkedit as it is faster than any other method.

if (this.checked === true) {
..

or

Use .propas shown below DEMO

if($(this).prop('checked') === true) {
..

Demo

+4
source

All Articles