👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.

how to make checkbox filters javascript

There are several ways to make checkbox filters in JavaScript. Therefore, the general idea is always the same:

  • create the HTML list of items with a differentiating attribute (typically a class) ;
  • create HTML checkboxes and fire an event on change ;
  • when the event is fired, hide or show the item according to the checkbox status.


Here is an example (check the full code on jsfiddle):


Create items to filter:

<ul>
  <li class=".io"><a href="https://alphons.io">alphons.io</a></li>
  <li class=".com"><a href="https://google.com">google.com</a></li>
</ul>

Create checkboxes:

<div><input type="checkbox" id=".com" checked>  <label for=".com">.com</label></div>
<div><input type="checkbox" id=".io"  checked>  <label for=".io">.io</label></div>

Event listeners:

// Event for the checkboxes
document.getElementById('.com').onchange = function() { hideShow ('.com', this.checked); }
document.getElementById('.io').onchange = function() { hideShow ('.io', this.checked); }
document.getElementById('.org').onchange = function() { hideShow ('.org', this.checked); }

In the above code, we use a hideShow() function :

// Show or hide the element with class
// Show if visible = true, otherwise hide the element
function hideShow(myClass, visible) {	
  [].forEach.call(document.getElementsByClassName(myClass), function (el) { el.hidden = !visible;	});  
}

More