jQuery filter with multiple options

jquery filter has been trending always and deployed in all kinds of projects for fast filtering of preloaded results. I always find plugins useful but hesitate to use them because whenever a page load, the plugin also loads impacting the load time of a page.

HTML

Always keep in mind that, to keep the javascript code simple and lightweight always write a comprehensive HTML with classes and IDs. In the following HTML code you may see I would’ve enclosed all search results in a parent container and all inputs to an individual parent block with a class name. This help to write a neat and a simple javascript code see above live filter.

I will explain them in a step-by-step of jquery filter

First let us write the jquery filter section


You can notice that I have assigned a class category for the checkboxes. This is to get the checked items by selecting the class in jQuery. Also, notice the value of each checkbox. The same values for each corresponding item in the search result should be used inside data-tag attribute.

Next is to set up the result blocks with appropriate data-tag value.


Each resultblock class has its own data-tag which is at least one of the value attribute of the jquery filter checkboxes. I have used game, technology and os. We have set up the HTML and ready to build the code to filter each result.

Javascript

I have written the javascript in two parts,

  1. Iterate through filters and put the checked items into an array
  2. Iterate through resultblock, get data-tag and check for data-tag value against the array. If item matches the show the result block else hide.

Step 1 of Javascript

Step 2 of Javascript

Putting it all together


That’s it we completed live filter. You can turn this into a programmatically driven process very easily. For any help feel free to ask in the comments section.