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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |