Home / jQuery / jQuery live filter with multiple options

jQuery live filter with multiple options

jQuery live 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. This results in a bad SEO concept. This tutorial is an alternate to live filter which can be upgraded based on the usage.

Markup

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.

I will explain them in a step-by-step fashion

First let us write the 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 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! You can turn this into a programatically driven process very easily. For any help feel free to ask in the comments section.

Download Β  Preview

About Ashik

I am a Full Stack Developer and love to work on APIs and Apps. Hardcore lover of Ionic and Laravel <3

Check Also

Private chatroom using socket.io, NodeJS and MySQL

As I promised to write a tutorial on Private chatroom with MySQL DB in the …

  • Daego

    Hi,
    which part of the CSS code I need to change, if I have the results hiden from the beginning when i open the site ? I want to see only results if at least one option was selected.

  • Upanshu

    Hi,
    I want to compare these values with my key in json and populate a corresponding checkbox list according to my selection of checked checkbox…Can you help me with this?

  • Levi

    Is there a way to edit the code for cases where one of the resultsblocks may fit into more than one of the filters? For example, an os which is also a game, can you somehow add multiple data-tags?

    • yes,

      data-tag=”os,game”

      now you gotta chagne jquery
      var item = $(this).attr(‘data-tag’);
      items = item.split(‘,’);
      $.each(key in items){
          if(jQuery.inArray(key,category_list) > -1){
              $(this).fadeIn(‘slow’);
          }
      }

      • Levi

        Thanks so much for the reply! This seems like exactly what I’m looking for, but I’m getting a “Uncaught SyntaxError: Unexpected token {” on:

        $.each(key in items){

        If I remove the { }’s I then get an “Uncaught ReferenceError: key is not defined” error.

        I’ve been messing around with it for a while but can’t get it to work, and I’m pretty new at this, do you have any suggestions on how I could fix this?
        Thanks

        • xenazfire

          Have you solved the error yet? Please do share as I required multiple data-tags.

          • Check out my edit

          • Harrison Hawkes

            I still can’t get multiple tags to work. I have this script but it doesn’t do anything:

            $(document).ready(function(){
            $(‘.category’).on(‘change’, function(){
            var category_list = [];
            $(‘#filters :input:checked’).each(function(){
            var category = $(this).val();
            category_list.push(category);
            });

            if(category_list.length == 0)
            $(‘.resultblock’).fadeIn();
            else {
            $(‘.resultblock’).each(function(){

            var item = $(this).attr(‘data-tag’);
            var itemarr = item.split(‘,’);
            $this = $(this);
            $.each(itemarr,function(ind,val){
            if(jQuery.inArray(val,category_list) > -1)
            $this.fadeIn(‘slow’);
            else
            $this.hide();
            });
            }
            });
            });

          • Check my update

        • I have edited my comment. This should work.

      • lokyman

        Thank you very much, but with this modification only can match the last value of multiple tags. How we can fix that?

        Thanks again in advance

      • Nadine

        Hi, I would also like to find out what I need to change if my resultblocks fit into more than one of the filters.

        I have tried the code you’ve posted above, but it does not work for me, I get a syntax error. Apparently a ( is missing somwhere, but no matter how I change the {} and (), still errors. This is the code I’ve used:

        var item = $(this).attr(‘data-tag’);
        var itemarr = item.split(‘,’);
        $this = $(this);
        $.each(itemarr,function(ind,val){
        if(jQuery.inArray(val,category_list) > -1){
        $this.fadeIn(‘slow’);
        return false;
        }
        else
        $this.hide();
        });

        Could you please have a look at it again and maybe post the WHOLE JQuery starting with $(document).ready(function(){…}); to make sure there will be no trouble with missing {} or ()?

        Many thanks in advance.

  • Rodrigo Ezequiel

    Great code! but imagine you don’t have Games but : Strategy Games, FPS and Card Games. And instead of technology you have: multiplayer, single player.

    And you have example: data-tag= FPS and data-player=single player. How you put this in Javascript code?

    thnk you

  • Bhom

    This is what is showing, http://i.stack.imgur.com/MKSZj.png.But i want to show like the bottom image help pls

  • ashu

    Great code ! Thanks for the great initiate…

  • Paul Smith

    Hello, is there a way to show the events in the calendar without hovering over the day?

  • Morning. Is there a way to work this code into the php/mysql script? I am a little confused in how to match the checkbox to the database. Thanks.

  • Andrew

    Ashik , thanks for this tutorial. How I can filter items by two parameters? For example, item with data-tag GAME, has category ACTION?
    Thanks!

    • Zeeshan

      did you figured out?

  • gabi

    You have “os, game and technology” data-tags. How do I add another one? I tried adding “computers”, and it doesn’t show anything.
    Thanks.

  • Blu Ycw

    this is filter by name, but what if i want to filter with date range also?

  • guest

    does it work?

  • pradeep

    You have “os, game and technology” data-tags. How do I add another one? I
    tried adding “computers”, and it doesn’t show anything.

  • pradeep

    and below code also i tried that you have posted but not getting correct output…

    data-tag=”os,game”

    now you gotta change jquery

    var item = $(this).attr(‘data-tag’);
    var itemarr = item.split(‘,’);
    $this = $(this);
    $.each(itemarr,function(ind,val){
    if(jQuery.inArray(val,category_list) > -1){
    $this.fadeIn(‘slow’);
    return false;
    }
    else
    $this.hide();
    });

  • Anita Bhave

    Hi,

    Very nice code and easy to implement. I am using this script in one of my projects. data tags are : shape,metal,stone and there are many subcategories in each data tag. like shape:asscher ,baguette,cushion and like wise in metal and stone. I copied your code and pasted but getting error “Uncaught SyntaxError: Unexpected token else”

    My code is as follows:

    $(document).ready(function(){

    $(‘.category’).on(‘change’, function(){

    var category_list = [];

    $(‘#filters :input:checked’).each(function(){

    var category = $(this).val();

    category_list.push(category);

    });

    if(category_list.length == 0)

    $(‘.resultblock’).fadeIn();

    else {

    $(‘.resultblock’).each(function(){

    var item = $(this).attr(‘data-tag’);

    var itemarr = item.split(‘,’);

    $this = $(this);

    $.each(itemarr,function(ind,val){

    if(jQuery.inArray(item,category_list) > -1)

    $(this).fadeIn(‘slow’);

    return false;

    else

    $(this).hide();

    });

    }

    });

    });

    can you tell me what is wrong with this code?Thanks in anticipation.

    • if(jQuery.inArray(item,category_list) > -1){

      $(this).fadeIn(‘slow’);

      return false;
      }

      else

      $(this).hide();

      • Anita Bhave

        Thanks. It worked. But unable to filter other two divs. Guess #filters is clashing with other divs. here is my html markup:

        $(document).ready(function(){

        $(‘.category’).on(‘change’, function(){

        var category_list = [];

        $(‘#filters :input:checked’).each(function(){

        var category = $(this).val();

        category_list.push(category);

        });

        if(category_list.length === 0)

        $(‘.resultblock’).fadeIn();

        else {

        $(‘.resultblock’).each(function(){

        var item = $(this).attr(‘data-tag’);

        var itemarr = item.split(‘,’);

        $this = $(this);

        $.each(itemarr,function(ind,val){

        if(jQuery.inArray(val,category_list) > -1){

        $this.fadeIn(‘slow’);

        return false;

        }

        else

        $this.hide();

        });

        });

        }

        });

        });

        METAL :

        STONE SHAPE :

        STONE TYPE:

  • Omarov

    hi,

    Thank you for sharing this amazing code. I have a question, i want to filter the results in a multiple way… for example:

    or

    I want that every time i check a filter checkbox, technology, os or game, the result shows on according to data-tag value.

    in other words, i want a multiple filter with multiple data tag values.

    is this possible?

    here’s my code:

    $(document).ready(function(){
    $(‘.category’).on(‘change’, function(){
    var category_list = [];
    $(‘#filters :input:checked’).each(function(){
    var category = $(this).val();
    category_list.push(category);
    });

    if(category_list.length == 0)
    $(‘.resultblock’).fadeIn();
    else {
    $(‘.resultblock’).each(function(){
    var item = $(this).attr(‘data-tag’);
    if(jQuery.inArray(item,category_list) > -1)
    $(this).fadeIn(‘slow’);
    else
    $(this).hide();
    });
    }
    });
    });

    • try something like this

      • Omarov

        Wow, thank you sou much !!! that really works !!! πŸ™‚ Greetings from Mexico.

  • Omarov

    Hi, Ashik.

    Excuse my ignorance, I am begginer in ajax… well, i have one last question:

    Your code works very fine, so… i want to know if is possible to filter results after the results have been filtered…

    for example, i have two filter rows. On the first row, i have pc and laptops, on the second row i have these filters: windows, linux and one new category called others.

    When i do click on the pc filter, the results shows only pc… all is in order by now, but, when i press the windows filter, the results shows laptops aswell because the laptos have installed windows too… here is my problem… i want to filter only the pc results when i press the second filter called windows…

    In other words, i want to do a filter on the filtered results…

    Is this possible?

    Thank you for your valious help and amability.

    Here’s my code:

    $(document).ready(function(){
    $(‘.category’).on(‘change’, function(){
    var category_list = [];
    $(‘#filters :input:checked’).each(function(){
    var category = $(this).val();
    category_list.push(category);
    });

    if(category_list.length === 0)
    $(‘.resultblock’).fadeIn();
    else {
    $(‘.resultblock’).each(function(){
    var item = $(this).attr(‘data-tag’);
    var itemarr = item.split(‘,’);
    $this = $(this);
    $.each(itemarr,function(ind,val){
    if(jQuery.inArray(val,category_list) > -1){
    $this.fadeIn(‘slow’);
    return false;
    }
    else
    $this.hide();
    });
    });
    }
    });
    });

    • Good to know the code works πŸ™‚ So now you are looking for nested filters!

      I cannot write code as of now coz I’m really occupied by other works. I can give you a hint though..

      Let calls the two filter as ‘primary’ and ‘secondary’

      Primary has PC and Laptops
      Secondary has WIndows, Linux and Others

      As of now your primary filter should work fine! Let us assume user has clicked on ‘PC’ and all items under PC is listed. Now you want only windows machines to be listed

      So when a user clicks on ‘windows’ in the second filter you just have to get all the displayed items and run iterate through them just like we do for ‘primary’. Try something like this for secondary filter use ‘:visible’ selector

      • Omarov

        Hi, Ashik

        I’ve been trying but, it looks like this doesn’t work right πŸ™

        Please, I know that you are busy, but please, help me one last time.

        I beg on you :'(

        I’ve been searching on the web a filter that do the job in a similar way that your filter does… but i have no success… your filter is the best option. This amazing filter needs that option: filter the filtered results (ΒΏnested filter?)

        Please, Ashik, i beg on you for help.

        Thank you so much, you are the best.

        Here is my code:

        $(document).ready(function(){
        $(‘.category’).on(‘change’, function(){
        var category_list = [];

        $(‘#filters :input:checked’).each(function(){
        var category = $(this).val();
        category_list.push(category);
        });

        if(category_list.length === 0)
        $(‘.resultblock’).fadeIn();
        else {
        $(‘.resultblock’).each(function(){
        var item = $(this).attr(‘data-tag’);
        var itemarr = item.split(‘,’);
        $this = $(this);
        $.each(itemarr,function(ind,val){
        if(jQuery.inArray(val,category_list) > -1){
        $this.fadeIn(‘slow’);
        return false;
        }
        else
        $this.hide();
        });
        });
        }
        });
        });

        • Ok I will share a working filter soon. Gimme time until tomorrow evening

          • Omarov

            Thank you very much, ashik !!

            I’ll be waiting for it πŸ™‚

          • Two level filtering with multiple data-tags

            http://www.mediafire.com/file/jkzzs9skk9p73t9/live_filter.zip

            I hope this helps

          • Omarov

            Ashik:

            This is EXACTLY that I’ve been searching for.

            I have no words to express my gratitude. Your code works very, very fine.

            You are awesome !! πŸ˜€

            Thank you for your valuable help.

            you are the kind of people that this world deserves.

          • Good luck πŸ™‚

  • shailendra Singh Tiwari

    hi
    I want Product Not Found if selected product category product not Found

  • Simon Tlz

    Hi, how could i match categories with whom are into my database? Thanks a lot… πŸ™‚

  • Ivan Todorov

    Any chance to add price range slider to this filter?

Do you wan't to get notified?

I will not spam your inbox. I will only send email whenever I publish a new article or to share information about technology

You have Successfully Subscribed!