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 rows with (can't get it working in jsfiddle, sorry http://jsfiddle.net/anschwem/Y4cf6/2/). Any simplified code would be greatly appreciated. Also, it would be nice if this code could be restricted to only filtering a certain table, so I can have many tables and many drop downs. If this could be done without row ids, even better. Thanks! My table/html:
<table>
<tr id="catRow">
<td id="cats">cats</td>
</tr>
<tr id="catRow2">
<td id="cats">cats</td>
</tr>
<tr id="dogRow">
<td id="dogs">dogs</td>
</tr>
<tr id="birdRow">
<td id="birds">birds</td>
</tr>
<tr>
<td id="dogRow2">dogs</td>
</tr>
</table>
<select id="selectFilter">
<option id="sel_All">Select...</option>
<option id="selCats">Cats</option>
<option id="selDogs">Dogs</option>
<option id="selBirds">Birds</option>
</select>
Code:
<script type='text/javascript'>
$(window).load(function(){
$('select').change(function() {
if($('#selectFilter option:selected').attr('id') == "sel_All" || $('#selectFilter option:selected').attr('id') == "sel_All"){$('#catRow').show();$('#catRow2').show();$('#dogRow').show();$('#dogRow2').show();$('#birdRow').show();}
if($('#selectFilter option:selected').attr('id') == "selCats" || $('#selectFilter option:selected').attr('id') == "selCats"){$('#catRow').show();$('#catRow2').show();$('#dogRow').hide();$('#dogRow2').hide();$('#birdRow').hide();}
if($('#selectFilter option:selected').attr('id') == "selDogs" || $('#selectFilter option:selected').attr('id') == "selDogs"){$('#catRow').hide();$('#catRow2').hide();$('#dogRow').show();$('#dogRow2').show();$('#birdRow').hide();}
if($('#selectFilter option:selected').attr('id') == "selBirds" || $('#selectFilter option:selected').attr('id') == "selBirds"){$('#catRow').hide();$('#catRow2').hide();$('#dogRow').hide();$('#dogRow2').hide();$('#birdRow').show();}
</script>
Please find the refactored code "http://jsfiddle.net/5fZv7/3/" here and the code snippet is as below..
html code:
and the javascript code:
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:
The Javascript is reduced to essentially a one-liner:
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
Then your jQuery
FIDDLE
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.