Looking for an easy way to add autocomplete values to a form input without getting your hands dirty with JavaScript? Well, you could create autocomplete input with just and only a few lines of plain HTML code.
Introducing datalist element, which provides a pre-defined autocomplete options to an input element. What you get is a drop-down list with your pre-defined options while a user types in the input field.
Create HTML input datalist
Let's learn about the datalist element with a simple example. First, we create a normal label and input field.
<label for="car-brand">Choose your favourite car brand?</label>
<input type="text" id="car-brand" name="car-brand">
Now, we need to show a few pre-defined options as autocomplete value when user input data. For that purpose, we add a datalist element with all options (autocomplete values you need) and then link it to the input field with a list property.
In our example, we add a few car brands as options for the datalist. Then give the datalist an ID, which is then linked to the input field with the list property with the value same as the datalist ID.
<label for="car-brand">Choose your favourite car brand?</label>
<input type="text" id="car-brand" name="car-brand" list="car-brand-list">
<datalist id="car-brand-list">
<option>Mercedes-Benz</option>
<option>Audi</option>
<option>Ford</option>
<option>Porsche</option>
<option>Tesla</option>
</datalist>
That's it, now when the user tries to input data it would show a list of options available for them choose from. They could also sort the list by typing a few characters of the value.
The HTML datalist element is compatible with all modern browsers and works even in IE10. You could learn more about the element in MDN web docs.