11

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>
2
  • 1
    Tested in Firefox and it seems to work the first time, but then it's just rendered as unchecked. Commented Aug 26, 2013 at 8:11
  • correct, same for me in Chrome and Firefox Commented Aug 26, 2013 at 8:13

1 Answer 1

20

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

Sign up to request clarification or add additional context in comments.

5 Comments

@Vandesh: There's plenty wrong with it. See, one big difference between the checked attribute and the checked property, is that the property gets/sets the current value, and the attribute gets/sets the initial value (and won't affect the state of the box afterward).
Or $("#fc").prop("checked", function(i, v) { return !v; });
@cHao: Then why does adding and removing the attribute check and uncheck the box the first time?
@FelixKling: Not sure. It's rather broken that only the first iteration works, IMO. It should either work every time or not work at all. Its only working once makes finding issues like this more difficult.
@Vandesh: Did you happen to try doing it in an interval? It checks the box once, unchecks it once, then nothing. See jsfiddle.net/arunpjohny/fDZXR/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.