7

In the following code using jQuery:

$("input").change(function(evt) {
  console.log("change event handler invoked", evt);
  console.log($("input").is(':checked'));
  console.log($("input").attr("checked"));
  console.log($("input").prop("checked"));
});

$("input").trigger("click");
$("input").trigger("click");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="the-input" type="checkbox">

the is(':checked') and prop("checked") can both show a true but the `attr("checked") will show undefined. I thought they are to be the same? (even if we manually click on the checkbox, it is the same effect).

Also, if I set the checked in HTML so that the checkbox is checked by default (http://jsfiddle.net/UcGyM/1/ ), now the attr("checked") will print out checked for both triggering, so it won't be able to tell whether it is checked or not -- why is that? (it is also strange that both shows checked, but $("input").attr("checked", true); or $("input").attr("checked", false); can turn it on or off.)

A related question is, if we want to insist on using attr("checked"), does that mean in the HTML, it has to have the checked attribute: <input type="checkbox" checked>, if so, how can it specify the attribute but with it defaulted to off? (because checked="false" or checked="" or checked="0" will not make it unchecked by default.

3
  • 3
    This question might help. Commented Apr 2, 2013 at 15:40
  • attributes aren't always kept in-line with properties, that's why the change to .attr/.prop was so important and needed. Commented Apr 2, 2013 at 15:41
  • 2
    Most of the answers to your questions are here api.jquery.com/prop Commented Apr 2, 2013 at 15:41

1 Answer 1

5

No, they are not the same. .attr is the DOM attribute. It would be checked if the element were

<input type=checkbox checked>

It is the property that gets changed when clicked.

As for your related question, checked is a boolean attribute so there is no way to specify that an element is not checked while having the checked attribute at all.

I'm not sure why you would want to insist on using attr when the jQuery API itself says this is incorrect as of jQuery 1.6

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.