Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is jQuery is not checking/unchecking checkbox

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>
like image 782
necromancer Avatar asked Aug 26 '13 08:08

necromancer


1 Answers

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

like image 107
Arun P Johny Avatar answered Sep 28 '22 00:09

Arun P Johny