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 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;
}
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.
Top comments (5)
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
Datalist is nice, but only limited styling and browser support is a bit of a gamble at this point, with Partial support.
Datalist is unfortunately really really "user unfriendly" on mobile. Just open your iPhone and try it for yourself.
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
Thanks for the tip re:Codepen :)