JS Basics - Form Select All and Unselect All

Angle 1: Click the Select All button, and all the flotation items below are selected.
Case analysis:
Let the checked attribute (checked state) of all the check boxes below follow the Select All button.
insert image description here

<script>
var j_cbAll=document.getElementById('j_cbAll');//全选按钮
var j_tbs=document.getElementById('j_tbs').getElementsByTagName('input');
//注册事件
j_cbAll.onclick=function(){
    
    
//this.checked可以得到当前复选框的选中状态,如果是true就是选中,如果是false就是未选中
for(var i=0;i<j_tbs.length;i++){
    
    

j_tbs[i].checked=this.checked;//让下面的复选框和控制所有复选框的全选按钮的checked相同。

}
}
</script>

Angle 2: If all the checkboxes below are selected, the select all button above will be automatically checked.
Case analysis: Bind click events to all the checkboxes below. Every time you click, you must cycle through all the checkboxes below. Whether the box is unchecked, if there is an unchecked box, the above selection will not be selected. A variable can be set to control whether select all is checked.

<script>
	var j_cbAll=document.getElementById('j_cbAll');//全选按钮
	var j_tbs=document.getElementById('j_tbs').getElementsByTagName('input');
	for(var i=0;i<j_tbs.length;i++){
    
    
		j_tbs.onclick=function(){
    
    
		//flag控制全选按钮是否选中
		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>

Guess you like

Origin blog.csdn.net/qq_44114147/article/details/122888866