Reputation: 721
I have one text input box
<input type="text" id="search" />
and multiple HTML-tables like this:
<table id="table1">
<thead>
<tr>
<th>Table1 title</th>
</tr>
<tr>
<th>Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Andrew</td>
<td>USA</td>
</tr>
<tr>
<td>John</td>
<td>Canada</td>
</tr>
</tbody>
</table>
I want to filter data depending on what user types in the input box.
Now my JS code is:
$(document).ready(function(){
$("#search").keyup(function(){
// When value of the input is not blank
if( $(this).val() != "")
{
// Show only matching TR, hide rest of them
$("#table1 > tbody > tr").hide();
$("#table1 td:contains-ci('" + $(this).val() + "')").parent("tr").show();
} else {
// When there is no input or clean again, show everything back
$("#table1 tbody > tr").show();
}
});
});
// jQuery expression for case-insensitive filter
$.extend($.expr[":"],
{
"contains-ci": function(elem, i, match, array)
{
return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
Everything works OK.
But now I want to hide a whole table including thead TR's if a typed text is not in the table.
How can I get that?
Upvotes: 1
Views: 2339
Reputation: 123739
Try this Demo
$("#search").keyup(function () {
var txtVal = $(this).val();
if (txtVal != "") {
$(".tblDetails").show();
$(".message").remove();
$.each($('.tblDetails'), function (i, o) {
var match = $("td:contains-ci('" + txtVal + "')", this);
if (match.length > 0) $(match).parent("tr").show();
else $(this).hide();
});
} else {
// When there is no input or clean again, show everything back
$("tbody > tr", this).show();
}
if($('.tblDetails:visible').length == 0)
{
$('#search').after('<p class="message">Sorry No results found!!!</p>');
}
});
// jQuery expression for case-insensitive filter
$.extend($.expr[":"], {
"contains-ci": function (elem, i, match, array) {
return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
Upvotes: 3