JS网页–全选和取消全选,供大家参考,具体内容如下
表格,初始状态下复选框都是未选中状态,选中表头的复选框后,下面几个复选框变为选中状态,取消表头复选框选中状态后,下面几个复选框选中状态也随之取消;下面的几个复选框同时选中时,表头的复选框也随之选中。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全选和取消全选</title>
<style>
table {
width: 200px;
border-collapse: collapse;
margin: 100px auto;
}
table thead {
font-size: 16px;
background-color: skyblue;
}
table th {
border: 1px solid black;
}
table td {
border: 1px solid black;
font-size: 14px;
}
</style>
</head>
<body>
<table>
<thead >
<tr>
<th><input type="checkbox" id="j_cbAll"></th>
<th>手机品牌</th>
<th>价格</th>
</tr>
</thead>
<tbody id="j_tb">
<tr>
<td><input type="checkbox" ></td>
<td>手机1</td>
<td>5000</td>
</tr>
<tr>
<td><input type="checkbox" ></td>
<td>手机2</td>
<td>6000</td>
</tr>
<tr>
<td><input type="checkbox" ></td>
<td>手机3</td>
<td>7000</td>
</tr>
</tbody>
</table>
<script>
//选择全选 下面复选框设置为checked;
var j_cbAll = document.getElementById('j_cbAll');
var j_tbs = document.getElementById('j_tb').getElementsByTagName('input');
j_cbAll.onclick = function(){
console.log(this.checked);
for (var i =0 ;i < j_tbs.length;i++){
j_tbs[i].checked = this.checked;
}
}
//下面复选框均为checked 全选复选框为checked;
for(var j = 0;j < j_tbs.length; j++){
j_tbs[j].onclick = function(){
var flag =true;
for(var i=0;i<j_tbs.length;i++){
if(!j_tbs[i].checked){
flag=false;
break;
}
}
j_cbAll.checked = flag;
}
}
</script>
</body>
</html>