$( elem ).attr("checked") giving opposite results
This question already has an answer here:
The problem is that you are checking checked
attribute which is not going to be removed or added when checked status changes. This is a nuance you should be aware about properties and attributes. You need to compare checked
property of the checkbox element, not attribute.
Also it's better to use change
event handler (because you can check checkbox not only with mouse click but with keyboard too).
$("input[type=checkbox]").change(function() {
if (this.checked) {
alert("checked");
}
else {
alert("not checked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "checkbox" id = "all" value="all" /> MyCheckbox
This :
$(this).attr("checked") //in old versions of jquery this yield "checked" ,
Yields undefined
which is a Falsy statement.
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set
You can either use :
if ($(this).is(":checked"))
or
$(this).prop("checked")
As of jQuery 1.6 , the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
链接地址: http://www.djcxy.com/p/27544.html