ImplementJavaScript Auto Complete / Suggestion feature

JavascriptWeb DevelopmentObject Oriented Programming

To implement JavaScript Auto Complete / Suggestion feature, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   body{
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>JavaScript Auto Complete / Suggestion feature</h1>
<input type="text" list="datalist" class="fruits" />
<datalist id="datalist">
<option value="orange"></option>
<option value="apple"></option>
<option value="pineapple"></option>
<option value="guava"></option>
<option value="mango"></option>
<option value="peach"></option>
<option value="pomegranate"></option>
<option value="litchi"></option>
</datalist>
<script type="text/javascript">
   var tags = ["orange", "apple","pineapple","guava","mango","pomegranate","litchi",];
   let check;
   document.querySelector(".fruits").addEventListener("keyup", (event) => {
      let value = event.target.value;
      document.getElementById("datalist").innerHTML = "";
      tags.forEach((item) => {
         if (item.toLowerCase().indexOf(value.toLowerCase()) > -1) {
            var opt = document.createElement("option");
            var sel = document.createTextNode(item);
            opt.appendChild(sel);
            document.getElementById("datalist").appendChild(opt);
         }
      });
   });
</script>
</body>
</html>

Output

On typing something in the input field −

raja
Published on 11-May-2020 14:16:17
Advertisements