Build on-the-fly filtering with jQuery

Wednesday, 10 February 2010


This tutorial looks at using jQuery to build on-the-fly filtering for search results to quickly filter out by matching search terms with content and hiding those elements that don't match.

Recently when jQuery upgraded their API they added a nice on-the-fly filtering feature for filtering by search terms within the API. To get an idea of what I'm talking about you can see the effect here by typing 'bl' into the search jQuery box and you will notice only the entries containing 'bl' are displayed.


You can download the code for this tutorial here
You can view a working demo here



This filtering works on both the title and on the content. It is quite easy to build and a nice trick that has multiple applications. Let's have a look at what our HTML will look like for each of our page elements:

<div class='option'>
 <div class='title'>Soccer</div>
 <div class='description'>A sport played with two teams of eleven players, a round ball and two sets of goals.</div>
 <a href='#'>more...</a>
</div>

So each element is an 'option' and there is a 'title' and a 'description' section. Fairly straight forward. Now let's look at the javascript behind the functionality:

$("document").ready(function() {
 $("#search_field").keyup(function() {
  var terms = $(this).val().toLowerCase();
  if (!terms) {
   $(".option").show();
  } else {
   $(".option").hide().filter(function() {
    return ($(this).children(".title").text().toLowerCase().indexOf(terms) > -1) || ($(this).children(".description").text().toLowerCase().indexOf(terms) > -1);
   }).show();
  }
 });
});

We start by adding the keyup event listener to our #search_field input. Whenever the keyup event occurs we grab the contents of the input and convert to lowercase and store in the terms variable.

If terms is empty we display all of our pages elements. If it is not empty then we begin by hiding all of the '.option' elements and then we apply a filter function. This function filters out all of the elements that do not contain the terms in the '.title' child element or the '.decription' child element. Those elements that haven't been filtered out are then displayed using show().

This kind of filtering is really useful when you have a limited number of elements on the page and makes good sense if you want to avoid round trips to the database.
blog comments powered by Disqus