Created
March 23, 2022 23:26
-
-
Save w3collective/78abc33dbeb0c4e700e9856ccfe62536 to your computer and use it in GitHub Desktop.
Autocomplete search using vanilla JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.