Common js/jQuery operations: Frequently asked questions about jQuery operation check boxes

1. Some other common basic operations of js/jQuery

2. Select all/unselect all questions

2.1 Effect

  • as follows:
    Insert image description here

2.2 Implementation code

2.2.1 Simple js implementation

  • as follows:
    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title></title>
    	</head>
    	<body>
    		
    		<form method="post" action="">
    			
    			您想饲养的狗狗有?
    			<input type="checkbox" id="checkAllOrNo"/>全选/全不选
    			 
    			<br />
    			<input type="checkbox" name="items" value="边牧"/>边牧
    			<input type="checkbox" name="items" value="柯基"/>柯基
    			<input type="checkbox" name="items" value="秋田犬"/>秋田犬
    			<input type="checkbox" name="items" value="金毛"/>金毛
    			
    			<br />
    			<input type="button" id="checkAll" value="全选"/>
    			<input type="button" id="checkNoOne" value="全不选"/>
    			<input type="button" id="fanxuan" value="反选"/>
    			<input type="button" id="btnAllOrNO" value="全选/全不选"/>
    			<input type="button" id="commit" value="提交"/>
    			
    		</form>
    		
    		<script type="text/javascript">
    			
    			//1. 全选
    			var all = document.getElementById("checkAll");
    			function funAll(){
            
            
    				var box = document.getElementsByName("items");
    				for(var i =0;i<box.length;i++){
            
            
    					// alert(box[i].value);
    					box[i].checked = true;
    				}
    			}
    			all.onclick = funAll;
    			
    			//2.全不选
    			var allNo = document.getElementById("checkNoOne");
    			function funAllNo(){
            
            
    				var box = document.getElementsByName("items");
    				for(var i =0;i<box.length;i++){
            
            
    					box[i].checked = false;
    				}
    			}
    			allNo.onclick = funAllNo;
    			
    			//3.反选(直接取反)
    			var fan = document.getElementById("fanxuan");
    			fan.onclick = function(){
            
            
    				var box = document.getElementsByName("items");
    				for(var i =0;i<box.length;i++){
            
            	
    					// if(box[i].checked == false){
            
            
    					// 	box[i].checked = true;
    					// }else{
            
            
    					// 	box[i].checked = false;
    					// }
    					//可以将整个if else优化为,如下:
    					box[i].checked = !box[i].checked;//直接取反
    				}
    			}
    			
    			//4.全选/全不选----按钮操作
    			var btn_check_all = document.getElementById("btnAllOrNO");
    			btn_check_all.onclick = function(){
            
            
    				var boxes = document.getElementsByName("items");
    				var flag = false;//false-全不选  true-全选
    				for(var i =0; i<boxes.length; i++){
            
            
    					if(boxes[i].checked == false){
            
            
    						flag = true;//只要存在没有选中的话,就进行反选
    						break;
    					}
    				}
    				// alert(flag);
    				if(flag){
            
            
    					//执行全选函数
    					funAll();
    				}else{
            
            
    					//执行全不选函数
    					funAllNo();
    				}
    			}
    			
    			//5 全选/全不选——复选框操作
    			//5.1 点击全选复选框
    			var checkAllOrNo_2 = document.getElementById("checkAllOrNo");//复选框全选/全不选
    			checkAllOrNo_2.onclick = function(){
            
            
    				var box = document.getElementsByName("items");
    				for(var i =0; i<box.length; i++){
            
            
    					box[i].checked = this.checked;//即:选中状态与全选/全不选的复选框保持一致即可
    				}
    			}
    			
    			//5.2 点击各项目复选框
    			var boxAll_2 = document.getElementsByName("items");
    			for(var i=0;i<boxAll_2.length;i++){
            
            
    				boxAll_2[i].onclick = function(){
            
            
    					checkAllOrNo_2.checked = true;//点击任何一个复选框,全选复选框都先设置为选中状态
    					for(var i=0; i<boxAll_2.length; i++){
            
            
    						if(boxAll_2[i].checked == false){
            
            
    							//只要有没有选中,全选复选框就设置未选中
    							checkAllOrNo_2.checked = false;
    							break;
    						}
    					}
    				}
    			}
    			
    			//6.提交 获取选中的复选框
    			var data = document.getElementById("commit");
    			data.onclick = function(){
            
            
    				var box = document.getElementsByName("items");
    				var commmitData = "";
    				for(var i =0; i<box.length; i++){
            
            
    					if(box[i].checked == true ){
            
            
    						commmitData += box[i].value + ",";
    					}
    				}
    				var resultData = commmitData.substring(0,commmitData.length-1);
    				alert(resultData);
    			}
    			
    		</script>
    		
    		
    	</body>
    </html>
    

2.2.2 jQuery implementation

2.2.2.1 Pay attention to the syntax (difference between jQuery versions)
  • The following isselect allFor example, as follows:
    • Complex writing:
      //1. 全选---复杂点写法
      var all = document.getElementById("checkAll");
      function funAll(){
              
              
      	// 1.1 循环处理
      	$("input[name='items']").each(function(){
              
              
      		// 下面两种写法高低版本的jQuery均可以
      		// $(this).attr("checked",true); 
      		this.checked = true;
      
      		// prop 适合高版本的jQuery
      		//$(this).prop("checked",true);
               	});
      	// 1.2 直接根据name处理
      	// $("input[name='items']").attr("checked", true);
      
      	// 注意:prop 适合高版本的jQuery
      	// $("input[name='items']").prop("checked", true); 
      }
      all.onclick = funAll;
      
    • Optimized writing:
      $("#checkAll").click(function(){
              
              
      	$("input[name='items']").attr("checked", true);
      });
      
  • againSelect all/Deselect allFor example (non-button case), as follows:
    • Click to select all/unselect all - more complex logic:
      //5.1.1 点击 全选/全不选 复选框---使用多层this
      $("#checkAllOrNo").click(function(){
              
              
      	var parentFlag = this.checked;
      	$("input[name='items']").each(function(){
              
              
      		this.checked = parentFlag;
      	});
      });
      
    • Click Select All/Deselect All——Simple logic
      //5.1.2 点击 全选/全不选 复选框----使用s(":checked")
      $("#checkAllOrNo").click(function(){
              
              
      	$("input[name='items']").each(function(){
              
              
      		this.checked = $("#checkAllOrNo").is(":checked");
      	});
      });
      
    • Click on each item:
      //5.2 点击各项目复选框
      $("input[name='items']").each(function(){
              
              
      	$(this).click(function(){
              
              
      		// 点击任何一个复选框,全选/不全选 复选框都先设置为选中状态
      		$("#checkAllOrNo").attr("checked",true);
      		// 然后再循环所有的复选框,是否有未选中的
      		$("input[name='items']").each(function(){
              
              
      			if(!this.checked){
              
              
      				$("#checkAllOrNo").attr("checked",false);
      				return;
      			}
      		});
      	});
      });
      
  • For more information about the jQuery version, you can read the following article, which is introduced in 3.6.
    Some common operations of js/jQuery (js/jQuery obtains form element values ​​and clears element values) Various implementation methods) - attached with test examples, you can achieve the effect immediately.
2.2.2.2 Complete code implementation
  • The codes for each situation are as follows:
    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title></title>
    		<!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script> -->
    		<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    
    	</head>
    	<body>
    		
    		<form method="post" action="">
    			
    			您想饲养的狗狗有?
    			<input type="checkbox" id="checkAllOrNo"/>全选/全不选
    			 
    			<br />
    			<input type="checkbox" name="items" value="边牧"/>边牧
    			<input type="checkbox" name="items" value="柯基"/>柯基
    			<input type="checkbox" name="items" value="秋田犬"/>秋田犬
    			<input type="checkbox" name="items" value="金毛"/>金毛
    			
    			<br />
    			<input type="button" id="checkAll" value="全选"/>
    			<input type="button" id="checkNoOne" value="全不选"/>
    			<input type="button" id="fanxuan" value="反选"/>
    			<input type="button" id="btnAllOrNO" value="全选/全不选"/>
    			<input type="button" id="commit" value="提交"/>
    			
    		</form>
    		
    		<script type="text/javascript">
    			
    			//1. 全选---复杂点写法
    			var all = document.getElementById("checkAll");
    			function funAll(){
          
          
    				// 1.1 循环处理
    				$("input[name='items']").each(function(){
          
          
    					// 下面两种写法高低版本的jQuery均可以
    					// $(this).attr("checked",true); 
    					this.checked = true;
    
    					// prop 适合高版本的jQuery
    					//$(this).prop("checked",true);
                	});
    				// 1.2 直接根据name处理
    				// $("input[name='items']").attr("checked", true);
    
    				// 注意:prop 适合高版本的jQuery
    				// $("input[name='items']").prop("checked", true); 
    			}
    			// all.onclick = funAll;
    
    			// 1. 全选---简单点写法
    			$("#checkAll").click(function(){
          
          
    				$("input[name='items']").attr("checked", true);
    			});
    			
    			//2.全不选
    			$("#checkNoOne").click(function(){
          
          
    				$("input[name='items']").attr("checked", false);
    			});
    			
    			//3.反选(直接取反)
    			$("#fanxuan").click(function(){
          
          
    				$("input[name='items']").each(function(){
          
          
    					this.checked = !(this.checked);//直接取反
    				});
    			});
    			
    			//4.全选/全不选----按钮操作
    			$("#btnAllOrNO").click(function(){
          
          
    				var selectedNum = 0;//0-全不选  >0-全选
    				$("input[name='items']:not(:checked)").each(function(){
          
          
    					selectedNum ++;//计算没有选中的项目个数
    				});
    				if(selectedNum > 0){
          
          
    					// 只要存在没有选中的话,就进行全选
    					$("input[name='items']").attr("checked", true);
    				}else{
          
          
    					// 全不选
    					$("input[name='items']").attr("checked", false);
    				}
    			});
    			
    			//5 全选/全不选——复选框操作
    			//5.1.1 点击 全选/全不选 复选框---使用多层this
    			// $("#checkAllOrNo").click(function(){
          
          
    			// 	var parentFlag = this.checked;
    			// 	$("input[name='items']").each(function(){
          
          
    			// 		this.checked = parentFlag;
    			// 	});
    			// });
    
    			//5.1.2 点击 全选/全不选 复选框----使用s(":checked")
    			$("#checkAllOrNo").click(function(){
          
          
    				$("input[name='items']").each(function(){
          
          
    					// 选中状态与 全选/全不选 的复选框保持一致即可
    					this.checked = $("#checkAllOrNo").is(":checked");
    				});
    			});
    
    			//5.2 点击各项目复选框
    			$("input[name='items']").each(function(){
          
          
    				$(this).click(function(){
          
          
    					// 点击任何一个复选框,全选/不全选 复选框都先设置为选中状态
    					$("#checkAllOrNo").attr("checked",true);
    					// 然后再循环所有的复选框,是否有未选中的
    					$("input[name='items']").each(function(){
          
          
    						if(!this.checked){
          
          
    							$("#checkAllOrNo").attr("checked",false);
    							return;
    						}
    					});
    				});
    			});
    			
    			//6.提交 获取选中的复选框
    			// 6.1 拼接字符串写法
    			$("#commit").click(function(){
          
          
    				var commmitData = "";
    				$("input[name='items']:checked").each(function(){
          
          
    					commmitData += $(this).val() + ",";
    				});
    				var resultData = commmitData.substring(0,commmitData.length-1);
    				alert(resultData);
    			});
    
    			// 6.2 数组写法
    			$("#commit").click(function(){
          
          
    				var commmitData = [];
    				$("input[name='items']:checked").each(function(){
          
          
    					commmitData.push($(this).val());
    				});
    				alert(commmitData);
    			});
    			
    		</script>
    		
    	</body>
    </html>
    

3. jQuery realizes click on row tr to realize checkBox selection + page turning check problem

3.1 jQuery implements clicking row tr to obtain the value of checkBox in td

3.1.1 Method 1

  • The implementation code is as follows:
    // 1.1 点击tr获取tr中是checkbox的td的值----方式1
    $("#dogs_data tr").each(function(){
          
          
        var current = $(this);
        current.click(function(){
          
          
            var box = $(this).find(":checkbox");
            console.log(box);
            console.log(box.val());
        });
    });
    
  • The effect is as follows:
    Insert image description here

3.1.2 Method 2

  • The implementation code is as follows:
    // 1.2 点击tr获取tr中是checkbox的td的值----方式2
    $("#dogs_data tr").each(function(){
          
          
        $(this).click(function(){
          
          
            var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
            console.log(box);
            console.log(box.value);//因为是标签,取值用.value
        });
    });
    
  • The effect is as follows:
    Insert image description here

3.2 jQuery implements clicking on row tr to implement checkBox selection or cancellation

3.2.1 When tr is clicked, the checkbox is selected or canceled

  • The implementation code is as follows:
    $("#dogs_data tr").each(function(){
          
          
        $(this).click(function(){
          
          
            var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
            box.checked = !box.checked;// 直接取反
        });
    });
    
  • The effect is as follows:
    Insert image description here

3.2.2 When clicking on the first line tr, select all or none

  • The implementation code is as follows:
    // 2.2 点击首行tr时(表头),实现全选或全不选
    $("#dogs_data tr:eq(0)").each(function(){
          
          
        $(this).click(function(){
          
          
            var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
            box.checked = !box.checked;// 直接取反
            $("input[name='dogIds']").each(function(){
          
          
                this.checked = box.checked;// 数据行的选中状态与首行的选中状态保持一致
            });
        });
    });
    
  • The effect is as follows:
    Insert image description here

3.2.3 When clicking on the non-first row tr (data list row), it will automatically switch between selecting all or not selecting all.

  • The implementation code is as follows:
    // 2.3 点击非首行tr时(数据列表行),全选或全不选自动切换
    $("#dogs_data tr:gt(0)").each(function(){
          
          
        $(this).click(function(){
          
          
            var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
            box.checked = !box.checked; // 数据行直接取反
            $("#checkAllOrNo").attr("checked",true);// 数行先设置选中
    
            // 然后循环数据行的checkbox,如果有未选中的,取消首行选中(为了少循环次数,直接从not(:checked)中循环)
            $("input[name='dogIds']:not(:checked)").each(function(){
          
          
                $("#checkAllOrNo").attr("checked",false);// 如果存在任意一个未选中,直接取消选中
                return;
            });
        });
    });
    
  • The effect is as follows (not a video, it is not very obvious, you need to test it yourself if you need it):
    Insert image description here

3.3 Page turning and checking questions

  • If you want to support page turning check, then cache each check in an input box on the page, and then add one after each check. This can be achieved by directly splicing with reference to the above value method. Here is No more words.

3.4 Attached is the full code of the above operation tr

  • as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script> -->
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    
        <style>
            table {
          
          
                border-collapse: collapse;
            }
            table tr th,td{
          
          
                border: 1px solid;
                width: 60px;
                text-align: center;
            }
    
            thead tr:hover{
          
          
                background-color: rgb(255, 127, 127);
            }
            tbody tr:hover{
          
          
                background-color: aquamarine;
            }
        </style>
    </head>
    <body>
    
    
    
        <table celllspacing="0" id="dogs_data">
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="checkAllOrNo" />
                    </th>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <input type="checkbox" name="dogIds" value="A1001"/>
                    </td>
                    <td>A1001</td>
                    <td>麦兜</td>
                    <td>3</td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" name="dogIds" value="A1002"/>
                    </td>
                    <td>A1002</td>
                    <td>贝塔</td>
                    <td>2</td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" name="dogIds" value="A1003"/>
                    </td>
                    <td>A1003</td>
                    <td>泡泡</td>
                    <td>6</td>
                </tr>
            </tbody>
        </table>
    
        <script>
            // 1.1 点击tr获取tr中是checkbox的td的值----方式1
            // $("#dogs_data tr").each(function(){
          
          
            //     var current = $(this);
            //     current.click(function(){
          
          
            //         var box = $(this).find(":checkbox");
            //         console.log(box);
            //         console.log(box.val());
            //     });
            // });
    
            // 1.2 点击tr获取tr中是checkbox的td的值----方式2
            // $("#dogs_data tr").each(function(){
          
          
            //     $(this).click(function(){
          
          
            //         var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
            //         console.log(box);
            //         console.log(box.value);// 因为是标签,取值用.value
            //     });
            // });
    
            // 2.1 点击 行tr 实现checkBox选中或取消
            // $("#dogs_data tr").each(function(){
          
          
            //     $(this).click(function(){
          
          
            //         var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
            //         box.checked = !box.checked;// 直接取反
            //     });
            // });
    
            // 2.2 点击首行tr时(表头),实现全选或全不选
            $("#dogs_data tr:eq(0)").each(function(){
          
          
                $(this).click(function(){
          
          
                    var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
                    box.checked = !box.checked;// 直接取反
                    $("input[name='dogIds']").each(function(){
          
          
                        this.checked = box.checked;// 数据行的选中状态与首行的选中状态保持一致
                    });
                });
            });
    
            // 2.3 点击非首行tr时(数据列表行),全选或全不选自动切换
            $("#dogs_data tr:gt(0)").each(function(){
          
          
                $(this).click(function(){
          
          
                    var box = this.firstElementChild.firstElementChild;//获取checkbox元素标签
                    box.checked = !box.checked; // 数据行直接取反
                    $("#checkAllOrNo").attr("checked",true);// 数行先设置选中
    
                    // 然后循环数据行的checkbox,如果有未选中的,取消首行选中(为了少循环次数,直接从not(:checked)中循环)
                    $("input[name='dogIds']:not(:checked)").each(function(){
          
          
                        $("#checkAllOrNo").attr("checked",false);// 如果存在任意一个未选中,直接取消选中
                        return;
                    });
                });
            });
    
        </script>
    </body>
    </html>
    

Guess you like

Origin blog.csdn.net/suixinfeixiangfei/article/details/134722886