Autocomplete in Javascript /HTML - find array index of clicked value

41 Views Asked by At

Its my first post, so thanks in advance, and I hope I have posted correctly. I am using the "autocomplete" code at W3Schools

(JS part of the code is below). On event "click", I need to find the array index of the clicked result. In my adapted version I have added a hidden value for the array index under with an "id" of 'place_Index'. However, the Event Listener (and !e.target!) return the string result from the Input text box (i.e. not the inner.HTML / hidden values).

JS code below

Even if I find a way to access the 'place_Index' value, the result is the index of the first item in the autocomplete-list, not the index for the selected item. I am still a 'noob' so would rather achieve this with Vanilla JS rather than via a Library / plug in. I genuinely have searched Stackoverflow, and the web, but cant locate an answer that produces the required result. Thanks in advance.

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] + "'>";
**          b.innerHTML += "<input type='hidden' name = 'place_Index' id = 'place_Index' value='" + Div_Array_Counter + "'>";**
          /*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 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 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);
});
}
autocomplete(document.getElementById("myInput"), countries);
1

There are 1 best solutions below

3
IT goldman On

I offer you my "library" for autocomplete. I probably used the same W3Schools tutorial because code is similar.

I also "connected" it with google suggest, but you should override the function suggest(word, callback) to search your list of countries.

function autocomplete(inp, foo_selected) {
  /**
   * must be inside relative wrapper or a <div class="autocomplete">
   */
  var noop = function() {}
  var currentFocus;

  function suggest(word, callback) {
    var script = document.createElement('script')
    var src = 'https://www.google.com/complete/search?client=gws-wiz&q=' + encodeURIComponent(word)
    script.async = true;
    script.src = src;
    document.head.appendChild(script)

    window.google = {
      ac: {
        h: callback
      }
    }
  }

  inp.addEventListener("input", function(ev) {
    var container, item, val = this.value;
    if (!val) {
      closeAllLists();
      return false;
    }
    var self = this;

    function foo_got_arr(arr) {
      closeAllLists();

      var terms = arr[0]
      terms = terms.map(word => stripHtml(word[0]));

      arr = terms;

      currentFocus = -1;
      container = document.createElement("DIV");
      container.setAttribute("id", self.id + "autocomplete-list");
      container.setAttribute("class", "autocomplete-items");
      self.parentNode.appendChild(container);
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          item = document.createElement("DIV");
          item.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          item.innerHTML += arr[i].substr(val.length);
          item.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          item.addEventListener("click", function(ev) {
            inp.value = this.getElementsByTagName("input")[0].value;
            closeAllLists();
            typeof foo_selected === 'function' && foo_selected(inp.value);
          });
          container.appendChild(item);
        }
      }
    }

    suggest(val, foo_got_arr)

  });

  function addActive(x) {
    if (!x) {
      return false;
    }
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    x[currentFocus].classList.add("autocomplete-active");

    inp.value = x[currentFocus].innerText;
    caret2End(inp)

  }

  function closeAllLists(elem) {
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elem != x[i] && elem != inp) {
        x[i].remove();
      }
    }

    window.google = {
      ac: {
        h: noop
      }
    }
  }

  function stripHtml(html) {
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || "";
  }

  function caret2End(input) {
    input.blur();
    setTimeout(function() {
      input.focus();
    })
  }

  inp.addEventListener("keydown", function(ev) {
    var x = document.getElementById(this.id + "autocomplete-list");
    if (x) {
      x = x.getElementsByTagName("div");
    }
    if (ev.keyCode == 40) {
      currentFocus++;
      addActive(x);
      ev.preventDefault();
    } else if (ev.keyCode == 38) {
      currentFocus--;
      addActive(x);
      ev.preventDefault();
    } else if (ev.keyCode == 27) {
      closeAllLists();
    } else if (ev.keyCode == 13) {
      closeAllLists();
      typeof foo_selected === 'function' && foo_selected(inp.value);

    }
  });

  document.addEventListener("click", function(ev) {
    closeAllLists(ev.target);
  });
}


// USAGE:

autocomplete(input, function(value) {
  alert("you chosen: " + value)
})
.autocomplete {
  /*the container must be positioned relative! */
  position: relative;
}

.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  top: 100%;
  left: 0;
  right: 0;
}

.autocomplete-items div {
  padding: 0 .2em;
  cursor: pointer;
  background-color: rgba(255, 255, 255, 0.75);
  color: black;
  border-bottom: 1px solid #d4d4d4;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.autocomplete-items div:hover {
  background-color: #e9e9e9;
  opacity: 1;
}

.autocomplete-active {
  background-color: DodgerBlue !important;
  color: #ffffff;
  opacity: 1 !important;
}
<div class="autocomplete">
  <input id="input" placeholder="Search...">
</div>

Here's a more generic version!

function autocomplete(inp, foo_suggest, foo_selected) {
  /**
   * must be inside relative wrapper or a <div class="autocomplete">
   */
  var currentFocus;

  inp.addEventListener("input", function(ev) {
    var container, item, val = this.value;
    if (!val) {
      closeAllLists();
      return false;
    }
    var self = this;

    function foo_got_arr(arr) {
      closeAllLists();

      currentFocus = -1;
      container = document.createElement("DIV");
      container.setAttribute("id", self.id + "autocomplete-list");
      container.setAttribute("class", "autocomplete-items");
      self.parentNode.appendChild(container);
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          item = document.createElement("DIV");
          item.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          item.innerHTML += arr[i].substr(val.length);
          item.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          item.addEventListener("click", function(ev) {
            inp.value = this.getElementsByTagName("input")[0].value;
            closeAllLists();
            typeof foo_selected === 'function' && foo_selected(inp.value);
          });
          container.appendChild(item);
        }
      }
    }

    foo_suggest(val, foo_got_arr)

  });

  function addActive(x) {
    if (!x) {
      return false;
    }
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    x[currentFocus].classList.add("autocomplete-active");

    inp.value = x[currentFocus].innerText;
    caret2End(inp)

  }

  function closeAllLists(elem) {
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elem != x[i] && elem != inp) {
        x[i].remove();
      }
    }
  }

  function caret2End(input) {
    input.blur();
    setTimeout(function() {
      input.focus();
    })
  }

  inp.addEventListener("keydown", function(ev) {
    var x = document.getElementById(this.id + "autocomplete-list");
    if (x) {
      x = x.getElementsByTagName("div");
    }
    if (ev.keyCode == 40) {
      currentFocus++;
      addActive(x);
      ev.preventDefault();
    } else if (ev.keyCode == 38) {
      currentFocus--;
      addActive(x);
      ev.preventDefault();
    } else if (ev.keyCode == 27) {
      closeAllLists();
    } else if (ev.keyCode == 13) {
      closeAllLists();
      typeof foo_selected === 'function' && foo_selected(inp.value);

    }
  });

  document.addEventListener("click", function(ev) {
    closeAllLists(ev.target);
  });
}


// USAGE:

function suggest_google(word, callback) {
  var script = document.createElement('script')
  var src = 'https://www.google.com/complete/search?client=gws-wiz&q=' + encodeURIComponent(word)
  script.async = true;
  script.src = src;
  document.head.appendChild(script)

  var noop = function() {}

  var foo_normlize = (function(result) {
    var arr = result[0].map(function(item) {
      return stripHtml(item[0])
    })

    window.google = {
      ac: {
        h: noop
      }
    }
    callback(arr)
  })

  function stripHtml(html) {
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || "";
  }

  window.google = {
    ac: {
      h: foo_normlize
    }
  }
}

function suggest_country(word, callback) {

  const countries = [`Afghanistan`, `Albania`, `Algeria`, `Andorra`, `Angola`, `Antigua and Barbuda`, `Argentina`, `Armenia`, `Australia`, `Austria`, `Azerbaijan`, `Bahamas`, `Bahrain`, `Bangladesh`, `Barbados`, `Belarus`, `Belgium`, `Belize`, `Benin`, `Bhutan`, `Bolivia`, `Bosnia and Herzegovina`, `Botswana`, `Brazil`, `Brunei`, `Bulgaria`, `Burkina Faso`, `Burundi`, `Côte d'Ivoire`, `Cabo Verde`, `Cambodia`, `Cameroon`, `Canada`, `Central African Republic`, `Chad`, `Chile`, `China`, `Colombia`, `Comoros`, `Congo (Congo-Brazzaville)`, `Costa Rica`, `Croatia`, `Cuba`, `Cyprus`, `Czechia (Czech Republic)`, `Democratic Republic of the Congo`, `Denmark`, `Djibouti`, `Dominica`, `Dominican Republic`, `Ecuador`, `Egypt`, `El Salvador`, `Equatorial Guinea`, `Eritrea`, `Estonia`, `Eswatini (fmr. "Swaziland")`, `Ethiopia`, `Fiji`, `Finland`, `France`, `Gabon`, `Gambia`, `Georgia`, `Germany`, `Ghana`, `Greece`, `Grenada`, `Guatemala`, `Guinea`, `Guinea-Bissau`, `Guyana`, `Haiti`, `Holy See`, `Honduras`, `Hungary`, `Iceland`, `India`, `Indonesia`, `Iran`, `Iraq`, `Ireland`, `Israel`, `Italy`, `Jamaica`, `Japan`, `Jordan`, `Kazakhstan`, `Kenya`, `Kiribati`, `Kuwait`, `Kyrgyzstan`, `Laos`, `Latvia`, `Lebanon`, `Lesotho`, `Liberia`, `Libya`, `Liechtenstein`, `Lithuania`, `Luxembourg`, `Madagascar`, `Malawi`, `Malaysia`, `Maldives`, `Mali`, `Malta`, `Marshall Islands`, `Mauritania`, `Mauritius`, `Mexico`, `Micronesia`, `Moldova`, `Monaco`, `Mongolia`, `Montenegro`, `Morocco`, `Mozambique`, `Myanmar (formerly Burma)`, `Namibia`, `Nauru`, `Nepal`, `Netherlands`, `New Zealand`, `Nicaragua`, `Niger`, `Nigeria`, `North Korea`, `North Macedonia`, `Norway`, `Oman`, `Pakistan`, `Palau`, `Palestine State`, `Panama`, `Papua New Guinea`, `Paraguay`, `Peru`, `Philippines`, `Poland`, `Portugal`, `Qatar`, `Romania`, `Russia`, `Rwanda`, `Saint Kitts and Nevis`, `Saint Lucia`, `Saint Vincent and the Grenadines`, `Samoa`, `San Marino`, `Sao Tome and Principe`, `Saudi Arabia`, `Senegal`, `Serbia`, `Seychelles`, `Sierra Leone`, `Singapore`, `Slovakia`, `Slovenia`, `Solomon Islands`, `Somalia`, `South Africa`, `South Korea`, `South Sudan`, `Spain`, `Sri Lanka`, `Sudan`, `Suriname`, `Sweden`, `Switzerland`, `Syria`, `Tajikistan`, `Tanzania`, `Thailand`, `Timor-Leste`, `Togo`, `Tonga`, `Trinidad and Tobago`, `Tunisia`, `Turkey`, `Turkmenistan`, `Tuvalu`, `Uganda`, `Ukraine`, `United Arab Emirates`, `United Kingdom`, `United States of America`, `Uruguay`, `Uzbekistan`, `Vanuatu`, `Venezuela`, `Vietnam`, `Yemen`, `Zambia`, `Zimbabwe`]

  var result = countries.filter(function(country) {
    return country.toLowerCase().indexOf(word.toLowerCase()) >= 0
  })

  callback(result)
}

autocomplete(input, suggest_google, function(value) {
  alert("you chosen: " + value)
})

autocomplete(input2, suggest_country, function(value) {
  alert("you chosen: " + value)
})
.autocomplete {
  /*the container must be positioned relative! */
  position: relative;
}

.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  top: 100%;
  left: 0;
  right: 0;
}

.autocomplete-items div {
  padding: 0 .2em;
  cursor: pointer;
  background-color: rgba(255, 255, 255, 0.75);
  color: black;
  border-bottom: 1px solid #d4d4d4;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.autocomplete-items div:hover {
  background-color: #e9e9e9;
  opacity: 1;
}

.autocomplete-active {
  background-color: DodgerBlue !important;
  color: #ffffff;
  opacity: 1 !important;
}
<div style="display:flex">

  <div class="autocomplete">
    <input id="input" placeholder="Search google...">
  </div>

  <div class="autocomplete">
    <input id="input2" placeholder="Search country...">
  </div>

</div>