Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created March 23, 2022 23:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3collective/78abc33dbeb0c4e700e9856ccfe62536 to your computer and use it in GitHub Desktop.
Save w3collective/78abc33dbeb0c4e700e9856ccfe62536 to your computer and use it in GitHub Desktop.
Autocomplete search using vanilla JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Create an autocomplete search using vanilla JavaScript</title>
</head>
<body>
<div>
<input type="text" id="autocomplete" placeholder="Select a color..."></input>
<ul id="results"></ul>
</div>
<script>
const data = ["red", "blue", "green", "yellow", "purple", "orange", "black", "white", "brown"];
const autocomplete = document.getElementById("autocomplete");
const resultsHTML = document.getElementById("results");
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>";
}
}
};
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;
}
resultsHTML.onclick = function (event) {
const setValue = event.target.innerText;
autocomplete.value = setValue;
this.innerHTML = "";
};
</script>
</body>
</html>
@w3collective
Copy link
Author

@giacomomarchioro
Copy link

giacomomarchioro commented May 5, 2022

Very nice! I am not sure it is really an autocomplete (because you can't complete the input automatically...) but at least it lists the possible choices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment