【问题标题】:Filter table with checkboxes带有复选框的过滤表
【发布时间】:2015-04-30 16:24:17
【问题描述】:

我正在过滤带有复选框的表格。 我的代码在某些方面运行良好。

如果结果满足所有检查,我希望它过滤结果,而不是一个。

基于:How can I add to my table filter to allow for multiple checkbox selections, as well as filtering from a dropdown?

我的Example

$("input[name='filterStatus'], select.filter").change(function() {
  var classes = [];
  var stateClass = ""

  $("input[name='filterStatus']").each(function() {
    if ($(this).is(":checked")) {
      classes.push('.' + $(this).val());
    }
  });

  if (classes == "" && stateClass == "") {
    // if no filters selected, show all items
    $("#StatusTable tbody tr").show();
  } else {
    // otherwise, hide everything...
    $("#StatusTable tbody tr").hide();

    // then show only the matching items
    rows = $("#StatusTable tr" + stateClass).filter(classes.length ? classes.join(',') : '*');
    if (rows.size() > 0) {
      rows.show();
    }
  }

});
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>

<body>
  <form name="FilterForm" id="FilterForm" action="" method="">
    <input type="checkbox" name="filterStatus" value="ISO " />
    <label for="filter_1">ISO</label>
    <input type="checkbox" name="filterStatus" value="AMCA" />
    <label for="filter_2">AMCA</label>
    <input type="checkbox" name="filterStatus" value="UL" />
    <label for="filter_3">UL</label>
  </form>

  <table border="1" id="StatusTable">
    <thead>
      <tr>
        <th>Name</th>
        <th>ISO</th>
        <th>AMCA</th>
        <th>UL</th>
      </tr>
      <tbody>
        <tr class="ISO">
          <td class="Name">Name1</td>
          <td class="ISO">&#x2713;</td>
          <td class="AMCA">&nbsp;</td>
          <td class="UL">&nbsp;</td>
        </tr>
        <tr class="ISO AMCA">
          <td class="Name">Name2</td>
          <td class="ISO">&#x2713;</td>
          <td class="AMCA">&#x2713;</td>
          <td class="UL">&nbsp;</td>
        </tr>
        <tr class="ISO AMCA UL">
          <td class="Name">Name3</td>
          <td class="ISO">&#x2713;</td>
          <td class="AMCA">&#x2713;</td>
          <td class="UL">&#x2713;</td>
        </tr>

      </tbody>
  </table>
  <script></script>
</body>

</html>

【问题讨论】:

  • 如果您创建了一个 Fiddle 或将代码发布到您的示例中并附上您的问题,这会让其他人更容易帮助您。
  • 该行是否总是包含其单元格的正确类列表?
  • 是的,我可以为该行分配类
  • 请不要忘记将您喜欢的答案标记为正确答案。
  • 谢谢,我看了之后会的

标签: jquery checkbox html-table


【解决方案1】:

修改你的 jQuery 循环遍历每一行的地方。创建一个标签变量来存储该行是否显示,默认设置为true

现在,当您遍历每一行时,您还将遍历您正在检查的每个类。如果在任何时候循环测试失败,请将您的 show 变量设置为 false 以保持该行隐藏。

$("input[name='filterStatus']").change(function () {
    var classes = [];

    $("input[name='filterStatus']").each(function () {
        if ($(this).is(":checked")) { classes.push('.' + $(this).val()); }
    });

    if (classes == "") { // if no filters selected, show all items
        $("#StatusTable tbody tr").show();
    } else { // otherwise, hide everything...
        $("#StatusTable tbody tr").hide();

        $("#StatusTable tr").each(function () {
            var show = true;
            var row = $(this);
            classes.forEach(function (className) {
                if (row.find('td' + className).html() == '&nbsp;') { show = false; }
            });
            if (show) { row.show(); }
        });
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    </head>
    
    <body>
        <form name="FilterForm" id="FilterForm" action="" method="">
            <input type="checkbox" name="filterStatus" value="ISO " />
            <label for="filter_1">ISO</label>
            <input type="checkbox" name="filterStatus" value="AMCA" />
            <label for="filter_2">AMCA</label>
            <input type="checkbox" name="filterStatus" value="UL" />
            <label for="filter_3">UL</label>
        </form>
        <table border="1" id="StatusTable">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>ISO</th>
                    <th>AMCA</th>
                    <th>UL</th>
                </tr>
                <tbody>
                    <tr class="ISO">
                        <td class="Name">Name1</td>
                        <td class="ISO">&#x2713;</td>
                        <td class="AMCA">&nbsp;</td>
                        <td class="UL">&nbsp;</td>
                    </tr>
                    <tr class="ISO AMCA">
                        <td class="Name">Name2</td>
                        <td class="ISO">&#x2713;</td>
                        <td class="AMCA">&#x2713;</td>
                        <td class="UL">&nbsp;</td>
                    </tr>
                    <tr class="ISO AMCA UL">
                        <td class="Name">Name3</td>
                        <td class="ISO">&#x2713;</td>
                        <td class="AMCA">&#x2713;</td>
                        <td class="UL">&#x2713;</td>
                    </tr>
                </tbody>
        </table>
        <script></script>
    </body>

</html>

【讨论】:

    【解决方案2】:

    在下面这段代码的帮助下。您可以根据选中的复选框过滤表格,当您没有选择任何复选框时,它将显示所有记录。

    $(document).ready(function(){
      $(".name").on("click", function() {
      name_list = []
      $("#myTable tr").hide()
      var flag = 1
      $("input:checkbox[name=name]:checked").each(function(){
      		flag = 0;
        	var value = $(this).val().toLowerCase();
          	$("#myTable tr").filter(function() {
                if($(this).text().toLowerCase().indexOf(value) > -1)
            		$(this).show()
        	});
     	 });
        if(flag == 1)
        	$("#myTable tr").show()
      });
    });
    table {
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 100%;
    }
    td, th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 8px;
    }
    
    tr:nth-child(even) {
      background-color: #dddddd;
    }
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    
    </script>
    <style>
    </style>
    </head>
    <body>
    
    <h2>Filterable Table</h2>
    
    <input type="checkbox" class="name" name="name" value="John" />John
    <input type="checkbox" class="name" name="name" value="July" />July
    <br><br>
    
    <table>
      <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
      </thead>
      <tbody id="myTable">
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@mail.com</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@greatstuff.com</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@greatstuff.com</td>
      </tr>
      <tr>
        <td>Anja</td>
        <td>Ravendale</td>
        <td>a_r@test.com</td>
      </tr>
      </tbody>
    </table>
      
    <p>Note that we start the search in tbody, to prevent filtering the table headers.</p>
    
    </body>
    </html>

    【讨论】:

    • 不错的解决方案。我觉得我们也可以使用.toggle() 函数获得相同的效果(用于捕获复选框 checkedunchecked 状态)。
    【解决方案3】:

    演示:https://jsfiddle.net/erkaner/u12te5jb/

    这是我的解决方案

    $("input[name='filterStatus']").change(function () {
    
    var count1 = $("input[name='filterStatus']:checked").length;//number of checked items
    
    $("#StatusTable>tbody> tr").each(function () {//for each row
        var count2 = 0;//this is the count of td that has ✓ 
        var row = $(this);//the current row
        $("input[name='filterStatus']:checked").each(function () {//for each checked item
            var inputVal = $(this).val();//get the value, which is class of the corresponding td, see below
            if (row.find('.' + inputVal).html().indexOf("✓") >= 0)//if the td that corresponds to the selected checkbox contains ✓
                count2++;//then increase
        });
    
        if (count1 == count2) //if counts match
            row.show();//then show
        else 
            row.hide();
        });
    });
    

    【讨论】:

    • 我可以在小提琴中使用它。 lorencook.com/example/table-1.html 但我的演示很糟糕
    • 你能把&lt;script&gt;&lt;/script&gt;的部分移到头部而不是身体吗?
    【解决方案4】:

    jQuery Scrollable, Sortable, Filterable table 引用 DataTables 库,在 https://datatables.net/news/ 下有 2019 年 2 月 8 日的条目:

    Yevgen Gorbunkov 为 DataTables 编写了一个非常不错的插件,它 显示来自标题的下拉过滤,允许联合搜索 被执行。来源在GitHub

    我已将示例从 https://jsfiddle.net/ahqso1j5/ 转换为此处的 sn-p:

    // Plug-in source available at:
    // https://github.com/ygorbunkov/datatables-multiple-criteria-filter
    $(document).ready(function () {
    //Source data definition	
    var tableData = [{
    		name: 'Clark Kent',
    		city: 'Metropolis',
    		race: 'cryptonian'
    	}, {
    		name: 'Bruce Wayne',
    		city: 'Gotham',
    		race: 'human'
    	}, {
    		name: 'Steve Rogers',
    		city: 'New York',
    		race: 'superhuman'
    	}, {
    		name: 'Peter Parker',
    		city: 'New York',
    		race: 'superhuman'
    	}, {
    		name: 'Thor Odinson',
    		city: 'Asgard',
    		race: 'god'
    	}, {
    		name: 'Jonathan Osterman',
    		city: 'New York',
    		race: 'superhuman'
    	}, {
    		name: 'Walter Kovacs',
    		city: 'New Jersey',
    		race: 'human'
    	}, {
    		name: 'Arthur Curry',
    		city: 'Atlantis',
    		race: 'superhuman'
    	}, {
    		name: 'Tony Stark',
    		city: 'New York',
    		race: 'human'
    	}, {
    		name: 'Scott Lang',
    		city: 'Coral Gables',
    		race: 'human'
    	}, {
    		name: 'Bruce Banner',
    		city: 'New York',
    		race: 'superhuman'
    	}
    ];
    //DataTable definition	
    window.dataTable = $('#mytable').DataTable({
    		sDom: 'tF',
    		data: tableData,
    		columns: [{
    				data: 'name',
    				title: 'Name'
    			}, {
    				data: 'city',
    				title: 'City'
    			}, {
    				data: 'race',
    				title: 'Race'
    		}]
    });
    });
    <!doctype html>
    <html>
    <head>
      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
      <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
      <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/ygorbunkov/datatables-multiple-criteria-filter@master/js/mFilter.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
      <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/ygorbunkov/datatables-multiple-criteria-filter@master/css/mFilter.css">
    </head>
    <body>
      <table id="mytable"></table>
    </body>
    </html>

    【讨论】:

      【解决方案5】:

      我正在这样做,代码会显示选中的复选框行,

       $('#btnReconcile').click(function () {
                  $("#tblReconcilReportDetails>tbody> tr").each(function () {
                      var row = $(this);
                      var isChecked = $(this).find('td').eq(0).find('input[type="checkbox"].chkReconcil').is(':checked');
                      if (isChecked) {
                          row.show();
                      } else {
                          row.hide();
                      }
                  });
              });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 2023-04-05
        • 2019-09-13
        • 2011-06-28
        相关资源
        最近更新 更多