Phillip Senn
Phillip Senn

Reputation: 47605

How do you check for whether a checkbox is checked or not checked?

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

Answers (3)

ehynds
ehynds

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

Jamie Treworgy
Jamie Treworgy

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

Tejs
Tejs

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

Related Questions