Taras Pavlov
Taras Pavlov

Reputation: 11

Filtering a table with jQuery (from ... to)

I'm quite a newbie when it comes to jQuery. But I have this thing I need to do. I know various plugins could be used to make it easier, but that's not the point.

I have a simple HTML table and I'm filtering results (in the example I'm filtering by the Author field), but how exactly can I make a filter for example for the year 1950 to 1960? Is there any simple way to edit my code to do that? I can't come up with a solution, although I feel it should be simple.

Also, is there a way to make filtering case-insensitive? Thanks in advance!

<input type="text" id="filter-input"  value=""/><br/>
<table class="table-class">
<tr>
    <th>Bookname</th><th>Author</th><th>Publish date</th>
</tr>
<tr>
    <td>Exaple</td><td>Matt</td><td>1951</td>
</tr>
<tr>
   <td>Example2</td><td>John</td><td>1990</td>
</tr>
    <tr>
   <td>Example3</td><td>Ted</td><td>1955</td>
</tr>
</table>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
var filter = $("#filter-input");
filter.keyup(function(e) {
    var author = $(this).val();
    $('.table-class tr:not(:first)').filter(function() {
        if (!$(this).find('td:eq(1)').is(':contains("' + author + '")')) {
            return true;
        }
        else {
            $(this).show();
            return false;
        }
    }).hide();
});
</script>

Upvotes: 1

Views: 144

Answers (1)

adeneo
adeneo

Reputation: 318182

You can filter by anything you'd like, to filter by year you can do something like:

$('.table-class tr:not(:first)').filter(function() {

    var txt  = $('td', this).last().text(),
        year = parseInt(txt, 10);

    return year > 1950 || year < 1960

}).hide();

to make it case insensitive :

$('.table-class tr:not(:first)').filter(function() {

    var txt =  $('td', this).eq(1).text().toLowerCase();

    return txt.indexOf(author.toLowerCase()) != -1;

}).hide();

Upvotes: 1

Related Questions