#AD "Ten++ Ways to Make Money as a Developer" eBook by Florin Pop - $20

Create an autocomplete textbox using vanilla JavaScript

Last modified November 17th 2020 | #js | GitHub Source Code [GitHub]

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>
Code language: HTML, XML (xml)

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"];
Code language: JavaScript (javascript)

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

const autocomplete = document.getElementById("autocomplete"); const resultsHTML = document.getElementById("results");
Code language: JavaScript (javascript)

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>"; } } };
Code language: JavaScript (javascript)

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; }
Code language: JavaScript (javascript)

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 = ""; };
Code language: JavaScript (javascript)

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

Related Posts