I have two checkboxes to filter through recipes (stored on a database) on a website. The allergy filter HIDES all the recipes with the allergy selected but the diet filter SHOWS only the recipes with the diet selected. (i.e. if the user checks the peanut allergy and gluten free it will hide recipes with those filters.) Both checkboxes work individually, but having both of them checked shows the wrong recipes. For example, what I want to happen is if the user checks off peanut allergy and the vegan diet, I want to show recipes that have no peanuts and are vegan. I basically need a way to keep track of what recipes are showing from one checkbox and filter through those for the other checkbox.
Below is the code I have:
function filterFilesList() {
var rows = $('.file-row');
var checkedAllergies = $("#filterControlsAllergies :checkbox:checked");
var checkedDiet = $("#filterControlsDiet :checkbox:checked");
if(checkedAllergies.length && checkedDiet.length){
console.log("both selected");
rows.show(200);
var type1 = []
var arr = checkedAllergies.map(function(){
type1.push("." + $(this).val())
}).get();
var type2 = []
var arr = checkedDiet.map(function(){
type2.push("." + $(this).val())
}).get();
//Filter through database and show/hide recipes depending on both checkboxes
} else if(checkedAllergies.length){
rows.show(200);
var type1 = []
var arr = checkedAllergies.map(function(){
type1.push("." + $(this).val())
}).get();
for (let i = 0; i < type1.length; i++){
$(type1[i]).hide(200);
}
} else if(checkedDiet.length){
rows.hide(200);
var type2 = []
var arr = checkedDiet.map(function(){
type2.push("." + $(this).val())
}).get();
for (let i = 0; i < type2.length; i++){
$(type2[i]).show(200);
}
} else {
rows.show();
}
}
you have two different ways to solve this problem.
Please check code below:
if(checkedAllergies.length && checkedDiet.length){
rows.hide(200);
var type1 = []
checkedAllergies.map(function(){
type1.push("." + $(this).val())
}).get();
//let's create set of allergies recipes, that we need to exclude
let allergiesSet = new Set();
for(let i=0;i<type1.length;i++){
allergiesSet.add(type1[i]);
}
var type2 = []
var arr = checkedDiet.map(function(){
type2.push("." + $(this).val());
}).get();
//Filter through database and show/hide recipes depending on both checkboxes
for (let i = 0; i < type2.length; i++){
if(!allergiesSet.has(type2[i])) {$(type2[i]).show(200);};
}
}