Dan Hough

Tutorial - Native HTML5 autocomplete with datalist

Published 10 October 2014 in London, UK

I’ve had the opportunity to play around with some cool new HTML5 stuff recently, and have just finished implementing a browser-native autocomplete using HTML5’s new <datalist> element into one of my open-source projects. No JavaScript required for this!

The <datalist> element has pretty OK support, so you should be ok reading this post if you’re on Chrome >= 20, Firefox >= 4, IE >= 10 or Opera >= 9.5. If not though, this is what we’re going for

HTML5 Datalist

No plugins! As you can see it's a regular input with a little dropdown attached to it.

Building it

This is really easy. First, you’re gonna need a regular ol’ <input type="text"> element, and let’s give it a label just because.

<label for="fav-fruit">Favourite Fruit</label>
<input type="text" id="fav-fruit">

Now we add the new element, datalist. It needs an ID so we can hook it up to the <input>. Put it above the <input>, because it looks better there. While you’re at it, add the list attribute to your <input> so it points at the <datalist> we created.

<datalist id="fruits">
</datalist>

<label for="fav-fruit">Favourite Fruit</label>
<input type="text" id="fav-fruit" list="fruits">

Just like the <select> element, we put <option> elements inside the <datalist>, like so:

<datalist id="fruits">
	<option value="Orange">
	<option value="Strawberry">
	<option value="Banana">
</datalist>

<label for="fav-fruit">Favourite Fruit</label>
<input type="text" id="fav-fruit" list="fruits">

As usual, we can also add a placeholder attribute to the <input> so you might as well do that.

Result

Try typing in it, or hitting the arrow on the right:

Heckle me on Twitter @basicallydan.