<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>實現復選框的操作</title>
</head>
<body>
<h4>請選擇你的愛好:</h4>
<input type="checkbox" id="all">全選/全不選<br>
<input type="checkbox" id="sel2" value="打籃球">打籃球
<input type="checkbox" id="sel2" value="踢足球">踢足球
<input type="checkbox" id="sel2" value="上網">上網
<input type="checkbox" id="sel2" value="寫代碼">寫代碼
<input type="checkbox" id="sel2" value="聽音樂">聽音樂
<br>
<button>全選</button>
<button>全不選</button>
<button>反選</button>
</body>
</html>
<script>
var oall = document.querySelector("#all");
var asel2 = document.querySelectorAll("#sel2");
var abtn = document.querySelectorAll("button")
//全選,全不選
oall.onclick = function () {
if (oall.checked) {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = true;
}
} else {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = false;
}
}
}
//全選
abtn[0].onclick = function () {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = true;
}
}
//全不選
abtn[1].onclick = function () {
for (var i = 0; i < asel2.length; i++) {
asel2[i].checked = false;
}
}
//反選
abtn[2].onclick = function () {
for (var i = 0; i < asel2.length; i++) {
if (asel2[i].checked) {
asel2[i].checked = false;
} else {
asel2[i].checked = true;
}
}
}
</script>
