Urs
Urs

Reputation: 5132

How to properly filter a list by multiple criteria with jQuery?

I would like to perform the following actions on my DOM:

Filter a list via multiple controls (combined):

I normally write something by hand to combine multiple choices from different select boxes, but it's not ideal. Also, for a "free text" filter, I have always used jQuery-Plugins, and they tend to reset the selection when you start typing.

With tables, I use the datatables plugin, which brings along multiple filters. It's extremely feature-rich, but also quite heavy - and designed for tables, not for any type of lists.

What are the general recommendations / outlines on how to achieve this?

PS: Here's how I do it now. a) it's extremely proprietary and b) I haven't managed to combine it with a text filter yet:

function showItems(selectedCanton,showTypeOne,showTypeTwo){
    var typeOneSelector = '';
    var typeTwoSelector = '';

    if (selectedCanton=='all'){
        var cantonSelector = '';
    }
    else {
        var cantonSelector = '.list-item[data-canton="'+selectedCanton+'"]';
    }

    if (showTypeOne){
        if (showTypeTwo){
            selector = cantonSelector;
            //selector = cantonSelector+'[data-type="one"],'+cantonSelector+'[data-type="two"]';
        }
        else {
            selector = cantonSelector+'[data-type="one"]';
        }
    }
    else if (showTypeTwo){
        selector = cantonSelector+'[data-type="two"]';
    }
    $('.list-item').hide();

    console.log(selector);
    $(selector).show(); 
}

$(document).ready(function($){

        $(".filter-select").change(function() {     
            var selectedCanton = $("#canton").val(); 
            var showTypeOne = $("#type-one").prop('checked');
            var showTypeTwo = $("#type-two").prop('checked'); 
            showItems(selectedCanton,showTypeOne,showTypeTwo);
        });
});

Upvotes: 0

Views: 3208

Answers (1)

nrgjack
nrgjack

Reputation: 76

you can use filter function of jquery.

try something like

$('.list-item').hide();

$('.list-item').filter(function (index, e) {
    var condition = true;
    var el = $(e);

    if(showTypeOne)
    {
      condition = condition && (el.data("type") === "one");
    }

    if(showTypeTwo)
    {
        condition = condition && (el.data("type") === "two");
    }

    if(selectedCanton!='all')
    {
        condition = condition && (el.data("canton") === selectedCanton);
    }

    return condition;
 })
.show();

you could add text filter easly that way..

working sample : http://jsfiddle.net/CufMp/1/

Upvotes: 3

Related Questions