JavaScript实现全选 反选 全不选

时间:2022-02-19 10:06:06
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全选 全不选 反选</title>
    <link rel="stylesheet" type="text/css" href="select_all.css">
</head>
<body>
    <form method="post" action="">
        <input type="checkbox" value="1">iPhone6<br>
        <input type="checkbox" value="2">iPhone6 plus<br>
        <input type="checkbox" value="3">iPhone6s<br>
        <input type="checkbox" value="4">iPhone6s plus<br>
        <input type="checkbox" value="5">iPhone7<br>
        <input type="checkbox" value="6">iPhone7 plus<br>
        <!--button的type需设为button 否则按下后就提交表单 所有的复选框全部都清空选择-->  <button class="btn" id="select-all" type="button">全选</button>
        <button class="btn" id="select-no" type="button">全不选</button>
        <button class="btn" id="select-inverse" type="button">反选</button>
    </form>
</body>
<script type="text/javascript" src="select_all.js"></script>
</html>
 
 
JavaScript
 
var selectAll = document.getElementById("select-all");
var selectNo = document.getElementById("select-no");
var selectInverse = document.getElementById("select-inverse");

var inputs = document.getElementsByTagName("input");

//全选 selectAll.onclick = function() {
    for(var i in inputs) {
        inputs[i].checked = true;
    }
}

//全不选 selectNo.onclick = function() {
    for(var i in inputs) {
        inputs[i].checked = false;
    }
}

//反选 selectInverse.onclick = function() {
    for(var i in inputs) {
        inputs[i].checked = !inputs[i].checked;
    }
}
 
 
CSS
 
button{
    outline: none;
}