April 27, 2012

What Data Type is $('#checkbox').attr('checked')

Question by Jonathan Wood

I’ve done a lot of searching on the web and found examples that treat $('#checkbox').attr('checked') as a string and others that treat it as a Boolean.

In my case, I find that this statement works as expected:

$('#AcceptAgreement').attr('checked', false);

But this one does not:

if ($('#AcceptAgreement').attr('checked') == true)

The second statement is false because in fact the value is ‘checked’.

So which is it? Is it a string or Boolean value, and how can I read and write it in a reliable manner?

Answer by Kevin B

This depends on which version of jQuery you are using.

checked is both a property and an attribute. In older versions of jQuery, .attr() always returned the property, not the attribute, which was usually a boolean value. Newer versions of jquery (1.6+) have a new method called .prop which returns the boolean property value, while .attr() now properly returns the string value. I’m not sure if the attribute is always updated when the property changes.

Answer by Starx

There is a fundamental way of finding out the data types

console.log(typeof $('#AcceptAgreement').attr('checked'));

But before jQuery 1.7, it used to return property value, now it returns pure string.

Another alternative to this is .prop('checked') which return boolean.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!