Reputation: 24651
When I run the following self-contained code, the checkbox gets checked and unchecked once but thereafter it doesn't even though the messages seem to imply the toggling.
<html>
<head>
<title>dummy</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="fc" type="checkbox" />
<script>
function f () {
if (typeof $("#fc").attr("checked") !== 'undefined') {
alert("checked, unchecking");
$("#fc").removeAttr("checked");
} else {
alert("unchecked, checking");
$("#fc").attr("checked", "checked");
}
setTimeout(f, 1000);
}
setTimeout(f, 1000);
</script>
</body>
</html>
Upvotes: 11
Views: 20963
Reputation: 388446
need to use .prop() instead of .attr() to check and uncheck checkboxes
$("#fc").prop("checked", true);// true to check false to uncheck
Also use :checked filter to check whether a checkbox is checked
function f () {
if ($("#fc").is(":checked")) {
alert("checked, unchecking");
$("#fc").prop("checked", false);
} else {
alert("unchecked, checking");
$("#fc").prop("checked", true);
}
setTimeout(f, 1000);
}
setTimeout(f, 1000);
The above given sample can be simplified as
function f () {
$("#fc").prop("checked", !$("#fc").is(":checked"));
}
setInterval(f, 1000);
Demo: Fiddle
Upvotes: 20