#9812 closed bug (worksforme)
$("#checkbox").attr("checked") don't work with jquery-1.6.2
Reported by: | Owned by: | ||
---|---|---|---|
Priority: | low | Milestone: | None |
Component: | attributes | Version: | 1.6.2 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
Why the function $("#checkbox").attr("checked") don't work??? When must be "true" return "checked" and when must be "false" return "undefined".
With the version 1.5.1 this function work correctly.
Change History (3)
comment:1 follow-up: 2 Changed 12 years ago by
Component: | unfiled → attributes |
---|---|
Priority: | undecided → low |
Resolution: | → worksforme |
Status: | new → closed |
comment:2 Changed 12 years ago by
Replying to addyosmani:
Thanks for submitting a ticket. The reason this isn't working is because the attribute you are checking for (checked) likely hasn't been defined. If you wish to check for truthy/falsy values on checkboxes, we recommend using .prop('checked') instead as follows: http://jsfiddle.net/addyosmani/tz9Zt/
Wrong answer. jQuery 1.6.1 release notes explicitly says in black bold text: "When updating from 1.5.2 to 1.6.1, you should not have to change any attribute code." And now it turns out, you have to...
attr() ALWAYS should use prop() when it is actually a property ( selectedIndex, selected, readonly, checked, etc.), with a simple if() or switch-case statement inside it. Easy fix.
comment:3 Changed 12 years ago by
@anonymous: the changed behavior for attr('checked') is also in the release notes and documentation. It has always been recommended to check for a truthy value when checking for checked:
if ( $(elem).attr('checked') ) { }
This is because return types were inconsistent across browsers before 1.6. Now, as you've noted, attr correctly returns "checked" and undefined for _attribute_ values, while the property( retrieved with prop or raw js) will correctly return true and false.
Therefore, if users were doing things correctly, the statement holds true: you should not have to change any attribute code.
As for selectedIndex, attr has never and will never officially support retrieving properties, even though it worked in the past. With 1.6 came the introduction of http://api.jquery.com/prop and removed the ambiguity between attributes and properties. For more information, see the docs on prop.
Thanks for submitting a ticket. The reason this isn't working is because the attribute you are checking for (checked) likely hasn't been defined. If you wish to check for truthy/falsy values on checkboxes, we recommend using .prop('checked') instead as follows: http://jsfiddle.net/addyosmani/tz9Zt/