I have a table. I want the user to be able to be able to filter the table by the option they pick in a given drop down. I have it working, but it\'s messy and hard to add new ro
You should check out DataTables, it has this kind of filtering built in (fnFilter in the API)
It might be a bit of a learning curve at first, but will be much more flexible in the end.
Please find the refactored code "http://jsfiddle.net/5fZv7/3/" here and the code snippet is as below..
html code:
<select id="selectFilter">
<option id="all">Select...</option>
<option id="cats">Cats</option>
<option id="dogs">Dogs</option>
<option id="birds">Birds</option>
</select>
<table border="1">
<tr class="all cats">
<td>cats</td>
</tr>
<tr class="all cats">
<td>cats 2</td>
</tr>
<tr class="all dogs">
<td>dogs</td>
</tr>
<tr class="all birds">
<td>birds</td>
</tr>
and the javascript code:
$(document).load(function () {
$('#selectFilter').change(function () {
$(".all").hide();
$("." + $(this).find(":selected").attr("id")).show();
});
});
Hopes this helps you to maintain the code easily and efficiently.
I've refactored your fiddle: http://jsfiddle.net/Y4cf6/4/
By taking advantage of CSS classes and built-in attributes like "value", we can easily make this code more generic.
For this HTML:
<table id="animals">
<tr class="cat">
<td>Cat 1</td>
</tr>
<tr class="cat">
<td>Cat 2</td>
</tr>
<tr class="dog">
<td>Dog 1</td>
</tr>
<tr class="cat">
<td>Cat 3</td>
</tr>
<tr class="bird">
<td>Bird 1</td>
</tr>
<tr class="cat">
<td>Cat 4</td>
</tr>
<tr class="dog">
<td>Dog 2</td>
</tr>
</table>
<select id="selectFilter">
<option>Select...</option>
<option value="cat">Cats</option>
<option value="dog">Dogs</option>
<option value="bird">Birds</option>
</select>
The Javascript is reduced to essentially a one-liner:
$("#selectFilter").on("change", function() {
$("#animals").find("tr").hide().filter("." + $(this).val()).show();
});
Edit: the one case this doesn't handle is giving you a way to show all the rows again. I'll leave this as an exercise for you, but here's a tip: You could read the value of $(this).val()
, and if there isn't a value, then show all the rows instead of filtering them.
You can change your html markup like this
<table id='animal'>
<tr class="cat">
<td>cats</td>
</tr>
<tr class="cat">
<td>cats</td>
</tr>
<tr class="dog">
<td>dogs</td>
</tr>
<tr class="bird">
<td>birds</td>
</tr>
<tr class='dog'>
<td>dogs</td>
</tr>
</table>
<select id="selectFilter">
<option value=''>Select...</option>
<option value='cat'>Cats</option>
<option value='dog'>Dogs</option>
<option value='bird'>Birds</option>
</select>
Then your jQuery
$('#selectFilter').change(function(){
var trs = $('#animal tr');
if(this.value == ''){ // if first option picked show all
trs.show();
}else{
var $el = $('.'+this.value); // element to show
trs.not($el).hide(); // hide all but the elements to show
$el.show(); // show elements
}
});
FIDDLE