Multiple checkboxes hiding rows if TD doesn't contain value

I have a table containing td's with text. I want to be able to filter each row based on checkbox values. For example, if I select only one checkbox, it will look and filter out the rows that don't contain the value of the checkbox. If I select two checkboxes, it will filter and only show the rows that contain both values of the checked boxes. I can get it to partially work, but it will show the row if a checkbox value is present, regardless if a second checkbox is selected. How can I get it to further filter when additional checkboxes are selected?

Here is the code I have so far.

jQuery('document').ready(function(){
var $ = jQuery
$(":checkbox").click(function() {
var showAll = true;
$('tr').not('.first').hide();
var checkedValues = $(":checkbox:checked").map(function() {
    return this.value;
}).get();

$("tbody tr").hide();
for (var i = 0; i < checkedValues.length; i++) {
    showAll = false;
    $("td:contains('" + checkedValues[i] + "')").parent("tr").show();
}

if(showAll){
    $('tr').show();
}
});
});

Answers 1

  • Assuming that you only need rows that contains all of the values of the checked checkboxes.

    Try this:

    $(":checkbox").click(function() {
      var checkedValues = $(":checkbox:checked").map(function() {
        return this.value;
      }).get();
    
      $("tbody tr")
      .hide()
      .filter(function() {
      	var
        $tr = $(this),
        $tds = $.map(checkedValues, function(v) {
        	return $tr.find('td:contains(' + v + ')').length > 0 ? v : null;
        });
        return $tds.length == checkedValues.length;
      }).show();
    
      if (checkedValues.length == 0) {
        $('tr').show();
      }
    });
    #searchTable {
      border-collapse: collapse;
    }
    
    #searchTable td {
      border: 1px solid #333;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="checkbox" id="buh" value="buh">
    <label for="buh">buh</label>
    <input type="checkbox" id="dum" value="dum">
    <label for="dum">dum</label>
    <input type="checkbox" id="tss" value="tss">
    <label for="tss">tss</label>
    
    <table id="searchTable">
      <thead>
        <tr class="first">
          <td>probably</td>
          <td>are</td>
          <td>headers</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>buh</td>
          <td></td>
          <td></td>
        </tr>
        <tr>
          <td></td>
          <td>dum</td>
          <td></td>
        </tr>
        <tr>
          <td></td>
          <td></td>
          <td>tss</td>
        </tr>
        <tr>
          <td>buh</td>
          <td>dum</td>
          <td></td>
        </tr>
        <tr>
          <td></td>
          <td>dum</td>
          <td>tss</td>
        </tr>
        <tr>
          <td>buh</td>
          <td></td>
          <td>tss</td>
        </tr>
      </tbody>
    </table>


Related Articles