DEV Community

Michael Burrows
Michael Burrows

Posted on • Updated on • Originally published at w3collective.com

Create an autocomplete textbox using vanilla JavaScript

[Codepen Demo]

This article will cover the process of adding autocomplete functionality to a textbox with JavaScript.

Let’s start with the HTML markup:

<input type="text" id="autocomplete" placeholder="Select a color..."></input>
<ul id="results"></ul>
Enter fullscreen mode Exit fullscreen mode

Now for the JavaScript, starting with a data array that’ll be used to populate the autocomplete results:

const data = ["red", "blue", "green", "yellow", "purple", "orange", "black", "white", "brown"];
Enter fullscreen mode Exit fullscreen mode

Next declare some variables for the autocomplete input text and the results unordered list:

const autocomplete = document.getElementById("autocomplete");
const resultsHTML = document.getElementById("results");
Enter fullscreen mode Exit fullscreen mode

We’ll then create a function that outputs any data matching the users search query into the results list:

autocomplete.oninput = function () {
  let results = [];
  const userInput = this.value;
  resultsHTML.innerHTML = "";
  if (userInput.length > 0) {
    results = getResults(userInput);
    resultsHTML.style.display = "block";
    for (i = 0; i < results.length; i++) {
      resultsHTML.innerHTML += "<li>" + results[i] + "</li>";
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

If you have a large data set you may want to change userInput.length to > 3 to limit the length of the results.

In the previous step we called getResults(userInput) which doesn’t exist yet so let’s create it:

function getResults(input) {
  const results = [];
  for (i = 0; i < data.length; i++) {
    if (input === data[i].slice(0, input.length)) {
      results.push(data[i]);
    }
  }
  return results;
}
Enter fullscreen mode Exit fullscreen mode

What this function does is return a new array containing only the data matching the users search query.

Finally functionality for when a user clicks the results it’s text is set as the autocompletes value:

resultsHTML.onclick = function (event) {
  const setValue = event.target.innerText;
  autocomplete.value = setValue;
  this.innerHTML = "";
};
Enter fullscreen mode Exit fullscreen mode

Add some CSS and you’ve got yourself a fully functioning autocomplete textbox.

Top comments (5)

Collapse
 
tbroyer profile image
Thomas Broyer

Most of the time, you won't want to implement it yourself: how about keyboard use? How about accessibility?

At a minimum, the native <datalist> should do better than your solution, with even fewer code (no JS \o/ )
caniuse.com/#feat=datalist

Collapse
 
dailydevtips1 profile image
Chris Bongers

Datalist is nice, but only limited styling and browser support is a bit of a gamble at this point, with Partial support.

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak • Edited

Datalist is unfortunately really really "user unfriendly" on mobile. Just open your iPhone and try it for yourself.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey, you can also embed the full Codepen to render in your article (i only learned this recently) There is a small docs next to making your post it shows all embeds.

Also agree with Thomas, Datalist would be a nice html solution

Collapse
 
michaelburrows profile image
Michael Burrows

Thanks for the tip re:Codepen :)