A few days back I was asked to build a scrolling div full of checkboxes populated via a database query record set that could be filtered. To accomplish this, I’ve often used AJAX in the past to hit a CF component that would run a SELECT statement containing a WHERE clause that looked for a record LIKE my existing value. This would return back the filtered item.
In this case however, I was working with a very large dataset and it was not appropriate to make an AJAX call to filter the dataset, and much less to do so on each key press to simulate live filtering. So I decided to filter on the client side and leave CF and AJAX out of the equation all-together. Naturally, I open the jQuery docs and start looking for something along the lines of a regular expression. As usual jQuery makes things even simpler than I could have imagined.
The jQuery selectors page shows multiple ways of selecting elements. One way is to use the ‘contains’ selector that essentially looks at the value of an attribute and checks if the substring exists in any of the available values. Once we know which elements are like and not like the substring (a.k.a. the filter criteria) we can use the jQuery show() and hide() functions to perform the filter visually for the user.
Let’s look at an example.
The HTML & Coldfusion
As far as our HTML is concerned we have text field where we can type our filter criteria and a set of checkboxes for each color defined in the list ‘variables.colorsList’ at the top of the page. All of this is standard HTML, but do notice the custom attribute in the div tag called ‘color’. This attribute is included to give jQuery a value to filter on. So if I type ‘bl’ into the filter field jQuery will loop through each of the divs containing a checkbox, get the value of the ‘color’ attribute and check if the substring ‘bl’ is contained in the attribute value. So in this case it should hide all color checkboxes except ‘black’ and ‘blue’.
So let’s now look at the heart of this which is the jQuery.
So, once again jQuery amazes me with the fact that, minus any var setting and event listening, client side filtering via showing and hiding can be accomplished in essentially two lines and a conditional that restores the data in the case that the filter is not being used. Incredibly simple!