Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple data-attribute filteration using input checkbox

Tags:

jquery

I want a jQuery function that filters a set of data-attributes.

In my HTML structure I have a number of list items and there attributes are:

data-offer and data-subcat these two will be used to filter out the items using multiple input check boxes.

So far I have this jQuery which is performing filtration but not as I want it to be.

$(".cs-widget-content").on("change", "input[type=checkbox]", function () {
    $(".five-column > li.column").hide();
    $(".cs-widget-content").find("input:checked").each(function (i, el) {
        $(".five-column > li.column").filter('[data-offer="' + el.id + '"]').show();
    });

    $(".cs-widget-content").find("input:checked").each(function (j, el) {
        $(".five-column > li.column").filter('[data-subcat="' + el.id + '"]').show();
    });

});

Here's the JSFiddle

Solution I want:

  1. All the data should be load on Page load (Which is working).

  2. The inputs filter for both data-attributes should work together (e.g when an input is checked for data-offer it will show that data and if the data-subcat is checked it will show up the data for this attribute as well, within the previous checked of data-offer.

  3. When any of the input is unChecked, the data should be visible back.

looking forward for your help.

Thank you

like image 974
yaqoob Avatar asked Jun 09 '15 05:06

yaqoob


1 Answers

Iterate through the products rather than the filters and decide for each whether it should be displayed.

var filter1HasChecked = $("[data-filter=1]:checked").length;
var filter2HasChecked = $("[data-filter=2]:checked").length;

$("ul.products li").each(function(i,v){
    var $this = $(this);

    if((!filter1HasChecked || $("#" + $this.data("offer")).is(":checked"))
       && (!filter2HasChecked || $("#" + $this.data("subcat")).is(":checked"))){
       $this.show();
    }        
});

http://jsfiddle.net/Curt/k62kxm0x/4/

This sort of operation would become costly with 100s of items, but then I would suggest some server-side filtering using AJAX, or perhaps implementation of a front-end framework such as AngularJS.

like image 72
Curtis Avatar answered Oct 19 '22 23:10

Curtis