#AD Top Online Web Development & Programming Courses | Udemy

Create an autocomplete search using vanilla JavaScript

Last modified March 24th 2022 | #js | GitHub Source Code [GitHub]

In this tutorial we’ll be creating an autocomplete search component using JavaScript. An autocomplete search is simply a HTML text input field that retrieves a set of possible results as a user inputs a search query.

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 an array that’ll populate the autocomplete results:

const data = ["red", "blue", "green", "yellow", "purple", "orange", "black", "white", "brown"];
Code language: JavaScript (javascript)

Next declare a variable that references the autocomplete input text and another that references 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. This function is triggered using the oninput event which fires anytime the value of the input text is changed:

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 larger data set of data than we’re using in this tutorial you may want to change userInput.length to > 3 to limit the results returned or there will be way too many suggestions returned at once.

In the previous step we called a getResults(userInput) function 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)

This function returns an array containing only the data matching the search query.

We now just need to add the functionality so when a result is clicked/selected it’s text is set as the autocomplete value:

resultsHTML.onclick = function (event) { const setValue = event.target.innerText; autocomplete.value = setValue; this.innerHTML = ""; };
Code language: JavaScript (javascript)

Open this code up in a browser and you should have a working autocomplete search box. This component can easily be styled for use in a production website or application. If you enjoyed this tutorial be sure to check out all our entire collection of JavaScript tutorials.

Related Posts

#AD Shop Web Developer T-Shirts