HTML Must Knows the datalist element

HTML Must Knows the datalist element

Subscribe to my newsletter and never miss my upcoming articles

The HTML <datalist> element is a very powerful input element. It functions as an input field with dropdown options, but here is the catch: it comes with autocomplete. Users will see a drop-down list of predefined options as they write in the input field!

The <datalist> element contains various <option> elements that represent the options that are available to the user.

It kind of feels like a <select> dropdown, but on steroids. Since the user is able to type and get autocomplete options in return.

How to use <datalist>

<label for="animals">What is your favorite animal?:</label>
<input list="animals" name="animal" id="animal">

<datalist id="animals">
  <option value="Dog">
  <option value="Cat">
  <option value="Horse">
  <option value="Donkey">
  <option value="Bunny">
</datalist>

Note the id of the <datalist> and the value of the list attribute on the <input> field

The HTML will translate into:

{% codepen codepen.io/karsviersel/pen/ZEWJXgW %}

If you click on the input field you already see the generated list of options that I've provided. Now start typing in the input field! As you will notice, once you start typing the list will shrink. It will only show the available options based on what you have typed.

So out of the box, HTML gives us an input field that brings autocomplete to the table.

The beauty of this is that it even works in all browsers! Both desktop and mobile.

Conclusion

When I learned about the <datalist> element I was very happy! In almost every project I had to spend hours creating custom dropdown lists with autocomplete. Never knowing that there was a HTML tag for it!

I wonder what you think of the <datalist> element? Let me know!

 
Share this