Reputation: 47605
I thought this would work:
if ($(this).attr('checked')) {}
but I had to write it this way:
if ($(this).is(':checked')) {}
Q: Why?
Upvotes: 0
Views: 229
Reputation: 4463
Better yet, just use this.checked
, which returns either "true" or "false". No need to use jQuery especially if you already have the DOM node.
Upvotes: 1
Reputation: 24344
Having been through this recently, it depends on what version of jQuery you are using. As of 1.6, the functioning of attr
with native properties (e.g. "checked", "disabled") -- properties being attributes that are supposed to either exist or not - changed, because they could return inconsistent results depending on browser behavior.
The correct way to set or test a property in 1.6 is with the new prop
function, which returns true or false always. The 2nd method you use is also valid to test.
Upvotes: 2
Reputation: 41246
When you request the attr checked, you are not getting a boolean value:
// this would be correct
if($(this).attr('checked') == 'checked')
// jQuery 1.6+
if($(this).prop('checked'))
Upvotes: 7