dimanche 19 février 2017

Hide rows with multiple checkboxes

I have a HTML table in which I want to hide/show rows based on multiple checkboxes.

When a checkbox is checked, (based on a text criterion) some rows are hiding, if it's unchecked, all rows are shown. If 2 or more checkboxes are checked, all rows are hiden, except those which met the criteria from all selected checkboxes. But if I uncheck any of the checboxes, all rows are shown.

My question is, when I uncheck one of the checkboxes, how can I show ONLY the rows that met the criteria from all current selected checkboxes?

For better understanding, I need to check which rows are already hidden by the other checkboxes and not show them when a checkbox is unchecked.

Example of working case: checkbox1 and checkbox2 are selected: only row1 is shown, if I uncheck checkbox2, only row1 and row3 must be shown

HTML:

<label><input type="checkbox" id="checkbox1">Teacher</label>
<label><input type="checkbox" id="checkbox2">Tennis</label>
<label><input type="checkbox" id="checkbox3">Married</label>

    <table id="table" border="1">
    <thead>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Profession</th>
        <th>Hobby</th>
        <th>Married</th>
    </thead>
    <tbody>
    <tr id="row1">
      <td>John</td>
      <td>Doe</td>
      <td>Teacher</td>
      <td>Tennis</td>
      <td>Yes</td>
    </tr>
    <tr id="row2">
      <td>Eve</td>
      <td>Jackson</td>
      <td>Doctor</td>
      <td>Darts</td>
      <td>No</td>
    </tr>
    <tr id="row3">
      <td>Adam</td>
      <td>Johnson</td>
      <td>Teacher</td>
      <td>Skydiving</td>
      <td>Yes</td>
    </tr>
     <tr id="row4">
      <td>Nina</td>
      <td>Pursuit</td>
      <td>Lawyer</td>
      <td>Tennis</td>
      <td>Yes</td>
    </tr>
    </tbody>
    </table> 

jQuery:

$(document).ready(function () {
    $('#checkbox1').change(function () {
            for (var i = 0; i < 5; i++) {
                if ((this.checked) && $("#table #row"+i+" td:nth-child(3):not(:contains('Teacher'))").length){
                    $('#row'+i).fadeOut('slow');
                } 
                if (!this.checked) $('#row'+i).fadeIn('slow');
                }
    });

    $('#checkbox2').change(function () {
            for (var i = 0; i < 5; i++) {
                if ((this.checked) && $("#table #row"+i+" td:nth-child(4):not(:contains('Tennis'))").length){
                    $('#row'+i).fadeOut('slow');
                } 
                if (!this.checked) $('#row'+i).fadeIn('slow');
                }
    });

    $('#checkbox3').change(function () {
            for (var i = 0; i < 5; i++) {
                if ((this.checked) && $("#table #row"+i+" td:nth-child(5):not(:contains('Yes'))").length){
                    $('#row'+i).fadeOut('slow');
                } 
                if (!this.checked) $('#row'+i).fadeIn('slow');
                }
    });
});

JSFiddle DEMO




Aucun commentaire:

Enregistrer un commentaire