Over a million developers have joined DZone.

Quick Tip – Autocomplete Using HTML5 Datalist Element

DZone 's Guide to

Quick Tip – Autocomplete Using HTML5 Datalist Element

· Web Dev Zone ·
Free Resource
One of the new elements in HTML5 specifications is the datalist. The datalist holds a predefined options list which will be presented as autocomplete list in other HTML5 controls such as textboxes.

Using Datalist Element

The use of a datalist element is straight forward. You create the datalist inside a phrasing element and write the autocomplete options inside of it:

<datalist id="dlCities">

    <option value="Seattle" />

    <option value="Las Vegas" />

    <option value="New York" />

    <option value="Salt lake City" />


In order to connect the previous list to a textbox and create the autocomplete functionality, you will use the new list attribute and give it the datalist id:

<input type="text" id="txt" name="txt" list="dlCities" />

The result of running the page will be:


Creating On The Fly Datalist

One of the requirements I had in a project I did lately was to create a datalist on the fly. This can be achieved using basic JavaScript functionality. Here the code sample:

(function () {

    var optionList = ["Seattle", "Las Vegas", "New York", "Salt lake City"];


    function fillDataList() {

        var container = document.getElementById('container'),

        i = 0,

        len = optionList.length,

        dl = document.createElement('datalist');


        dl.id = 'dlCities';

        for (; i < len; i += 1) {

            var option = document.createElement('option');

            option.value = optionList[i];






    window.addEventListener("DOMContentLoaded", fillDataList, false);

} ());

As you can see you have a predefined array with the same cities options from the previous code sample. The fillDataList function is called when the DOM content loaded event is fired. In the fillDataList, all you have to do is to get the container element (that must be a phrasing element) and append to it the created datalist. This example can be changed easily to use data retrieved from the server-side.

Datalist Browser Support

As in all new HTML5 elements, currently the datalist isn’t supported in all of the browsers. The datalist is supported in Chrome from version 20, in Firefox from version 4, in Internet Explorer from version 10 and in Opera from version 9. You can go to the following web page to see where the datalist is supported in more details.


The datalist element can be useful when you have predefined options that you want to use as autocomplete in HTML controls. It’s lack of browsers support forces us to have fallbacks to the behavior using JavaScript control libraries such as the autocomplete control in jQuery UI.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}