用JavaScript(js)实现复选框效果(全选、全不选、反选)!
程序员文章站
2022-06-25 12:07:33
复选框js全选、反选、全不选...
用JavaScript(js)实现复选框效果(全选、全不选、反选)!
话不多说,先上效果图:
HTML代码:
<p>请选择你的爱好</p>
<input type="checkbox" id="orallchoose">全选/全不选
<br>
<input type="checkbox" class="hobby">打篮球
<input type="checkbox" class="hobby">踢足球
<input type="checkbox" class="hobby">敲代码
<input type="checkbox" class="hobby">唱歌
<input type="checkbox" class="hobby">跳舞
<br>
<input type="button" id="allchoose" value="全选">
<input type="button" id="nochoose" value="全不选">
<input type="button" id="Fchoose" value="反选">
JavaScript代码:
let orallchoose = document.getElementById("orallchoose");
let allchoose = document.getElementById("allchoose");
let nochoose = document.getElementById("nochoose");
let hobby = document.getElementsByClassName("hobby");
let Fchoose = document.getElementById("Fchoose");
let check = true;
allchoose.onclick = function(check){ //全选按钮事件
for(let i=0;i<hobby.length;i++){
hobby[i].checked = check;
}
}
nochoose.onclick = function(){ //全不选按钮事件
check = false;
for(let i=0;i<hobby.length;i++){
hobby[i].checked = check;
}
orallchoose.checked = check;
check = true;
}
orallchoose.onclick = function(){ //全选或全不选按钮事件
if(check){
for(let i=0;i<hobby.length;i++){
hobby[i].checked = check;
}
check=false;
}else{
for(let i=0;i<hobby.length;i++){
hobby[i].checked = check;
}
check=true;
}
}
Fchoose.onclick = function(){ //反选按钮事件
for(let i=0;i<hobby.length;i++){
hobby[i].checked = !hobby[i].checked;
}
}
本文地址:https://blog.csdn.net/qq_43923146/article/details/107496722