Real time text filter with JavaScript


Intermediate

This JavaScript filter search can be used to filter list of links, for example list of articles. It will search text between a tags and displays only the ones that are matching with search term. We will use vanilla JavaScript on this one.

 

HTML should look something like this. You need a input field for search and list of items you want to filter. Main point are ID’s so javascript can catch them.

<input id="filterInput" placeholder="Filter names"></input>

<ul class="listaus" id="names">
  <li class="name-item"><a href="URL HERE"><h3>Browallius, Johan</h3></a></li>
  <li class="name-item"><a href="URL HERE"><h3>Browallius, Johan</h3></a></li>
  <li class="name-item"><a href="URL HERE"><h3>Browallius, Johan</h3></a></li>
  <li class="name-item"><a href="URL HERE"><h3>Browallius, Johan</h3></a></li>
  <li class="name-item"><a href="URL HERE"><h3>Browallius, Johan</h3></a></li>
                        
           

</ul>

 

Final JavaScript code should look like this. First you get input element and add ‘keyup’ event listener to it. This way your list will update every time user type something to input field. This eventlistener will activate function filterNames.

Create function filterNames. First function will get value from our input field and store it to variable filterValue. Then we get ul and li variables based on ID’s in our HTML.

Next thing we need is a for loop. We store a elements to a variable. Then we make a if statement that checks innerHTML of these a tags and if it match filterValue variable we put display style to null and if not display style is none.

    // Get input element
    let filterInput = document.getElementById('filterInput');
    // Add event listener
    filterInput.addEventListener('keyup', filterNames);

    function filterNames(){
      // Get value of input
      let filterValue = document.getElementById('filterInput').value.toUpperCase();

      // Get names ul
      let ul = document.getElementById('names');
      // Get lis from ul
      let li = ul.querySelectorAll('li.name-item');

      // Loop through collection-item lis
      for(let i = 0;i < li.length;i++){
        let a = li[i].getElementsByTagName('a')[0];
        // If matched
        if(a.innerHTML.toUpperCase().indexOf(filterValue) > -1){
          li[i].style.display = '';
        } else {
          li[i].style.display = 'none';
        }
      }

    }