最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is jQuery is not checkingunchecking checkbox - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 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

发布评论

评论列表(0)

  1. 暂无评论