javascript - 如何从列表中删除未选中的值?
问题描述
我需要从复选框中获取所有选中的值并在元素中返回它们。
我有一个代码:
this.values = [];
if (item.checked) {
this.values.push(item.value);
} else {
this.values.splice(item.value)
}
return alert(this.values);
有几个问题:
- 如果我选中和取消选中同一个项目,它每次都会推送到数组,所以可能有相同的多个值。
(this.values = [1,1,1])
- Splice 不会从 this.values 中删除一个未选中的 item.value,它会删除所有值并使 this.values 为空
(this.values = []);
我需要的是:如果我有项目值,例如: 1 , 2 , 3
并检查每个项目,我的数组将变为 -this.values = [1 , 2 , 3]
如果我取消选中第 2 项,this.values = [1, 3]
解决方案
为所有复选框使用一个公共类,然后使用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>
推荐阅读
- python - 使用 executemany() 加载 CSV 的 Python cx_Oracle 给出“未找到必需的参数‘参数’(位置 2)”
- sql-server - SQL Server 子查询返回超过 1 个值。这是不允许的
- symfony - 具有“算法:自动”的用户密码字段的最大长度?
- python-3.x - 如何解决autopytoexe中的错误以将python程序编译为exe?
- mule - RAML 字符串数组中项目的最大长度
- c++ - CMake 链接器标志
- c# - 使用泛型转换器使用派生源类列表中的对象更新目标派生类列表中的对象
- react-native - 如何在 React Native 中从 NFC 卡读取数据?
- angular - 类型“字符串”不可分配给类型“数字”
- amazon-web-services - 是否可以在 WebHost 启动后添加到 IConfiguration?