Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Auto-Complete Input
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Autocomplete</title>
<!-- Included some basic styling, change at will -->
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/prampcontent/3ea04cbd0f61a798e96afbe5d31ec2f9/raw/e879e32222b543b29a168daa089e2f9f28cf9eb2/autocomplete.css">
</head>
<body>
<form class="search-form">
<input type="text" class="search-input" placeholder="Start typing a movie title...">
<ul class="results"></ul>
</form>
<!-- Helper code to provide a search API for mock data -->
<script src="https://cdn.rawgit.com/prampcontent/180077452f9279073cab1035f60d30cf/raw/9cbf891a80bad9ad09c6261ef9578a65502922cc/search_helper.js"></script>
<script>
/*-------------------------------
*
* Write your JavaScript code here.
*
* The mocked search data is available using the searchData async method, e.g:
* searchData("QUERY").then(results => ...)
Response from API:
[
{
rating: 8.5
title: "Casablanca (1942)"
},
...
]
* ------------------------------*/
const inputElement = document.querySelector(".search-input")
const resultsElement = document.querySelector(".results")
let inputElementText = ""
inputElement.addEventListener("input", e => {
inputElementText = e.target.value
//If the user isn't deleting text, then try to autocomplete
if(e.inputType !== "deleteContentBackward") {
//Call API with input
searchData(e.target.value)
.then(res => {
//Filter the results with startsWith
//Because searchData matches any part of a title
res = res.filter((obj) => obj.title.startsWith(e.target.value))
//If there were results
if(res.length > 0) {
//Autocomplete input field
inputElement.value = res[0].title
//Highlight what was autocompleted so the user can easily replace it
inputElement.setSelectionRange(inputElementText.length, res[0].title.length)
//Remove previous matches from list
while(resultsElement.children.length){
resultsElement.removeChild(resultsElement.children[resultsElement.children.length-1])
}
//Append list items to move list
res.forEach(movie => {
const movieListItem = document.createElement("li")
movieListItem.innerHTML = `<h1>${movie.title}</h1>`
resultsElement.appendChild(movieListItem)
})
}
})
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment