开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情
JavaScript多选框功能
我们在写一些功能时,需要用到多选框这个功能,比如像购物车这种的东西就需要用到
我分享下我做这个功能的方法
功能描述
我们有一个 all 多选的按钮,和三个复选框的按钮
我们需要点击ALL之后将one、two、three给选上
当将one、two、three全部选上时将all选上,反之则关闭
<input type="checkbox" id="all">
<label for="all">ALL</label>
<hr>
<input type="checkbox" id="one">
<label for="one">one</label>
<input type="checkbox" id="two">
<label for="two">two</label>
<input type="checkbox" id="three">
<label for="three">three</label>
思路
当ALL的value值发生变化时,让下面三个复选框的 checked等于ALL的checked
点击下面三个复选框时声明一个数组,让数组的内容来自三个复选框中选中的按钮
当数组的内容个数等于3时让ALL的checked为true,否则ALL的checked为false
实践
1.获取ALL按钮和三个复选框按钮
let all = document.querySelector('#all');
let inputs = document.querySelectorAll('input:not(#all)');
let inputs = document.querySelectorAll('input:not(#all)');
获取除 id 为 ALL 以外的元素
2.监听ALL的value是否发送变化
all.onchange = function () {
inputs.forEach(item => {
item.checked = all.checked
})
}
onchange当ALL的值发生变化执行事件
遍历inputs,让所有元素的 checked 为 ALL 的 checked
3.当选上所有的复选框让ALL的checked为true
遍历 inputs 给它们加上点击事件
每次点击时声明一个arr,来自inputs里checked为true的元素
当 arr.length===inputs.length 时让 ALL 的 checked 为 true 反之则 false
inputs.forEach(item => {
item.onclick = function () {
// 声明一个数组 内容来自inputs里面checked为true的元素
let arr = Array.from(inputs).filter(item => item.checked === true);
if (arr.length === inputs.length) all.checked = true;
else all.checked = false;
}
})
if (arr.length === inputs.length) all.checked = true;
else all.checked = false;
这一串代码还可以再简化一下
all.checked = arr.length === inputs.length;
// 它和 if (arr.length === inputs.length) all.checked = true;
// else all.checked = false;
// 是一样的
当 arr.length===inputs.length 时让 all.checked=true
代码总览
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="checkbox" id="all">
<label for="all">ALL</label>
<hr>
<input type="checkbox" id="one">
<label for="one">one</label>
<input type="checkbox" id="two">
<label for="two">two</label>
<input type="checkbox" id="three">
<label for="three">three</label>
<script>
let all = document.querySelector('#all');
let inputs = document.querySelectorAll('input:not(#all)');
// 点击all后选上全部
// onchange 当 all 的 value 值发送变化时触发
all.onchange = function () {
inputs.forEach(item => {
// 让inputs里面所有元素的checked为true
item.checked = all.checked
})
}
inputs.forEach(item => {
item.onclick = function () {
// arr的内容来自inputs里面checked为ture的元素
let arr = Array.from(inputs).filter(item => item.checked === true);
// if (arr.length === inputs.length) all.checked = true;
// else all.checked = false;
// 当 arr.length===inputs.length 时让 all.checked=true
all.checked = arr.length === inputs.length;
}
})
</script>
</body>
</html>