Bug Tracker

Ticket #9812 (closed bug: worksforme)

Opened 3 years ago

Last modified 3 years ago

$("#checkbox").attr("checked") don't work with jquery-1.6.2

Reported by: jose.tiago13@… Owned by:
Priority: low Milestone: None
Component: attributes Version: 1.6.2
Keywords: Cc:
Blocking: Blocked by:

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

comment:1 follow-up: ↓ 2 Changed 3 years ago by addyosmani

  • Priority changed from undecided to low
  • Resolution set to worksforme
  • Status changed from new to closed
  • Component changed from unfiled to attributes

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/

comment:2 in reply to: ↑ 1 Changed 3 years ago by anonymous

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 3 years ago by timmywil

@anonymous: the changed behavior for attr('checked') is also in the release notes and documentation. It has always been recommended to checked 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.

Version 0, edited 3 years ago by timmywil (next)
Note: See TracTickets for help on using tickets.