Auto complete as you type in JavaScript

Tags: ,



I was looking the w3cschool link for auto complete as you type.

https://www.w3schools.com/howto/howto_js_autocomplete.asp

The above only works for the first ordering for names eg. If country name is United States. You need to type Uni and it shows in drop-down. How to make it work if you type any letter eg ted or state so it still shows. United States in drop down.

Answer

All you need is do a includes string comparison instead of starts With and you should be all set if you just show the matching country instead f substring of matching text.

if (arr[i].toUpperCase().includes(val.toUpperCase())) {
  /*create a DIV element for each matching element:*/
  b = document.createElement("DIV");
  /*make the matching letters bold:*/
  b.innerHTML = "<strong>" + arr[i] + "</strong>";

https://jsfiddle.net/9ym4Lcta/1/



Source: stackoverflow