A simple AutoComplete feature using JSON and JavaScript includes() method

← Prev

The example here shows how to create a simple AutoComplete textbox feature using data from an Array and using the includes() method.

Let us assume, I have a list of birds stored in an array. I want to search for birds using a character or two. It’s like a look-up, similar to an AutoComplete feature.

🚀 Related example: How to convert JSON to an HTML table dynamically using JavaScript?

<!DOCTYPE html>
<html>
<head>
  <title>AutoComplete feature using JSON and JavaScript includes() Method</title>

  <style>
    ul {
      list-style: none;
      padding: 0px;
      margin: 10px 0;
    }

    input, div, ul {
      font-size: 18px;
    }
  </style>
</head>
<body>
  <input id="tbFind" placeholder='Enter search term' onkeyup="find(this.value)" />
  
  <div id="list"></div>
</body>
<script>
  // JSON array.
  const birds = ['Eurasian Collared-Dove', 'Bald Eagle',
                 'Coopers Hawk', 'Mourning Dove', 'Bells Sparrow',
                 'Rock Pigeon', 'Aberts Towhee', 'Brewers Sparrow',
                 'Canyon Towhee', 'Black Vulture', 'Gila Woodpecker'];

  let find = (term) => {
    document.getElementById('list').innerHTML = '';
    if (term != '') {

      const ul = document.createElement('ul'); 

      for (let i = 0; i < birds.length; i++) {
        if (birds[i].includes(term)) {
          let li = document.createElement('li');
          ul.appendChild(li);
          li.innerHTML = birds[i];
          li.setAttribute('onclick', 'showValue(this)');   // ATTACH AN EVENT.
        }
      }
      document.getElementById('list').appendChild(ul);
    }
    else {
      document.getElementById('list').innerHTML = '';
    }
  }

  const showValue = (ele) => {
    let t = document.getElementById('tbFind');
    t.value = ele.innerHTML;

    document.getElementById('list').innerHTML = '';
  }
</script>
</html>
Try it

➡️ Advance autocomplete features using jQuery

← Previous