filter certain TR based on checkbox checked

旧城冷巷雨未停 提交于 2019-12-24 23:03:12

问题


Please help me as I am still trying to grasp the jQuery coding. I have this data and would like to filter it based on users' check box selection as the html code below.

.All rows are displayed when nothing is checked.

.All rows are displayed when all check boxes checked

.Only rows that meet selected criteria are displayed. For example,

a. When 2GB checked, only 2GB rows displayed.

b. When Shipping and 2GB checked, only Memory3 is displayed

<input type="checkbox" >1GB<br/>
<input type="checkbox" >2GB<br/>
<input type="checkbox" >4GB<br/>
<input type="checkbox" >1000MHz<br/>
<input type="checkbox" >1333MHz<br/>
<input type="checkbox" >Discontinued<br/>
<input type="checkbox" >Shipping<br/>
<br /><br />

<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla">
<caption>bla bla</caption>
<thead>
    <tr id="ProductID">
        <th>Product Number</th>
        <th>Status</th>
        <th>Capacity</th>
        <th>Speed</th>
    </tr>
</thead>
<tbody>
    <tr id="Memory1">
        <td>Memory1</td>
        <td>Shipping</td>
        <td>1GB</td>
        <td>1333MHz</td>
    </tr>
    <tr id="Memory2">
        <td>Memory2</td>
        <td>Discontinued</td>
        <td>1GB</td>
        <td>1000MHz</td>
    </tr>
    <tr id="Memory3">
        <td>Memory3</td>
        <td>Shipping</td>
        <td>2GB</td>
        <td>1333MHz</td>
    </tr>
    <tr id="Memory4">
        <td>Memory4</td>
        <td>Discontinued</td>
        <td>4GB</td>
        <td>1000MHz</td>
    </tr>
    <tr id="Memory5">
        <td>Memory5</td>
        <td>Shipping</td>
        <td>4GB</td>
        <td>1333MHz</td>
    </tr>
</tbody>

回答1:


Was feeling a bit generous, the below code does the following

  1. On checkbox change, map an array of selected values
  2. Iterate selected values and find td containing said value
  3. Show parent tr of selected value

    $(":checkbox").change(function() {
        var checkedValues = $(":checkbox:checked").map(function() {
            return this.value;
        }).get();
    
        $("tbody tr").hide();
        for (var i = 0; i < checkedValues.length; i++) {
            $("tbody tr td:contains('" + checkedValues[i] + "')").parent("tr").show();
        }
    });
    

Demo: http://jsfiddle.net/kXNAg/



来源:https://stackoverflow.com/questions/19776160/filter-certain-tr-based-on-checkbox-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!