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.