Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the "checked" attribute not true when checkbox is triggered? [duplicate]

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.

like image 614
nonopolarity Avatar asked Apr 02 '13 15:04

nonopolarity


1 Answers

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

like image 92
Explosion Pills Avatar answered Sep 20 '22 18:09

Explosion Pills