Easy Tutorial
❮ Js Timestamp2Date Zookeeper Znode Data Model ❯

JavaScript Search Box Auto-Suggest

Category Programming Technology

This article introduces how to implement a search box suggestion feature, similar to Baidu search.

HTML Code:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search...">

<ul id="myUL">
  <li><a href="#" class="header">A</a></li>
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>

  <li><a href="#" class="header">B</a></li>
  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>

  <li><a href="#" class="header">C</a></li>
  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

Note: In the example, we used href="#". In actual applications, you need to replace it with your own URL.

CSS Code:

#myInput {
    background-image: url('https://static.tutorialpro.org/images/mix/searchicon.png'); /* Search icon */
    background-position: 10px 12px; /* Position the search icon */
    background-repeat: no-repeat; /* Do not repeat the image */
    width: 100%; 
    font-size: 16px; /* Increase font size */
    padding: 12px 20px 12px 40px; 
    border: 1px solid #ddd; 
    margin-bottom: 12px; 
}

#myUL {
    /* Remove default list styling */
    list-style-type: none;
    padding: 0;
    margin: 0;
}

#myUL li a {
    border: 1px solid #ddd; /* Add a border to links */
    margin-top: -1px; 
    background-color: #f6f6f6; 
    padding: 12px; 
    text-decoration: none;
    font-size: 18px; 
    color: black; 
    display: block; 
}

#myUL li a.header {
    background-color: #e2e2e2; 
    cursor: default; 
}

#myUL li a:hover:not(.header) {
    background-color: #eee;
}

JavaScript Code:

function myFunction() {
    // Declare variables
    var input, filter, ul, li, a, i;
    input = document.getElementById('myInput');
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName('li');

    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

Tip: If you need case sensitivity, you can remove the toUpperCase() method.

Online Demo

❮ Js Timestamp2Date Zookeeper Znode Data Model ❯