The datalist element

We continue our journey through the (fun) world of forms. This time it is all about <datalist>.

In this article you will learn what <datalist> is, how to use it and why it might not be your favourite choice.

How to use datalist #

<label for="formelement">Your favourite form element?</label> 
<input list="formelements" id="formelement" name="formelement" />
<datalist id="formelements">
<option value="input">
<option value="button">
<option value="select">
<option value="datalist">
<option value="legend">
</datalist>

First you need an input element and the datalist element. To connect the input and the datalist you have to use the list attribute on the input, with the same value as the id attribute of the datalist element. After that you have to define possible values using the option element.

In the end you have a simple autosuggest feature. When the user starts typing e.g. "d", they will get a select showing "datalist" and "legend" for our example options above.

native styling of datalist in Firefox

You can find a working example on JS Bin.

Caveats with <datalist> #

So, while it can be a good enhancement, datalist is very basic and often not what you may want. Let's see what is missing.

No custom styles #

As with <option> inside <select>, the options for <datalist> are also not styleable at all. This means you will always get the native styles of the browser.

You can change styles for <datalist> as shown here if you force it to be display: block;, but this will not affect the dropdown you see with the suggestions, and is therefore not useful.

No options #

Not being able to style it is something you may accept, but the biggest issue for me is that you can't influence when and why suggestions are shown as there are not options.

You can't define a minimum character length when to start showing suggestions, nor can you define a maximum for results to be shown.

Browser support #

Browser support for <datalist> is very good, as all modern browser support it. It is also supported all the way back to Internet Explorer, although it is a bit buggy there. As it is an enhancement, I suggest you can use it today without any polyfill.

Resources #

Example: https://jsbin.com/lipelisuza/1/edit?html

MDN: datalist https://developer.mozilla.org/en/docs/Web/HTML/Element/datalist

datalist-polyfill https://github.com/mfranzke/datalist-polyfill