LeeTee LeeTee - 1 month ago 12
CSS Question

JQuery filter checkboxes to show / hide elements

I have the below code which filters elements by hiding them in JQuery using the styles on the elements. See my JSFiddle(https://jsfiddle.net/vy41zwch/4/).

My issue is that it I need it to show only elements that have ALL the checked filters listed in the styles and not show ANY of checked elements.

For example, if I select, "red" and "Coat" It should show only BOX A as that contains both filters. Instead it shows BOXs A & B.

//filter files list
function filterFilesList() {
var rows = $('.file-row');
var checked = $("#filterControls :checkbox:checked");
if(checked.length){
rows.hide(200);
checked.each(function(){
$("." + $(this).val()).show(200);
});
} else {
rows.show();
}
}

$("#filterControls :checkbox").click(filterFilesList);
filterFilesList();

Answer

You need to create the selector which is combination of all the filters

var selector = checked.map(function() {
    return "." + $(this).val()
}).get().join('');
$(selector).show(200);

Fiddle