首页 > 解决方案 > 如何从列表中删除未选中的值?

问题描述

我需要从复选框中获取所有选中的值并在元素中返回它们。

我有一个代码:

this.values = []; 
if (item.checked) {
        this.values.push(item.value);
    } else {
        this.values.splice(item.value)
    }
 return alert(this.values);

有几个问题:

  1. 如果我选中和取消选中同一个项目,它每次都会推送到数组,所以可能有相同的多个值。(this.values = [1,1,1])
  2. Splice 不会从 this.values 中删除一个未选中的 item.value,它会删除所有值并使 this.values 为空(this.values = []);

我需要的是:如果我有项目值,例如: 1 , 2 , 3

并检查每个项目,我的数组将变为 -this.values = [1 , 2 , 3]

如果我取消选中第 2 项,this.values = [1, 3]

标签: javascriptarrays

解决方案


为所有复选框使用一个公共类,然后使用document.querySelectorAll获取复选框并将事件侦听器附加到每个框。

现在change甚至调用另一个函数并首先filter退出checked复选框,然后用于map获取复选框值的数组

let elem = [...document.querySelectorAll('.checkBox')]
elem.forEach(item => item.addEventListener('change', getChecked))

function getChecked() {
  let getChex = elem.filter(item => item.checked).map(item => item.value)
  console.log(getChex)
}
<input type="checkbox" value="1" id="one" class="checkBox">
<label for="one">1</label>

<input type="checkbox" value="2" id="two" class="checkBox">
<label for="two">2</label>

<input type="checkbox" value="3" id="three" class="checkBox">
<label for="three">3</label>


推荐阅读