HTML5 Zone is brought to you in partnership with:

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 212 posts at DZone. You can read more from them at their website. View Full User Profile

Example of a Dynamic HTML5 Datalist Control

07.03.2012
| 13905 views |
  • submit to reddit

I've made no secret of being a huge fan of the updates to forms within HTML5. One of the more interesting updates is the datalist control. This control gives you basic autocomplete support for an input field. At its simplest, you create the datalist control options, tie it to a control, and when the user types, they see items that match your initial list. Consider this example.

<!doctype html>
<html>
<head>
<title>Example 0</title>
</head>

<body>

<p>
<input type="text" name="search" id="search" placeholder="Type Something" list="searchresults" autocomplete="off">
<datalist id="searchresults">
<option>Ray</option>
<option>Scott</option>
<option>Todd</option>
<option>Dave</option>
<option>Jeanne</option>
<option>Jacob</option>
</datalist>
</p>

</body>
</html>

Note that the input field, search, has a list attribute that points to the datalist control below it. The datalist control is simply a list of options. If you run this code in a supported browser, you will see the options show up as autocomplete values. As you type, they filter out based on your input. If you run this in an unsupported browser, nothing bad happens. (You can demo this script yourself here.)

So - that's cool I think - but most folks are not going to have a static list of options. Instead, they will want to base it on some dynamic data, possibly loaded in via AJAX. I built a simple demo that talks to some server-side code and returns a list of options based on input. Let's look at the code.

<!doctype html>
<html>
<head>
<title>Example 1</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {

$("#search").on("input", function(e) {
var val = $(this).val();
if(val === "") return;
//You could use this to limit results
//if(val.length < 3) return;
console.log(val);
$.get("artservice.cfc?method=getart&returnformat=json", {term:val}, function(res) {
var dataList = $("#searchresults");
dataList.empty();
if(res.DATA.length) {
for(var i=0, len=res.DATA.length; i<len; i++) {
var opt = $("<option></option>").attr("value", res.DATA[i][0]);
dataList.append(opt);
}

}
},"json");
});

})
</script>	
</head>

<body>

<p>
<input type="text" name="search" id="search" placeholder="Type Something" list="searchresults" autocomplete="off">
<datalist id="searchresults"></datalist>
</p>

</body>
</html>

For my example, I make use of jQuery, although that is certainly not required. I've bound to the input event for my search field and removed any items from my datalist control. When the event is fired, I grab the field value and simply pass it to a server-side script that does a database lookup. None of this is particular new or unique, but note how I handle the result. I take each result sent to me and create new option items for my datalist. (Note too that I make sure to clear out any previous ones.) This then gives me a simple database-bound datalist control. You can try this yourself here. I recommend using "mo" for input.

One interesting tidbit. I noticed in Chrome that if I didn't disable autocomplete, the browser would use both the explicit list I specified in JavaScript and my personal autocomplete history. It even used a little separator to divide the options:

I'm not sure if I like that so for my examples I've simply disabled it. Firefox only shows the explicit list, which feels right to me.

As I mentioned above, if you run this in a browser that doesn't support datalist, it fails nicely. But my demo was still firing off a bunch of AJAX requests and that seemed a bit silly. In my final version, I modified the code to first see if the browser supported datalist. This way it won't waste time hitting the server when it doesn't need to.

<!doctype html>
<html>
<head>
<title>Example 2</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {

if(document.createElement("datalist").options) {

$("#search").on("input", function(e) {
var val = $(this).val();
if(val === "") return;
//You could use this to limit results
//if(val.length < 3) return;
console.log(val);
$.get("artservice.cfc?method=getart&returnformat=json", {term:val}, function(res) {
var dataList = $("#searchresults");
dataList.empty();
if(res.DATA.length) {
for(var i=0, len=res.DATA.length; i<len; i++) {
var opt = $("<option></option>").attr("value", res.DATA[i][0]);
dataList.append(opt);
}

}
},"json");
});

}

})
</script>	
</head>

<body>

<p>
<input type="text" name="search" id="search" placeholder="Type Something" list="searchresults" autocomplete="off">
<datalist id="searchresults"></datalist>
</p>

</body>
</html>

You can try this version by hitting the giant demo button below.

Published at DZone with permission of Raymond Camden, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)