Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter table from <select> input using jQuery

I'm trying to filter a table from an alphabetical <select> input with jQuery.

I have first and last names in two columns of the table, and I'd like to filter the rows by either of these.

I have a select input set up as so:

<select>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    ...
</select>

and I'd like to filter this table:

<tr>
    <td>Joe</td>
    <td>Schmoe</td>
    <td>$2482.79</td>
    <td>172.78.200.124</td>
    <td>http://gmail.com</td>
</tr>
<tr>
    <td>John</td>
    <td>Doe</td>
    <td>$2776.09</td>
    <td>119.232.182.142</td>
    <td>http://www.example.com</td>
</tr>

How would I go about filtering the table using jQuery?

like image 557
peehskcalba Avatar asked Jul 08 '09 19:07

peehskcalba


2 Answers

This will work assuming you only have one select and one table that is stuctured like your example

$(document).ready(function($) {
    var rows = $('table tr').each(function() {
        var row = $(this);
        var columns = row.children('td');

        row.data('name-chars', [
            columns.eq(0).html()[0].toUpperCase(),
            columns.eq(1).html()[0].toUpperCase(),
        ]);
    });

    $('select').change(function() {
        var char = $(this).val().toUpperCase();

        rows.each(function() {
            var row = $(this);
            var chars_to_match = row.data('name-chars');
            if($.inArray(char, chars_to_match) > -1) {
                row.show();
            }
            else {
                row.hide();
            }
        });
    });
});
like image 181
howardr Avatar answered Oct 10 '22 15:10

howardr


I came up with this. Pretty similar to what Elzo came up with but it limits it to the first two columns of the table.

 $('select').change( function(e) { 
   var letter = $(this).val();
     if (letter === 'ALL') {
         $ ('tr').show ();
     }
     else {
         $('tr').each( function(rowIdx,tr) {
             $(this).hide().find('td').each( function(idx, td) {
                 if( idx === 0 || idx === 1) {
                     var check = $(this).text();
                     if (check && check.indexOf(letter) == 0) {
                         $(tr).show();
                     }
                 }
             });             

         });
     }             
 });

It doesn't ignore case and assumes you have one select and the only tr's on the page are the ones you want to filter.

EDIT Added an 'ALL' option to show rows again.

like image 43
seth Avatar answered Oct 10 '22 16:10

seth