Reputation: 1350
I have set up a basic table from an example in SO here where I added column titles.
Can anyone make a suggestion how to fix the table filter so it does not hid the column titles? Here is the jsfiddle code I have been testing.
Javascript
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
reg = RegExp(val, 'i'),
text;
$rows.show().filter(function() {
text = $(this).text().replace(/\s+/g, ' ');
return !reg.test(text);
}).hide();
});
Example search: If you type apple in the search - it hides title 1 and title 2. However, I prefer to keep the title 1 and title 2 after the search has been entered.
Upvotes: 3
Views: 8883
Reputation: 4739
My recommendation: add a class into your header, and exclude that from your filter results:
http://jsfiddle.net/7BUmG/1161/
<input type="text" id="search" placeholder="Type to search">
<table id="table">
<tr class="header">
<th>Title 1</th>
<th>Title 2</th>
</tr>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
</table>
And using RegEx
var $rows = $('#table tr[class!="header"]');
$('#search').keyup(function()
{
var val = '^(?=.*\\b'
+ $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b')
+ ').*$',
reg = RegExp(val, 'i'),
text;
$rows.show().filter(function()
{
text = $(this).text().replace(/\s+/g, ' ');
return !reg.test(text);
}).hide();
});
Upvotes: 4