0

I thought this would work:

if ($(this).attr('checked')) {}

but I had to write it this way:

if ($(this).is(':checked')) {}

Q: Why?

8
  • 4
    Why is not a question. What about this seems strange 2k user?
    – Hogan
    Commented May 12, 2011 at 17:22
  • Which jquery version are you using? Commented May 12, 2011 at 17:25
  • Are you using the latest version of jQuery? Because then you'd have to use .prop instead of .attr Commented May 12, 2011 at 17:25
  • @Pixelbobby -- I originally put "Because". The UI complained, so I did a re-write.
    – Hogan
    Commented May 12, 2011 at 17:25
  • Why not use the simpler and faster if (this.checked) { ... ?
    – Pointy
    Commented May 12, 2011 at 17:47

3 Answers 3

7

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'))
2
  • Like selected I believe there are browsers and cases where this would have failed. (Thus the change to use prop).
    – Hogan
    Commented May 12, 2011 at 17:32
  • It is perfectly OK for the value of the attribute to be the boolean constant true - specifically it does not have to be the string "checked". In the DOM, the attribute is indeed a simple boolean.
    – Pointy
    Commented May 12, 2011 at 17:46
2

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.

1

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.

2
  • I'm afraid of using any native JavaScript if there is a jQuery alternative because I don't know if it will behave one way in one browser and another way in another browser. jQuery helps me make sure my code is normalized. Commented May 14, 2011 at 19:20
  • Understood, I take the same approach most of the time. However, the checked property is 100% cross browser, so in this particular case it will work as expected.
    – ehynds
    Commented May 16, 2011 at 13:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.