Hi, I have created a filter function but it does not work as intended. I really don’t understand why it doesn’t work, and I would really appreciate if someone could tell me what the problem is and point me in the right direction. Other ways to do it is good, but what I really want to know is whats wrong with my code and why it does not work.
The idea is simple, see if checkboxes is checked, then push them to an array (isChecked or unChecked). For classes that is in isChecked array, change to display: block, otherwise display: none.
So what is the problem?
When I check both boxes and then uncheck one, the divs that contains two classes (both animals and cars) disappears. It should have display block because one of them is in the isChecked array… It works when both is unchecked and I check one.
Any ideas what I am doing wrong?
Javascript:
let anotherOne = (x) => {
let all = document.getElementsByClassName('filterDiv'); //all filterable divs
let checkBoxCars = document.getElementById('cars');
let checkBoxAnimals = document.getElementById('animals');
let elements = document.getElementsByClassName(x); //divs with selected class
//Empty arrays for pushing checked and unchecked boxes.
let isChecked = []
let unChecked = []
if (checkBoxCars.checked == true) {
isChecked.push('cars')
} else {
unChecked.push('cars')
}
if (checkBoxAnimals.checked == true) {
isChecked.push('animals')
} else {
unChecked.push('animals')
}
//if checkbox value is in checked array then
if (isChecked.indexOf(x) > -1) {
//In the array
for (i = 0; i < elements.length; i++) {
elements[i].style.display = "block";
}
} else {
//Not in the array
for (i = 0; i < elements.length; i++) {
elements[i].style.display = "none";
}
}
//If all checkboxes is unset, show all
if (isChecked.length == 0) {
for (i = 0; i < all.length; i++) {
all[i].style.display = "block";
}
}
}
HTML:
<body>
<div id="myBtnContainer">
<input type="checkbox" id="cars" onclick="anotherOne('cars')">
<label for="cars">cars</label>
<input type="checkbox" id="animals" onclick="anotherOne('animals')">
<label for="animals">animals</label>
</div>
<!-- The filterable elements. Note that some have multiple class names (this can be used if they belong to multiple categories) -->
<div class="container">
<div id="cars" class="filterDiv show cars">BMW</div>
<div class="filterDiv show cars animals">CarDog1</div>
<div class="filterDiv show cars">Volvo</div>
<div class="filterDiv show cars">Mustang</div>
<div class="filterDiv show animals">Cat</div>
<div class="filterDiv show animals">Dog</div>
<div class="filterDiv show cars animals">CarDog2</div>
<div class="filterDiv show animals">Cow</div>
</div>
</body>