Autocomplete on an input field gives users suggestions while they type their responses. This feature lets users quickly select what they are looking for and save on their keystrokes.
In this Answer, we break down the steps to implement an autocomplete feature on an input field in JavaScript, given a list of suggestions. For this example, we consider an input field for the user's favorite fruit.
The first step is to create the input field we use. We must also create a container that encapsulates the input field and the list of suggestions.
autocomplete
attribute set to off
. This attribute tells the browser not to use its autocomplete logic, as we will define our own.<div>
tag. Inside <div></div>
, we create the input field on which we want the autocomplete feature.Right now, our input field isn't of much use. We must tell the browser which suggestions to give the user, and how to provide them with JavaScript.
Note: Inside the event listener function,
this
refers to the calling element.
<div>
to hold our autocomplete suggestions. We set its ID and append it to the element that contains the input field.<div>
element for that item and append it to the suggestions
element.closeList()
function. It retrieves the suggestions element and removes it if it exists.So far, we only display the list of suggestions. The user still has to type it in. Let's add some code to allow users to click on the item they want.
click
event.cursor
when it hovers over the suggestion. This styling lets the user know the item is clickable.