Help with modifying the code so I can sort by more than one filter. As an example, I'd like to be able to "check" BOTH Blue and Green, and have the result show two items. My code would work like that IF there is both 'blue green' in the data-colors area.
I know very little JavaScript, so any help would be appreciated!
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);
filterables.forEach(filterable => {
const colors = filterable.dataset.colors.split(' ');
if (checkedValues.every(value => colors.includes(value))) {
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="blue">Blue</label>
<label><input type="checkbox" class="filter-checkbox" value="green">Green</label>
<label><input type="checkbox" class="filter-checkbox" value="red">Red</label>
</div>
<div>
<h1>Filtered Result</h1>
<div class="filterable" data-colors="blue">Content 1</div>
<div class="filterable" data-colors="green">Content 2</div>
<div class="filterable" data-colors="red">Content 3</div>
</div>
someinstead ofevery? But definitely a duplicate