我有一个带有多个复选框的HTML页面。

我需要一个名称为“全选”的复选框。当我选择此复选框时,HTML页面中的所有复选框都必须被选中。我该怎么做呢?


当前回答

我不确定有人没有这样回答(使用jQuery):

  $( '#container .toggle-button' ).click( function () {
    $( '#container input[type="checkbox"]' ).prop('checked', this.checked)
  })

它是干净的,没有循环或if/else子句,工作就像一个魅力。

其他回答

JavaScript是最好的选择。下面的链接给出了一个使用按钮取消/全选的例子。你可以尝试调整它来使用复选框,只需使用你的“全选”复选框的onClick属性。

Javascript函数来检查或取消所有复选框

本页有一个更简单的示例

http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html

简单扼要:

jQuery -点击按钮或div或标签元素。勾选页面上的所有复选框。请记住,您必须调整:复选框,使其更具体。

jQuery("#My-Button").click(function() {

  jQuery(':checkbox').each(function() {
    if(this.checked == true) {
      this.checked = false;                        
    } else {
      this.checked = true;                        
    }      
  });

});
<script language="JavaScript">
function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var checkbox in checkboxes)
    checkbox.checked = source.checked;
}
</script>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

更新:

对于每个…in construct似乎不能工作,至少在Safari 5或Chrome 5中是这样。这段代码应该在所有浏览器中工作:

function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}

您可以使用此代码。

var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
  let checkboxes = document.querySelectorAll(".dlMultiDelete");
  checkboxes.forEach(function (ele) {
    ele.checked = !!checkbox.checked;
  });
});

由于我无法评论,这里作为回答: 我会用更一般的方式写出Can Berk Güder的解决方案, 因此,您可以对其他复选框重用该函数

<script language="JavaScript">
  function toggleCheckboxes(source, cbName) {
    checkboxes = document.getElementsByName(cbName);
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = source.checked;
    }
  }
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>