Filterable Contact List With JavaScript

Category: Javascript | April 16, 2018
Author: karabayse
Views Total: 47
Official Page: Go to website
Last Update: April 16, 2018
License: MIT

Preview:

Filterable Contact List With JavaScript

Description:

Makes use of JavaScript to enable a search input to filter your long contact list.

How to use it:

Add a search input to the contact list as these:

<input type="text" id="filterInput" placeholder="Search names...">
<ul id="names" class="collection with-header">
  <li class="collection-header">
    <h5>A</h5>
  </li>
  <li class="collection-item">
    <a href="#">Abe</a>
  </li>
  <li class="collection-item">
    <a href="#">Adam</a>
  </li>
  <li class="collection-item">
    <a href="#">Alan</a>
  </li>
  <li class="collection-item">
    <a href="#">Anna</a>
  </li>
  <li class="collection-header">
    <h5>B</h5>
  </li>
  <li class="collection-item">
    <a href="#">Beth</a>
  </li>
  <li class="collection-item">
    <a href="#">Bill</a>
  </li>
  <li class="collection-item">
    <a href="#">Bob</a>
  </li>
  <li class="collection-item">
    <a href="#">Brad</a>
  </li>
  <li class="collection-header">
    <h5>C</h5>
  </li>
  <li class="collection-item">
    <a href="#">Carrie</a>
  </li>
  <li class="collection-item">
    <a href="#">Cathy</a>
  </li>
  <li class="collection-item">
    <a href="#">Connor</a>
  </li>
  <li class="collection-item">
    <a href="#">Courtney</a>
  </li>
</ul>
</div>

The main JavaScript to enable the filter functionality.

// Get input element
let filterInput = document.getElementById('filterInput');

// Add event listener
filterInput.addEventListener('keyup', filterNames);

function filterNames() {
  console.log('in filterNames');
  // Get value of input
  let filterValue = document.getElementById('filterInput').value.toUpperCase();
  console.log(filterValue);
  // Get names ul
  let ul = document.getElementById('names');
  // Get lis from ul
  let li = ul.querySelectorAll('li.collection-item');
  // Loop through collection-item lis
  for (let i = 0; i < li.length; i++) {
     let a = li[i].getElementsByTagName('a')[0];
     // If matched -> a.innerHTML grabs whatever is inside the 'a' tag
     if (a.innerHTML.toUpperCase().indexOf(filterValue) > -1) {
       li[i].style.display = '';
     } else {
       li[i].style.display = 'none';
     }
   }
}

 

Leave a Reply