d
Amit DhamuSoftware Engineer
 

Filter Table Results

2 minute read 00000 views

The function below will allow you to use a text input to filter the results of a table with live updating of the table rows.

HTML

<!-- Your Table -->
<table class="default-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Gender</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Smith</td>
      <td>30</td>
      <td>Male</td>
    </tr>
    <tr>
      <td>Mary Jane</td>
      <td>25</td>
      <td>Female</td>
    </tr>
    <tr>
      <td>Steve Jackson</td>
      <td>45</td>
      <td>Male</td>
    </tr>
  </tbody>
</table>

<!-- Filter Text Input -->
<input id="filter-input" type="text" placeholder="Filter Table Here" />

Function Setup and Execution

function filterTable(search, table) {
  $(table + ' tr:hidden').show()

  $.each(search, function () {
    $(table + " tr:visible .indexColumn:not(:contains('" + this + "'))")
      .parent()
      .hide()
  })
}

$(document).ready(function () {
  $('table tr:has(td)').each(function () {
    var t = $(this).text().toLowerCase()
    $("<td class='indexColumn'></td>").hide().text(t).appendTo(this)
  })

  $('#filter-input').keyup(function () {
    var search_term = $(this).val().toLowerCase().split(' ')
    filterTable(search_term, '.default-table')
  })
})