Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table - Live Search with jQuery

I have been working on a solution for a Live Search on my table of data.

When I search Jim it works as expected :-)

However, when I search Carey, no results appear. Why is this? :-(

Demo: http://jsfiddle.net/L1d7naem/

$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            var id = $row.find("td:first").text();

            if (id.indexOf(value) !== 0) {
                $row.hide();
            }
            else {
                $row.show();
            }
        }
    });
});
table, tr, td, th{
    border: 1px solid blue;
    padding: 2px;
}

table th{
    background-color: #999999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><th>Forename</th><th>Surname</th><th>Extension</th></tr>
<tr><td>Jim</td><td>Carey</td><td>1945</td></tr>
<tr><td>Michael</td><td>Johnson</td><td>1946</td></tr>
</table>
<br />
<input type="text" id="search" placeholder="  live search"></input>
like image 883
michaelmcgurk Avatar asked Nov 30 '25 03:11

michaelmcgurk


2 Answers

Its because of the following line:

var id = $row.find("td:first").text();  

You are working on the first column of table only and "Carey" is in second column of table

like image 130
Mayank Pandeyz Avatar answered Dec 01 '25 16:12

Mayank Pandeyz


The behaviour you want can be achieved with the following corrections in the each loop (also note the < 0 in the condition...):

var id = $.map($row.find('td'), function(element) {
    return $(element).text()
}).join(' ');

if (id.indexOf(value) < 0) {
    $row.hide();
} else {
    $row.show();
}
like image 39
José Antonio Postigo Avatar answered Dec 01 '25 17:12

José Antonio Postigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!