jquery实现多选框全选、反选、自动全选、自动取消全选


<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>title>

head>
<body>
  
<div class="wrap">
  <table border="1px solid">
    <thead>
    <tr>
      <th>
        <input type="checkbox" id="allBtn"/>
      th>
      <th>菜名th>
      <th>饭店th>
    tr>
    thead>
    <tbody id="j_tb">
    <tr>
      <td>
        <input type="checkbox" id="itemBox"/>
      td>
      <td>红烧肉td>
      <td>田老师td>
    tr>
    <tr>
      <td>
        <input type="checkbox" id="itemBox"/>
      td>
      <td>西红柿鸡蛋td>
      <td>田老师td>
    tr>
    <tr>
      <td>
        <input type="checkbox" id="itemBox"/>
      td>
      <td>红烧狮子头td>
      <td>田老师td>
    tr>
    <tr>
      <td>
        <input type="checkbox" id="itemBox"/>
      td>
      <td>日式肥牛td>
      <td>田老师td>
    tr>
    
    tbody>
  table>
  
div>
<script src="jquery-2.1.1.min.js">script>
<script>
  $(function () {
      

    $("img").attr("src", "11111");
    
    //思路是,点击全选按钮后全选按钮状态是已选中,
    //那么代表之前全选按钮时未选中状态,所以其它
    //所有按钮设为选中状态,反之,其它所有按钮取消全选状态
     $("#allBtn").click(function(){
      
         var ischecked = $(this).prop('checked');
         if(ischecked == true){
      
           $('input').prop('checked',true);
         }else{
      
          $('input').prop('checked',false);
         }

     });

     $('input#itemBox').click(function(){
      
        //补充:如果我们手动选中了除了全选按钮外的全部按钮,那么全选按钮自动被选定
        //思路是,根据全部多选框的个数(排除一个总选按钮)和已选中多选框的个数对比,一致则总选按钮被自动选定
        var checkedLen = $('input#itemBox:checked').length;
        var allInput = $('input#itemBox').length;
        if(allInput == checkedLen){
      
          $("#allBtn").prop('checked',true);
        }else{
      
          $("#allBtn").prop('checked',false );

        }


     })
  });
script>

body>
html>

你可能感兴趣的:(前端(js为主),checkbox,js,jq,jquery,vue)