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
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:
Cat 1
Cat 2
Dog 1
Cat 3
Bird 1
Cat 4
Dog 2
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.