JSFiddle - React, Tailwind, and code Playground

by Yesha Shah

HTML

<div class="autocomplete" style="width:300px;">
  <input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>

JavaScript

var countries = [{
  "value": "Afghanistan, Pakistan",
  "label": "Afghanistan"
}, {
  "value": "Albania, Balkans",
  "label": "Albania"
}, {
  "value": "Andorra",
  "label": "Andorra"
}, {
  "value": "Angola , Anguilla",
  "label": "Anguilla"
}, {
  "value": "Antigua & Barbuda",
  "label": "Antigua & Barbuda"
}, {
  "value": "Armenia",
  "label": "Armenia"
}];

function autocomplete(inp, arr) {
  var currentFocus;
  inp.addEventListener("input", function(e) {
    var a, b, i, val = this.value;
    closeAllLists();
    if (!val) {
      return false;
    }
    currentFocus = -1;
    a = document.createElement("DIV");
    a.setAttribute("id", this.id + "autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    this.parentNode.appendChild(a);
    for (i = 0; i < arr.length; i++) {
      var itemLabel = arr[i].label,
        itemValue = arr[i].value;
      if (itemLabel.substr(0, val.length).toUpperCase() === val.toUpperCase()) {
        b = document.createElement("DIV");
        b.innerHTML = "<strong>" + itemLabel.substr(0, val.length) + "</strong>";
        b.innerHTML += itemLabel.substr(val.length);
        b.innerHTML += "<input type='hidden' value='" + itemValue + "'>";
        b.addEventListener("click", function(e) {
          inp.value = this.getElementsByTagName("input")[0].value;
          closeAllLists();
        });
        a.appendChild(b);
      }
    }
  });
  inp.addEventListener("keydown", function(e) {
    var x = document.getElementById(this.id + "autocomplete-list");
    if (x)
      x = x.getElementsByTagName("div");
    if (e.keyCode === 40) {
      currentFocus++;
      addActive(x);
    } else if (e.keyCode === 38) {
      currentFocus--;
      addActive(x);
    } else if (e.keyCode === 13) {
      e.preventDefault();
      if (currentFocus > -1) {
        if (x)
          x[currentFocus].click();
      }
    }
  });

  function addActive(x) {
    if (!x)
      return false;
    removeActive(x);
    if (currentFocus >=...