jQuery Live Search Filter for a Table

This code filters the rows of a table while the user types. It checks all the cells of a row and ignores the upper and lower case.

HTML

<input type="text" id="table-search" placeholder="Search...">
<table id="students">
  <thead><tr><th>Name</th><th>City</th></tr></thead>
  <tbody>
    <tr><td>Anita Rao</td><td>Delhi</td></tr>
    <tr><td>Ravi Kumar</td><td>Pune</td></tr>
    <tr><td>Maya Singh</td><td>Delhi</td></tr>
    <tr><td>Manish Das</td><td>Kolkata</td></tr>
  </tbody>
</table>
<p id="no-result" style="display:none">No result found</p>

jQuery code

$('#table-search').on('input', function () {
  var term = $(this).val().toLowerCase().trim();
  var shown = 0;

  $('#students tbody tr').each(function () {
    var match = $(this).text().toLowerCase().indexOf(term) !== -1;
    $(this).toggle(match);
    if (match) shown++;
  });

  $('#no-result').toggle(shown === 0);
});

function search(text) {
  $('#table-search').val(text).trigger('input');
  console.log('"' + text + '": ' + $('#students tbody tr').filter(function () { return $(this).css('display') !== 'none'; }).length + ' row(s), message: ' + $('#no-result').css('display'));
}

search('delhi');
search('ma');
search('xyz');
search('');
Console output

"delhi": 2 row(s), message: none
"ma": 3 row(s), message: none
"xyz": 0 row(s), message: block
"": 4 row(s), message: none

How it works

  • $(this).text() of a row has the text of all its cells together, so we search in all columns.
  • .toggle(match) shows the row if it matches and hides it if not.
  • The message “No result found” is shown only when no row is visible.
  • The test function counts the rows which are not hidden.
Note: For a big table (thousands of rows), wait a short time after the last key before you filter, or filter on the server. See jQuery each().

Learn more about the similar topics:
Tutorials
jQuery Events
jQuery Mouse, Keyboard and Form Events
jQuery Event Delegation
Exercises & Assignments
Write jQuery code to hide a paragraph when a button is clicked
Write jQuery code to highlight the clicked list item
Write jQuery code to remove a list item when it is clicked
Write jQuery code to change the image source when a thumbnail is clicked
Write jQuery code to show the text typed in an input field
Write jQuery code to filter a list while typing in a search box
Write jQuery code to count the clicks of a button
Interview Questions & Answers
What is the on() method in jQuery?
What is the difference between click() and on(‘click’) in jQuery?
What is event bubbling in jQuery and how do you stop it?
What is event.preventDefault() in jQuery?
What is event delegation in jQuery and why is it useful?
What is the difference between bind(), live(), delegate() and on() in jQuery?