سؤال

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>
هل كانت مفيدة؟

المحلول

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/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top