Content description: Click a checkbox to select all other checkboxes, and cancel a checkbox to cancel all other checkboxes.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js实现全选</title>
<script>
//window.onload里面的函数会在页面加载之后执行
window.onload = function () {
var input0 = document.getElementById('input0');
var oDiv = document.getElementById('div1');
var oInput = oDiv.getElementsByTagName('input');
input0.onclick = function () {
if (input0.checked) {
for (var i = 0; i < oInput.length; i++) {
oInput[i].checked = true;
}
} else {
for (var i = 0; i < oInput.length; i++) {
oInput[i].checked = false;
}
}
}
};
</script>
</head>
<body>
<input type="checkbox" id="input0"><br><br>
<div id="div1">
<input type="checkbox" id="input1"><br>
<input type="checkbox" id="input2"><br>
<input type="checkbox" id="input3"><br>
<input type="checkbox" id="input4"><br>
<input type="checkbox" id="input5"><br>
</div>
</body>
</html>
Code description:
window.onload indicates that the functions inside will be executed after the page is loaded
Use the onclick attribute to update the current state of the checkbox in real time
Renderings:
Initial image:
Click on the first checkbox:
Click again: