Nightwhistle Nightwhistle - 4 days ago 5
Javascript Question

Search/Filter rows through multiple tables with one search field

I have PHP generated tables, usually more than 10 at a time. I want to use one search field to find rows that match input in all tables and show only those rows, but if there is no such row in a table then i want that table hidden.

I have found close answer here http://stackoverflow.com/a/16127730/3435158 that's doing great in hiding tables that don't have rows that match - however with his code entire table that matches search input stay visible, and I want only rows that match to be visible, not entire table.




edit: http://jsfiddle.net/jrfUM/113/

What I want to do is if I type 'andrew' in a search field, i want to get (hopefully I'm more clear now):

+---------+
| table 1 |
+---------+
| Andrew |
+---------+

+---------+
| table 4 |
+---------+
| Andrew |
+---------+

Answer

I managed to edit PSL code and made it work for what I needed: http://jsfiddle.net/jrfUM/115/

<input type="text" id="search" />
<table class="tblDetails">
    <thead>
        <tr><th>Table 1</th></tr>
    </thead>
    <tbody>
        <tr><td>Andrew</td></tr>
        <tr><td>John</td></tr>
    </tbody>
</table>
<table class="tblDetails">
    <thead>
        <tr><th>Table 2</th></tr>
    </thead>
    <tbody>
        <tr><td>Jack</td></tr>
        <tr><td>Marc</td></tr>
    </tbody>
 ....

$("#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);
            match.parent().siblings().hide();                       //  <<=== [LINE ADD]
            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;
    }
});
Comments