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.