如果已选中某些复选框,则选中所有javascript

问题描述 投票:1回答:3

<!--

if all checkboxes are not 'checkecd' then check all
if some are 'checked' then check all
if all are 'checked' then uncheck all
-->

const btn = document.querySelector('button');
        btn.addEventListener('click',()=>{
            const allboxes = document.querySelectorAll('input[type="checkbox"]');
            allboxes.forEach(box => {
                if(!box.checked){
                    box.checked = true;
                } else {
                    box.checked = false;
                }
            })
        })
<button>select all</button>
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
单击按钮全选后,我的代码无法正常工作。如果所有复选框都不都是“ checkecd”,则选中所有如果某些被“检查”,则全部检查如果所有都被“选中”,则取消选中所有
javascript input checkbox checkboxlist
3个回答
1
投票

您可以使用数组someevery。用some检查是否已选中某些元素,并用every检查是否已全部选中。然后相应地选中或取消选中

const btn = document.querySelector('button');
btn.addEventListener('click', () => {
  const allboxes = document.querySelectorAll('input[type="checkbox"]');
  // if some of the checkbox is checked
  const isSomeCheck = [...allboxes].some(item => item.checked);
  // if all are checked
  const isAllChecked = [...allboxes].every(item => item.checked);
  // if some are checked then on click of button check all
  if (isSomeCheck) {
    allboxes.forEach(item => item.checked = true)
  }
  // if all are checked then uncheck all
  if (isAllChecked && isSomeCheck) {
    allboxes.forEach(item => item.checked = false)
  }
})
<button>select all</button>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">

1
投票

具有CSS伪类querySelectorAll的[好旧:checked,可以抢救。您可以通过将length比较移到forEach中来进一步缩短此时间。

/*
if all checkboxes are not 'checkecd'
then check all
if some are 'checked'
then check all
if all are 'checked'
then uncheck all
*/

const btn = document.querySelector('button');
btn.addEventListener('click', () => {
  const allboxes = document.querySelectorAll('input[type="checkbox"]');
  const checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');
  const allChecked = allboxes.length === checkedBoxes.length;
  allboxes.forEach(box => box.checked = !allChecked);
})
<button>select all</button>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">

0
投票

您可以使用Array.prototype.every()Array.prototype.every()。例如这样:

Array.prototype.some()
© www.soinside.com 2019 - 2024. All rights reserved.