How to search based on multiple column using basic jQuery

I am working on table layout with search on top of each row.

https://codepen.io/chiragjain94/pen/rNLBbNG

I want to search for “897” in first column and in second column I want to enter “Card” The result should be => 553492-987 897 Traveller Card

But that is not the result I get.

$(document).on('input', '.filter-table', function() {
  var searchKey = $(this).val().toLowerCase();
  var tableName = $(this).attr('data-table-id');
  var columnId = $(this).attr('data-column-id');
  $("#" + tableName + " tbody td:nth-child(" + columnId + ")").filter(function() {
    $(this).parent().toggle($(this).text().toLowerCase().indexOf(searchKey) > -1);
  });
});
<table class="table mb-0  table-striped" id="selectedList">
  <thead>
    <tr>
      <td colspan="2">Table</td>
    </tr>
    <tr class="search-fields" style="">
      <td><input type="search" class="form-control search-input filter-table valid" data-table-id="selectedList" data-column-id="1" placeholder="Search column 1..." autocomplete="off"></td>
      <td><input type="search" class="form-control search-input filter-table" data-table-id="selectedList" data-column-id="2" placeholder="Search column 2" autocomplete="off"></td>
    </tr>
  </thead>
  <tbody>
    <tr class="search-row">
      <td>Card 126 897</td>
      <td>Big Bank 2015</td>
    </tr>

    <tr class="search-row">
      <td>553492-987 897</td>
      <td>Traveller Card</td>
    </tr>

    <tr class="search-row" style="">
      <td>Card 67920</td>
      <td>Credit Card 8729
      </td>
    </tr>
  </tbody>

</table>

Additional condition, once I clear any of the search input, my result table should still show result based on other search input.

Answer

Instead of filtering by comparing each input value separately, you should take both in account. You can do it this way:

$(document).on('input', '.filter-table', function () {
 var tableName = $(this).attr('data-table-id');
 var searchKey1 = $("[data-column-id='1']").val().toLowerCase();
 var searchKey2 = $("[data-column-id='2']").val().toLowerCase();


$("#" + tableName + " tbody tr").filter(function () {
 var columnSearch1 = !searchKey1 || 
 $(this).children().eq(0).text().toLowerCase().indexOf(searchKey1) > -1;

 var columnSearch2 = !searchKey2 ||  
 $(this).children().eq(1).text().toLowerCase().indexOf(searchKey2) > -1;

 $(this).toggle(columnSearch1 && columnSearch2);
 });

});

Link to example

Leave a Reply

Your email address will not be published. Required fields are marked *