开发者

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

开发者 https://www.devze.com 2023-03-05 05:53 出处:网络
I thought this would work: if ($(this).attr(\'checked\')) {} but I had to write it this way: if ($(t开发者_开发知识库his).is(\':checked\')) {}

I thought this would work:

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

but I had to write it this way:

if ($(t开发者_开发知识库his).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'))


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.


Interesting info about attr and prop jQuery 1.6 and 1.6.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消