Top of page

Learn to add an autocomplete input with HTML datalist

Varmapublished on March 30, 2020 & last updated on October 27, 2020

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.

In DigitalOcean

Free $100 DigitalOcean credit for Cloud Hosting

Exclusive - Get free $100 DigitalOcean credit on your new account which is good for 60 days usage to spin up a Droplets, Cloud Servers, Managed Databases, Kubernetes, Block Storage, Load Balancers and much more.

$100 FREE Deal
NO CODE NEEDEDGet this deal

In NameCheap

Discounted COM, NET, ORG, BIZ, INFO domain Registrations and Transfers

Get discount on .com, .net, .org, .biz, .info domain names on Registrations and Transfers at NameCheap.

LOWEST Coupon
TLDSDISCONT CopyGet this deal

Related Articles

Fetching coffee...

{}