Javascript 应取消选中“全部选中”复选框

Javascript 应取消选中“全部选中”复选框,javascript,html,forms,checkbox,Javascript,Html,Forms,Checkbox,功能切换(源代码){ 复选框=document.getElementsByName('options[]); 对于(变量i=0,n=checkbox.length;i

功能切换(源代码){
复选框=document.getElementsByName('options[]);
对于(变量i=0,n=checkbox.length;i

选择1
选择2
选择3
选择4
备选案文5
全部的


您需要在每个复选框中添加
onchange
事件处理程序,并检查是否应选中“全部”复选框(选中所有复选框)或未选中(至少取消选中一个)。例如:

var复选框=[].slice.call(document.getElementsByName('options[]),
allCheckbox=document.querySelector('input[value=“All”]”);
复选框。forEach(函数(复选框){
checkbox.onchange=函数(){
如果(!this.checked){
allCheckbox.checked=false;
}
否则{
选中的变量=复选框。过滤器(函数(复选框){
返回检查。已检查;
});
if(checked.length==复选框.length){
allCheckbox.checked=true;
}
}
};
});
函数切换(源){
对于(变量i=0,n=checkbox.length;i

选择1
选择2
选择3
选择4
备选案文5
全部的

我建议如下:

function toggle() {
  // getting a reference to all the 'name="option[]" elements:
  var options = document.getElementsByName('options[]'),
    // a reference to the 'all' checkbox:
    all = document.getElementById('checkbox-1-6');

  // if the changed checkbox is the 'all':
  if (this === all) {
    // we iterate over all the options checkboxes (using
    // Array.prototype.forEach()):
    Array.prototype.forEach.call(options, function(checkbox) {
      // and we set their checked property to the checked property
      // state of the 'all' checkbox:
      checkbox.checked = all.checked;
    });
  } else {
    // otherwise we set the 'all' checkbox to the state of
    // the Boolean returned by Array.prototype.every(),
    // which returns true if all checkboxes evaluate to
    // the condition within the function, otherwise false:
    all.checked = Array.prototype.every.call(options, function(checkbox) {
      return checkbox.checked;
    });
  }
}

// getting a NodeList of all the elements of 'class="unsubscribe-checkbox"':
var options = document.querySelectorAll('.unsubscribe-checkbox');

// iterating over them, again with Array.prototype.forEach()
// and assigning a change event-listener, which will execute the
// name function:
Array.prototype.forEach.call(options, function(opt) {
  opt.addEventListener('change', toggle);
});
函数切换(){
var options=document.getElementsByName('options[]'),
all=document.getElementById('checkbox-1-6');
如果(此===全部){
Array.prototype.forEach.call(选项、函数(复选框)){
checkbox.checked=all.checked;
});
}否则{
all.checked=Array.prototype.every.call(选项、函数)(复选框){
返回复选框。选中;
});
}
}
var options=document.querySelectorAll(“.unsubscribe复选框”);
Array.prototype.forEach.call(选项,函数(opt)){
opt.addEventListener(“更改”,切换);
});

选择1
选择2
选择3
选择4
备选案文5
全部的


其他复选框上没有任何事件处理程序,此处是否缺少代码?在每个复选框上添加一个方法(例如onClick)以取消选中/选中复选框-1-6。谢谢!我理解!非常感谢你!