I’m new to javascript and have some code that filters products based on color and size. It works great, but I’m wondering if it’s possible to have the javascript also SUBTRACT products based on two filters.
For example; if you check all the color filters it shows all the products, great. But as soon as I check "small" for example, it still shows all the products since it’s using the filters values from Color.
Is there a way to have it only show "Product B", which has a data filter of a color AND small?
Thanks for your help!
const filterCheckboxes = document.querySelectorAll('.filter-checkbox');
const filterables = document.querySelectorAll('.filterable');
function updateFilter() {
const checkedValues = Array.from(filterCheckboxes)
.filter(checkbox => checkbox.checked)
.map(checkbox => checkbox.value);
if (!checkedValues.length > 0) {
filterables.forEach(filterable => {
filterable.style.display = 'block';
})
return;
}
filterables.forEach(filterable => {
const colors = filterable.dataset.colors.split(' ');
if (checkedValues.some(value => colors.includes(value)) || checkedValues.length === 0) {
filterable.style.display = 'block';
} else {
filterable.style.display = 'none';
}
});
}
filterCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', updateFilter);
});
updateFilter(); // initial filter based on default checkbox state
<div>
<h3>Color</h3>
<label><input type="checkbox" class="filter-checkbox" value="red">Red</label>
<label><input type="checkbox" class="filter-checkbox" value="green">Green</label>
<label><input type="checkbox" class="filter-checkbox" value="blue">Blue</label>
</div>
<div>
<h3>Size</h3>
<label><input type="checkbox" class="filter-checkbox" value="small">Small</label>
<label><input type="checkbox" class="filter-checkbox" value="medium">Medium</label><label>
<input type="checkbox" class="filter-checkbox" value="large">Large</label>
</div>
<div>
<h1>Filtered Result</h1>
<div class="filterable" data-colors="blue large">Product A</div>
<div class="filterable" data-colors="green small">Product B</div>
<div class="filterable" data-colors="red medium">Product C</div>
<div class="filterable" data-colors="red large">Product D</div>
</div>
I was hoping that Javascript can also subtract products based on multiple values.
2
Answers
For it to work as desired, you should better identify what each value is an instance of (either color or size):
div
of a checkbox group a CSS class that names the dimension (color or size)data-colors
attributes bydata-color
anddata-size
attributesincludes
test for color and for sizeHere is how it could be coded:
You have to check if the element has the N filters values, there is a example code: