2

I'm trying to do something trivial and running into a problem. When retrieving the checked attribute of a checkbox, I'm getting undefined and I can't figure out why. What am I doing wrong?

http://jsfiddle.net/YPYME/

console.log($("#invert").attr("checked"));
<input type="checkbox" id="invert"/> Invert Image

3 Answers 3

12

Because the element in question doesn't have a checked attribute. It has a checked property though:

console.log($("#invert").prop("checked")); // true or false

Here's a working example.

Sign up to request clarification or add additional context in comments.

1 Comment

THIS IS THE SECOND TIME I'VE MADE THIS MISTAKE. NEVER AGAIN. AS GOD IS MY WITNESS, I'LL NEVER CONFUSE PROPERTY AND ATTRIBUTE AGAIN.
2

Use prop() instead attr() in 1.9.1

DEMO --> http://jsfiddle.net/YPYME/2/

Comments

1

You're using jQuery 1.9 which uses the latest "prop" property instead of "attr" property which has been deprecated. Lower your jQuery version to < 1.6 or use ".prop".

1 Comment

The .attr() method has not been deprecated. It just returns undefined for attributes which do not exist on the element (in 1.6 and below it sometimes used property values instead of attribute values).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.