Introduction
In this post I will tell you how you can filter an HTML table using jQuery.
Using the code
All you need is create an HTML table and a textbox. The search function will be called on the textbox's onkeyup
event. Here is the function:
function Search() {
var value = $('input[id$="txtSearch"]').val();
if (value) {
$('#MyTable tr:not(:first)').each(function () {
var index = -1;
$(this).children('td').each(function () {
var text = $(this).text();
if (text.toLowerCase().indexOf(value.toLowerCase()) != -1) {
index = 0;
return false;
}
});
if (index == 0)
$(this).show();
else
$(this).hide();
});
}
else
$('#MyTable tr').show();
}
<input type="text" onkeyup="Search()" id="txtSearch" />
This function checks if the input criteria matches the text of any td
, it makes the row visible and if input criteria is not found
in whole row, then that row is hidden. If there is no value in input criteria all table rows are displayed.
This is a very basic code. Any suggestions will be greatly appreciated.