Create an autocomplete textbox using vanilla JavaScript

Last modified on August 30th 2020 GitHub [Source] 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>

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"];

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

const autocomplete = document.getElementById("autocomplete"); const resultsHTML = document.getElementById("results");

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>"; } } };

If you have a large data set you may want to change userInput.length to > 3 to limit 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; }

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 = ""; };

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