Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Auto-Complete Input
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Search Autocomplete</title>
<!-- Included some basic styling, change at will -->
<link rel="stylesheet" type="text/css" href="">
<form class="search-form">
<input type="text" class="search-input" placeholder="Start typing a movie title...">
<ul class="results"></ul>
<!-- Helper code to provide a search API for mock data -->
<script src=""></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 =
//If the user isn't deleting text, then try to autocomplete
if(e.inputType !== "deleteContentBackward") {
//Call API with input
.then(res => {
//Filter the results with startsWith
//Because searchData matches any part of a title
res = res.filter((obj) => obj.title.startsWith(
//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
//Append list items to move list
res.forEach(movie => {
const movieListItem = document.createElement("li")
movieListItem.innerHTML = `<h1>${movie.title}</h1>`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment