hypern00b
hypern00b

Reputation: 350

Checkbox and Filtering Items with JS

I'm trying to build a set of filters using checkboxes.

For example, I have:

and want to be able to filter based on the color AND the shape. I'm having difficulty.

If you run the code in this post, you'll see that my .querySelector() method is not pulling in all the elements with the '.red' class. It's only altering the first element with that class name, not every element with the class name. If I use the .querySelectorAll() method I also have no luck.

My desired outcome is checkboxes that are "red only", "blue only", "circles only", and "squares only" and that can have MORE THAN ONE filter active at a time.

Any help is appreciated.

const allRedItems = document.querySelector(".red");

const checkBox = document.querySelector('#hide');

checkBox.addEventListener('change', function(e){
  if (hide.checked){allRedItems.style.display = "none";} 
  else { allRedItems.style.display = "inline-block"; }
});
div {
  height:100px;
  width:100px;
  border:1px solid #ccc;
  display:inline-block;
  margin:2rem;
}

.red {
  background-color:red;
}

.blue {
  background-color:blue;
}

.square {
  border-radius:5px;
}

.circle {
  border-radius:50%;
}
<div class="red circle"></div>
<div class="red square"></div>
<div class="blue circle"></div>
<div class="blue square"></div>
<br>
<input type="checkbox" id="hide">
<label for="hide">Hide All Red Elements</label>

Upvotes: 1

Views: 197

Answers (1)

MirroredFate
MirroredFate

Reputation: 12816

Documentation on querySelector

returns the first Element within the document that matches the specified selector

The function you are looking for is querySelectorAll

The Element method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Because it will return an array of elements rather than a single element, make sure you iterate through the array.

const allRedItems = document.querySelectorAll(".red");

const checkBox = document.querySelector('#hide');

checkBox.addEventListener('change', function(e){
    allRedItems.forEach( function(item) {
        if (hide.checked){ 
            item.style.display = "none";
        }
        else { 
            item.style.display = "inline-block"; 
       }
  });
});
div {
  height:100px;
  width:100px;
  border:1px solid #ccc;
  display:inline-block;
  margin:2rem;
}

.red {
  background-color:red;
}

.blue {
  background-color:blue;
}

.square {
  border-radius:5px;
}

.circle {
  border-radius:50%;
}
<div class="red circle"></div>
<div class="red square"></div>
<div class="blue circle"></div>
<div class="blue square"></div>
<br>
<input type="checkbox" id="hide">
<label for="hide">Hide All Red Elements</label>

As a final note, you should be able to build a function to create the query string needed for querying, based on the selected boxes.

Upvotes: 2

Related Questions