Reputation: 273
I have a table which is filled dynamically using php. and I wanted to add search functionality to it. after searching similar questions here on stackoverflow I found a JS snippet which I tried.
var $rows = $('#existing tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
jsfiddle link: http://jsfiddle.net/kvkBw/3/
The problem is that when I enter any search term the table itself gets hidden (goes invisible) any help would be appreciated thanks!.
Note that the php code is removed because php is not supported by jsfiddle and also to increase readability
Upvotes: 0
Views: 3551
Reputation: 1640
Remove the .hide() at the end that's what's causing your issue.
Also remove the ! at the beginning of the return value.
$rows.show().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return text.indexOf(val);
});
Upvotes: 0
Reputation: 1557
First, your function search is wrong, what is !~
, and why you try to hide all the occurence you find ??
Try this:
var $rows = $('#existing tbody tr:not(:first)'); // this is the reason for table hidding like @drizzie says
$('#search').keyup(function () {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.hide().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return text.indexOf(val) != -1 ;
}).show();
});
But better look at the DEMO
Upvotes: 3
Reputation: 3361
You are hiding your first and second rows. Change your row selector to
var $rows = $('#existing tbody tr:not(:first)');
This eliminates your header row and your filter row.
Upvotes: 0