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? 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. Commented May 12, 2011 at 17:25
  • Why not use the simpler and faster if (this.checked) { ... ? 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'))
Sign up to request clarification or add additional context in comments.

2 Comments

Like selected I believe there are browsers and cases where this would have failed. (Thus the change to use prop).
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.
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.

Comments

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 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.