views:

425

answers:

4

I'm trying to figure out how to filter a table based on the row class when I click a button. I've been looking at various jquery plugins, but none of them seem to do what I need it to do. Some have textboxes that filter, etc., and I've tried adapting the code but frankly, I'm just making a great big mess... Help? I have a table that looks like this:

<table>
<tr class="dr"><td>data</td></tr>
<tr class="dr"><td>data</td></tr>
<tr class="sr"><td>data</td></tr>
<tr class="mr"><td>data</td></tr>
<tr class="mr"><td>data</td></tr>
<tr class="dr"><td>data</td></tr>
<tr class="dr"><td>data</td></tr>
<tr class="sr"><td>data</td></tr>
<tr class="sr"><td>data</td></tr>
<tr class="sr"><td>data</td></tr>
<tr class="sr"><td>data</td></tr>
</table>

And I have three buttons:

<input type="button" name="filterdr" /> <!-- clicking this will only show rows with dr class -->
<input type="button" name="filtersr" /> <!-- clicking this will only show rows with sr class -->
<input type="button" name="filtermr" /> <!-- clicking this will only show rows with mr class -->
+1  A: 

You could do something like below respectively for each button click, it should work out.

$("tr:not(.dr)").hide();
$("tr.dr").show();

IE:

$(document).ready(function(){
    $(":button[name='filterdr']").click(function(){
        $("tr:not(.dr)").hide();
        $("tr.dr").show();
    });
});
Quintin Robinson
Thank you! Had no idea it would be that easy...
n00b0101
A: 
<input type="button" id="filterdr" /> <!-- clicking this will only show rows with dr class -->
<input type="button" id="filtersr" /> <!-- clicking this will only show rows with sr class -->
<input type="button" id="filtermr" /> <!-- clicking this will only show rows with mr class -->

JQuery:

$('#filterdr').click(function() { 
   $('table tr').hide();
   $('table tr.dr').show();
});

and You do the same for the other buttons.

Soufiane Hassou
+3  A: 

Something like this might do the trick:

$('input[type=button]').click(function()
{
    $('tr').hide()
        .filter('.' + this.name.replace(/filter/, '')).show();
});

Adding an ID to your table would be a good idea.

Greg
A: 

DataTables does exactly what you need:

  • Column or row filtering
  • Event Handling for on row creation
  • Filtering for all columns from a single Search textbox
  • Multicolumn sorting
  • Editable Rows

I've used this on production projects and some cases I've elected to use DataTables over Telerik RadGrad. It's very flexible and great for RIA.

David Robbins