效果图:
- 当表单内所有均被选择时,最上方全选自动勾选;
- 当表单内有选项未被选择时,最上方全选自动取消;
- 当最上方全选勾选时,表单内所有均被自动勾选。
<body>
<div class="wrap">
<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>iPhone8</td>
<td>8000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPad Pro</td>
<td>5000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPad Air</td>
<td>2000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Apple Watch</td>
<td>2000</td>
</tr>
</tbody>
</table>
<input type="button" value=" 反 选 " id="btn">
</div>
<script type="text/javascript">
//1.获取元素
var j_cbAll = document.getElementById('j_cbAll');
var j_tbs = document.getElementById('j_tb').getElementsByTagName('input');
j_cbAll.onclick = function() {
//this.checked若为true则表示选中该选择框
for (var i = 0 ; i < j_tbs.length; i++) {
j_tbs[i].checked = this.checked;
}
}
//2.下面全部选中,上面选中
for (var i = 0; i < j_tbs.length; i++){
j_tbs[i].onclick = function() {
var flag = true;
for(var i = 0 ; i < j_tbs.length; i++){
console.log(!j_tbs[i].ckecked);
if (!j_tbs[i].checked) {
flag = false;
}
}
// console.log(flag);
j_cbAll.checked = flag;
}
}
</script>
</body>
来源:CSDN
作者:GGxGx
链接:https://blog.csdn.net/Guoxuxinwen/article/details/104577411