天天看點

js實作複選框全選,全不選及反選

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		//html布局
		<input type="button" value="全選" id="all"/>
		<input type="button" value="全不選" id="not"/>
		<input type="button" value="反選" id="cle"/>
		<br />
		<br />
		<input type="checkbox" />
		<input type="checkbox" />
		<input type="checkbox" />
		<input type="checkbox" />
		<input type="checkbox" />
		<input type="checkbox" />
		<input type="checkbox" />
		<input type="checkbox" />
		<input type="checkbox" />
		
		<script>
			//擷取按鈕
			var all = document.getElementById("all");
			var not = document.getElementById("not");
			var cle = document.getElementById("cle");
			//擷取所有複選框
			var inputs = document.getElementsByTagName("input");
			//全選
			all.onclick = function () {
				for (var i = 3; i < 12; i++) {
					inputs[i].checked = true;
				}
			};
			//全不選
			not.onclick = function () {
				for (var i = 3; i < 12; i++) {
					inputs[i].checked = false;
				}
			};
			//反選
			cle.onclick = function () {
				for (var i = 3; i < 12; i++) {
					if (inputs[i].checked === true) {
						inputs[i].checked = false;
					} else {
						inputs[i].checked = true;
					}
				}
			}
		</script>
	</body>
</html>