0

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

2
  • What is this ´return !~text.indexOf(val);´? Commented Oct 29, 2013 at 20:00
  • That is an expression I've never seen before, but testing it out it looks like it is equivalent to (text.indexOf(val) === -1). A little too clever, I think. Commented Oct 29, 2013 at 20:02

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

What do you add in the $('#existing tbody tr:not(:first)') ? And do I need to add a textbox myself?
0

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.

Comments

0

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);
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.