Make a filter with oninput Event

Posted by on August 23, 2017

Maybe the most awesome event that javascript has to offer. It looks so hard to create a filter for a list but with this event things cannot get any easier.

Lets take for example a small list fruits:

<ul id="list">
 <li>Orange</li>
 <li>Red</li>
 <li>Yellow</li>
 <li>Blue</li>
 <li>Black</li>
</ul>
  • Orange
  • Red
  • Yellow
  • Blue
  • Black

 

and just before them we add a input field

<input oninput="filter('#list>li',this.value)">

 

and finally the script

<script>
function filter(query,value) {
 var list = document.querySelectorAll(query)

 list.forEach(function(entry){
  if(!entry.innerHTML.includes(value))
   entry.style.display='none';
  else
   entry.style.display='list-item';
 })
}
</script>