Ace
Ace

Reputation: 845

Jquery Search not working

In this code, when someone enters a users name I want to show only that row and hide others.

<input type="text" id="usearch">
<table class="table myTable">
    <thead>
        <tr>        
            <th></th>
            <th>User</th>                                            
        </tr>
    </thead>   
    <tbody id="searchbody">
        <tr>
            <td>Jhon</td>
        </tr>
        <tr>
            <td>Jane</td>
        </tr>
        <tr>
            <td>Sarah</td>
        </tr>
        <tr>
            <td>Peter</td>
        </tr>
        <tr>
            <td>Paul</td>
        </tr>
    </tbody>
</table>



jquery

$(document).on('keyup','.myTable',function() {
    var uval = $(this).val();
    alert(uval);
    if(uval != '') {
        $('.myTable tr').hide();
        $('.myTable tr td')each(function() {
            if($(this).is(':contains('+uval+')')) {
                $(this).parent('tr').show();
            }
        });
    }
});

FIDDLE:http://jsfiddle.net/nzhu6/ It is not working. What's wrong with the code?

Upvotes: 1

Views: 859

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The keyup event must be attached to the input element

$('#usearch').on('keyup', function () {
    var uval = $(this).val();
    var $trs = $('.myTable tbody tr');
    if (uval != '') {
        $trs.hide().filter(function(){
            return $(this).text().toLowerCase().indexOf(uval.toLowerCase()) >= 0;
        }).show()
    } else {
        $trs.show();
    }
});

Demo: Fiddle

Upvotes: 1

Related Questions