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=".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>
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>
Share
Improve this question
asked Aug 26, 2013 at 8:06
necromancernecromancer
24.6k22 gold badges70 silver badges117 bronze badges
2
- 1 Tested in Firefox and it seems to work the first time, but then it's just rendered as unchecked. – Felix Kling Commented Aug 26, 2013 at 8:11
- correct, same for me in Chrome and Firefox – necromancer Commented Aug 26, 2013 at 8:13
1 Answer
Reset to default 20need 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