jQuery - How to filter rows onclick?
-
18-09-2019 - |
Question
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 -->
Solution
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();
});
});
OTHER TIPS
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.
<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.
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.