html代碼
<label for="all">全選</label><input type="checkbox" id="all">
<div id="box">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
JS代碼
var all = document.getElementById("all");
var aInput = document.querySelectorAll("#box>input");
all.onclick = function () {
if (this.checked) {
for (var i = 0; i < aInput.length; i++) {
aInput[i].checked = true;
}
} else {
for (var i = 0; i < aInput.length; i++) {
aInput[i].checked = false;
}
}
};
for (var i = 0; i < aInput.length; i++) {
aInput[i].onclick = function () {
var bStop = true;
for (var K = 0; K < aInput.length; K++) {
if (!aInput[K].checked) {
bStop = false;
break;
}
}
if (bStop) {
all.checked = true;
} else {
all.checked = false;
}
}
}