【问题标题】:Javascript select/deselect all checkboxes in a formJavascript选择/取消选择表单中的所有复选框
【发布时间】:2015-11-04 00:48:26
【问题描述】:

我想做一个 javascript 选择/取消选择所有复选框。

这是我的脚本,但它不起作用:

<form id="labels">
<input type="checkbox">
<input type="checkbox" id="select_all">
</form>
<script>
$('#select_all').click(function()
{
        if($("#select_all").is(':checked'))
        {
            $("form#labels input[type='checkbox']").prop('checked', false);
        }else{
            $("form#labels input[type='checkbox']").prop('checked', true);
        }
    });
</script>

【问题讨论】:

  • 反对者是否愿意发表评论?

标签: javascript select checkbox


【解决方案1】:

您应该交换 truefalse 布尔值。

$('#select_all').click(function() {
  if($("#select_all").is(':checked')) {
    $("form#labels input[type='checkbox']").prop('checked', true);
  }else{
    $("form#labels input[type='checkbox']").prop('checked', false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="labels">
  <input type="checkbox" />
  <input type="checkbox" id="select_all" />
</form>

也可以简化为

$('#select_all').click(function(){
  $("#labels input[type='checkbox']").prop('checked', this.checked);
});

$('#select_all').click(function(){
  $("#labels input[type='checkbox']").prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="labels">
  <input type="checkbox" />
  <input type="checkbox" id="select_all" />
</form>

【讨论】:

    【解决方案2】:

    使用 .change 事件 - 并引用 this - 此外,您可以缩短很多时间:

    $('#select_all').change(function() {
        $("form#labels input[type='checkbox']").prop('checked', this.checked);
    });
    

    演示:http://jsfiddle.net/om37znud/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2011-10-09
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多