Let’s say you have a smallish table that you want to allow your users to filter (via text search), but don’t necessarily want to install another plugin. I recently found myself in this position and decided it would just be easier to make my own simple filter. The requirements were simple:
- Filter will be a text input
- Non-matching rows are removed from the table as the user types
- If no matches are found, a message is shown to the user indicating such.
For the impatient, here is the final result
For this task, I’m going to use jQuery. If anyone would really like a non-jQuery version, let me know in the comments and I will post that as well.
Here is the HTML table we will use for our example:
In order to filter the table, we need to do a few simple things:
- Get the text the user typed and convert it to lower case (that way the search is case-insensitive)
- Loop through each row in the table and for each row:
- Convert row to text
- Convert text to lower case
rowText.indexOf(searchText)to test if the search value is contained with the row text
- If the text is NOT in the row, set the CSS
- If the text IS in the row, leave it alone.
- After looping through each row, if no rows are displayed (matching), show a “No results found” message
In case you missed it above, here is a preview of the finished product: Simple Table Filtering