JS form select all and reverse select

Effect picture:

  • When all items in the form are selected, select all at the top is automatically checked;
  • When there are options in the form that are not selected, the top selection will be automatically cancelled;
  • When all the top boxes are checked, all items in the form are automatically checked.

Insert picture description here

<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>

Guess you like

Origin blog.csdn.net/Guoxuxinwen/article/details/104577411