Easy Tutorial
❮ Android Tutorial Alertdialog Detect Empty Javascript Object ❯

JavaScript Implementation of Search Box Autocomplete Functionality

Category Programming Technology

In this section, we will learn how to implement search box autocomplete functionality using JS/CSS.

First, take a look at the effect:

View the live example: https://c.tutorialpro.org/codedemo/6190

Basic HTML Code

Example

<!-- autocomplete="off" ensures the form has autocomplete functionality turned off: -->
<form autocomplete="off" action="/index.php">
  <div class="autocomplete" style="width:300px;">
    <input id="myInput" type="text" name="s" placeholder="Please enter search content">
  </div>
  <input type="submit">
</form>

Next, prepare the basic search test data, which is a JavaScript array:

var sites = ["Google","Taobao","tutorialpro","Wiki","Zhihu","Baidu","Sina","Tmall","JD","Alibaba","QQ","Weixin"];

Here is the style for the search box and autocomplete menu:

Example

* { box-sizing: border-box; }
body {
  font: 16px Arial;
}
.autocomplete {
  /* Set container position to relative: */
  position: relative;
  display: inline-block;
}
input {
  border: 1px solid transparent;
  background-color: #f1f1f1;
  padding: 10px;
  font-size: 16px;
}
input[type=text] {
  background-color: #f1f1f1;
  width: 100%;
}
input[type=submit] {
  background-color: DodgerBlue;
  color: #fff;
}
.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  /* Set autocomplete items width to match the container */
  top: 100%;
  left: 0;
  right: 0;
}
.autocomplete-items div {
  padding: 10px;
  cursor: pointer;
  background-color: #fff;
  border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
  /* Background color for autocomplete items when hovered */
  background-color: #e9e9e9;
}
.autocomplete-active {
  /* Background color for autocomplete items when navigating with arrow keys */
  background-color: DodgerBlue !important;
  color: #ffffff;
}

Here is the JavaScript code for the search box and autocomplete menu:

Example

function autocomplete(inp, arr) {
  /* The autocomplete function takes two arguments, the text field element and an array of possible autocompleted values: */
  var currentFocus;
  /* Execute a function when someone writes in the text field: */
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      /* Close any already open lists of autocompleted values */
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /* Create a DIV element that will contain the items (values): */
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      /* Append the DIV element as a child of the autocomplete container: */
      this.parentNode.appendChild(a);
      /* For each item in the array... */
      for (i = 0; i < arr.length; i++) {
        /* Check if the item starts with the same letters as the text field value: */
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          /* Create a DIV element for each matching element: */
          b = document.createElement("DIV");
          /* Make the matching letters bold: */
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          /* Insert a input field that will hold the current array item's value: */
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
              /* Execute a function when someone clicks on the item value (DIV element): */
              b.addEventListener("click", function(e) {
              /* Insert the value for the autocomplete text field: */
              inp.value = this.getElementsByTagName("input")[0].value;
              /* Close the list of autocompleted values, (or any other open lists of autocompleted values: */
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  /* Execute a function presses a key on the keyboard: */
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /* If the arrow DOWN key is pressed, increase the currentFocus variable: */
        currentFocus++;
        /* And make the current item more visible: */
        addActive(x);
      } else if (e.keyCode == 38) { //up
        /* If the arrow UP key is pressed, decrease the currentFocus variable: */
        currentFocus--;
        /* And make the current item more visible: */
        addActive(x);
      } else if (e.keyCode == 13) {
        /* If the ENTER key is pressed, prevent the form from being submitted, */
        e.preventDefault();
        if (currentFocus > -1) {
          /* and simulate a click on the "active" item: */
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    /* A function to classify an item as "active": */
    if (!x) return false;
    /* Start by removing the "active" class on all items: */
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /* Add class "autocomplete-active": */
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    /* A function to remove the "active" class from all autocomplete items: */
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    /* Close all autocomplete lists in the document, except the one passed as an argument: */
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
      x[i].parentNode.removeChild(x[i]);
    }
  }
}
/* Execute a function when someone clicks in the document: */
document.addEventListener("click", function (e) {
    closeAllLists(e.target);
});
}

Finally, we use the above JavaScript code on the input field with id myInput:

Example

autocomplete(document.getElementById("myInput"), countries);

** Click to Share Notes

Cancel

-

-

-

❮ Android Tutorial Alertdialog Detect Empty Javascript Object ❯