Simple Javascript Table Filtering

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

jQuery Requirement

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.

Setup

Here is the HTML table we will use for our example:

Logic Explanation

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
    • Run 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 display property to none
    • 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

That’s all there is to the logic. If we wanted a more feature-rich filtering that allowed filtering on individual columns, this would require some minor modifications. For our purposes though, this is sufficient. On to the Javascript. Rather than writing out each line, I have commented on the purpose of each line of code. If there are any questions, please let me know in the comments!

In case you missed it above, here is a preview of the finished product: Simple Table Filtering

4 thoughts on “Simple Javascript Table Filtering

  1. Hey rob, what’s the benefit here above doing a :contains(…)? I’ve been using $target.find(‘tr’).not(“:contains(‘” + current_search + “‘)”); with an overwritten contains that lowercases search. Are there benefits one way or the other?

  2. Hey Joe! Glad to hear from you 🙂

    So the main reason I go with indexOf over :contains is performance, I’ve created a jsperf case to illustrate the differences here: http://jsperf.com/jq-contains-vs-indexof

    As you can see in the jsperf results, indexOf is quite a bit faster. I think the :contains pseudo-selector is great (in terms of brevity) for searching a minimal set, but if you plan on sifting through any larger data sets you would want to go the indexOf route.

Leave a Reply