I thought this would work:
if ($(this).attr('checked')) {}
but I had to write it this way:
if ($(this).is(':checked')) {}
Q: Why?
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'))
true
- specifically it does not have to be the string "checked". In the DOM, the attribute is indeed a simple boolean.
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.
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.
checked
property is 100% cross browser, so in this particular case it will work as expected.
.prop
instead of.attr
if (this.checked) {
... ?