Example of a dynamic HTML5 datalist control

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.

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.

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.

You can try this version by hitting the giant demo button below. Sorry - the old demo used ColdFusion, which I don't have on this server anymore.

Archived Comments

Comment 1 by Eric Reeves posted on 6/14/2012 at 6:52 PM

I kind of like the way Chrome handles autocomplete. If the form uses this type of input instead of a select, it's basically saying "I know SOME of the options you might want, but not all of them." If I typed in "mobile jum" (?) last time I filled out the form, maybe I would type it again. Maybe not for every form, so it's cool that there's a way to disable it.

Comment 2 by Raymond Camden posted on 6/14/2012 at 6:54 PM

To be clear, I'm not saying Chrome is wrong to make suggestions, my point though is that I think the use of datalist should override it, as it does in Firefox.

Comment 3 by Pinapple posted on 7/5/2012 at 1:15 PM

I think Opera did it best. You should see the list when the field is in focus. Not wait until something is typed or it's double clicked. That's the whole reason I'd provide those options, not suggestive-autocomplete.

Comment 4 by Raymond Camden posted on 7/5/2012 at 6:04 PM

@Pinapple: That would work for a static list, not sure how well it would work with the dynamic data source example.

Comment 5 by Pete posted on 7/31/2012 at 10:43 AM

Slightly off topic, but how long have you been zero indexing your examples?

If you said "Example 0" out loud, wouldn't that just sound strange?

And back on topic, nice post. So many hours of building combo boxes and including plugins could have been saved if the HTML spec contained this earlier.

Comment 6 by Raymond Camden posted on 7/31/2012 at 6:08 PM

I only do example 0 when I realize example 1 needs to be 'backtracked' a bit.

Comment 7 by Gokul posted on 10/18/2012 at 1:23 PM

Hi
Raymond i want to know that how it is possible to make searching among various field or columns via a single text field is available only.

Comment 8 by Raymond Camden posted on 10/19/2012 at 7:55 PM

I'm not quite sure I get what you are asking, Gokul. Can you provide an example?

Comment 9 by Kent posted on 10/30/2012 at 4:08 PM

Hi Ray, what is the variable used in the CFC for the query search and should it be serialized before returning? Is it possible to see code from your artservice.cfc please. I've been struggling. Cheers

Comment 10 by Raymond Camden posted on 10/30/2012 at 5:45 PM

I'm not sure what you mean by variable. As for serialized, remember that CF has automatic JSON serialization for CFCs.

Here is the code: http://pastebin.com/JQ4TCsgV

Comment 11 by Hidayat Meman posted on 2/20/2013 at 6:16 PM

Following Code Usefull For Laod menu at run time in ASP.Net With C#..
.aspx Page code

<datalist id="ddlCities" runat="server">

</datalist>
<asp:TextBox ID="txt" runat="server" list="ddlCities"></asp:TextBox>

.cs Page Code

protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
HtmlGenericControl h = new HtmlGenericControl("option");
h.InnerHtml = i + " Number";
ddlCities.Controls.Add(h);
}
}

Run the Page...

Comment 12 by Kent posted on 2/20/2013 at 7:04 PM

Thanks Ray, forgot to say so earlier. I understand the code now and modifying aspects freely.

Comment 13 by Lucrian posted on 2/25/2013 at 2:30 AM

Hello,

Can you please write here an example of what can that page return? I've tried this script, the results from server seems ok, but it doesn't appear the list with results.

For example, when I press A, my script return:

{
"DATA" : {
"AContact" : "Arre23",
"ALista" : "Asd-2",
"AInternet" : "Atte-3"
}
}

What's wrong?
Thanks!

Comment 14 by Lucrian posted on 2/25/2013 at 3:01 AM

I figure out how should be. Long life to Firebug
Example for dummies, like me :)

{
"DATA" : [
["AContact"],
["Arre23"],
["ALista"],
["Asd-2"],
["AInternet"],
["Atte-3"]
]
}

Doesn't work with different values and options.

Comment 15 by Raymond Camden posted on 2/25/2013 at 3:53 AM

To be clear, this is how I built the back end service. You can build it differently. There isn't anything magical about the {data:[array]} format.

Comment 16 by BillF posted on 4/9/2013 at 12:26 AM

Can you post the artservice.cfc code too?

Comment 17 by Raymond Camden posted on 4/9/2013 at 12:41 AM
Comment 18 by BillF posted on 4/9/2013 at 1:30 AM

Thanks.. Figured out why it wasn't calling it. ie8... :(

Comment 19 by Raman posted on 4/12/2013 at 2:29 PM

could you please explain me the role of following:
"$.get("artservice.cfc?method=getart&returnformat=json", {term:val},"
and do i get value from my .jsp page to fill datalist.

Comment 20 by Raymond Camden posted on 4/12/2013 at 3:17 PM

The first argument is just the URL. The query parameters mean something to ColdFusion. This is not important to you as a JSP person. The second argument is an additional argument passed over the URL.

Comment 21 by Raman posted on 4/17/2013 at 8:55 AM

could you please send me the sample code in JSP code.
Thanx

Comment 22 by Raymond Camden posted on 4/17/2013 at 2:56 PM

I don't know JSP.

Comment 23 by Rémi posted on 4/25/2013 at 12:55 AM

Thanks for the autocomplete=off tip :)

Comment 24 by Johnny posted on 8/28/2013 at 11:00 PM

Thanks for the example, but I have one question. Is there any way to make datalist show automaticlly after the function ends? At your example, results show only after the second character is typed or search box is clicked after the first character.

Comment 25 by Raymond Camden posted on 8/28/2013 at 11:06 PM

As far as I know, no. When stuff shows is up to the browser itself. Unlike 'fake' autocompletes (fake is a bad word, I mean pre-datalist) which draws DOM items, this is more low level and is tied to your input.

Not sure I explained that very well. :\

Comment 26 by Johnny posted on 8/29/2013 at 8:36 PM

Yeah I think I got it...Thank you :)

Comment 27 by Amin posted on 12/20/2013 at 11:08 PM

hi. do u have any idea or see somthing about rtl support datalist, such as persian (or arabic)?

Comment 28 by Raymond Camden posted on 12/21/2013 at 12:17 AM

No idea. Have you tried it?

Comment 29 by Christopher Jazinski posted on 2/12/2014 at 1:31 AM

Is there any way that you know of (built in to HTML5 maybe via an attribute) to make it preform a wild card search before as well. Example if I have options that are multiple words (lets say a first and last name) If i search for last name the drop box will not be populated. It seems to search Left to right.

Comment 30 by Raymond Camden posted on 2/12/2014 at 2:27 AM

Afaik it is browser dependent. Chrome will not match in the middle - Firefox will. (But to be clear, for *this* specific example, my server is not returning matches in the middle. I'd have to fix that to make it work and it would still only work with Firefox.)

Comment 31 by Navneet posted on 3/15/2014 at 11:02 AM

Very Useful code
Thnx

Comment 32 by Carlos posted on 7/28/2014 at 11:03 PM

Very usefull raymond, i have a question, if i had more than 40 data in the list, how can i limit for example the list return me the first 10.

Comment 33 by Raymond Camden posted on 7/28/2014 at 11:22 PM

Make your back end service only return 10 items.

Comment 34 by Carlos posted on 7/28/2014 at 11:32 PM

I could do that, but it's possible to make that in some configuration by css, js or html, to do that limit of data?

Comment 35 by Raymond Camden posted on 7/28/2014 at 11:37 PM

In the JS you could reduce it to 10. I'd do it on the server so you aren't sending unnecessary data over the wire, but you could limit it client-side too.

Comment 36 by Carlos posted on 7/28/2014 at 11:42 PM

Thanks a lot Raymond, i will the test....

Comment 37 by Dylan posted on 9/27/2014 at 7:40 PM

Thank you so much for sharing this Raymond! It uses browser facilities, it's lightweight, and very simple. No need for a whole library!

Unfortunately it was not working on my website! I found the problem: the newer version of jQuery that I use, 1.4.4. The latest versions are too bloated and slow (2.1.1+). I made the following changes:

$("#search").on("input", function(e) {
to:
$('#search').keyup(function() {

It works now. Thanks again!

Comment 38 by usuario042 posted on 10/1/2014 at 12:28 AM

Hello,
I'm quite new to jQuery. But i have modified you function to retrieve data from a database instead.
Although I have verified the integrity of the SQL query, I keep getting the "undefined value" for te results I get. The number of undefined entries retrieved corresponds to those of the query executed in a Database Browser.
Whats suggests that the data is being retrieved, but ...

Here follows the code:

$(document).ready(function() {
$("#marca_teste").on("input", function(e) {
var val = $(this).val();
if(val === "") return;
var dataList = $("#search_veiculo");
var sqlquerry = "select distinct(fabricante) from veiculo where fabricante like 'f%'" ;
//You could use this to limit results
//if(val.length < 3) return;
console.log("Marca_teste: "+val);
console.log(sqlquerry);

db.transaction(function(tx){
tx.executeSql( sqlquerry, [], function(tx, res){
dataList.empty();
if(res.rows.length) {
for(var i=0, len=res.rows.length; i<len; i++) {
var opt = $("<option></option>").attr("value", res.rows.item(i).fabricante+"a");

dataList.append(opt);

console.log(res.rows.item(i).fabricante);
}
}
//console.dir(res);
});
},function(error){console.log(error.message + "Query: "+sqlquerry);}
,function(){
console.log("Item inserido");
});

});

});

Comment 39 by Raymond Camden posted on 10/1/2014 at 12:31 AM

I assume the console.log shows the right value?

Comment 40 by usuario042 posted on 10/1/2014 at 12:42 AM

(Not it doesn't, it also show the "undefined".)

But I have come up with a solution, silly me.
The problem with the code above is the letter case. Although the SQL Lite Data browser allows either Upper and Lower case, the websql API doesn't.
So the solution was pretty simple, change the statement "res.rows.item(i).fabricante" to "res.rows.item(i).Fabricante" and it works just fine.

It was indeed a silly mistake, but at least we can now offer more information to those like me, begginers in the topic.

1. Case sensitiveness of Web SQL
2. The code above wich provide way of dynamically updating a combobox through Web SQL

Sorry About that, and thank you for your assitance.

Comment 41 by Federico C. posted on 12/7/2015 at 5:41 PM

it is posible use data list to retrieve a list when the chars entered match in any part of the options, as like '%' in SQL ?

Comment 42 (In reply to #41) by Raymond Camden posted on 12/7/2015 at 7:01 PM

Datalists don't match in the middle, you can't change that unfortunately.

Comment 43 (In reply to #42) by Federico C. posted on 12/7/2015 at 7:22 PM

i am trying this....

http://stackoverflow.com/qu...

need some detail, but it is working.

Comment 44 (In reply to #43) by Raymond Camden posted on 12/7/2015 at 7:25 PM

Ah they "fake" it by prefixing the item with the input. So yeah, just follow what they do.

Comment 45 by Ranjan Kumar Gochhayat posted on 7/27/2016 at 6:28 AM

Hi how can i impliment onchange method in datalist

Comment 46 (In reply to #45) by Raymond Camden posted on 7/27/2016 at 12:50 PM

You can't do an onchange on the datalist, but you can on the input field it is bound to.

Comment 47 by Ranjan Kumar Gochhayat posted on 7/27/2016 at 12:58 PM

Hi, I have implemented onchange on input field but unless i click on the html body, that event not fires.

Comment 48 (In reply to #47) by Raymond Camden posted on 7/27/2016 at 12:59 PM

Can you post a link to your code? Or to a Gist of your code. (Do not post all the code in a comment.)

Comment 49 (In reply to #48) by Ranjan Kumar Gochhayat posted on 7/27/2016 at 1:10 PM

Did you get my html file?

Comment 50 (In reply to #48) by Ranjan Kumar Gochhayat posted on 7/27/2016 at 1:11 PM

Please find the screen shot.

Comment 51 (In reply to #49) by Raymond Camden posted on 7/27/2016 at 1:12 PM

Nope. Is it online at least?

Comment 52 (In reply to #51) by Ranjan Kumar Gochhayat posted on 7/27/2016 at 1:17 PM

I have shared the snap. But I dont have idea how to post online.

Comment 53 (In reply to #51) by Ranjan Kumar Gochhayat posted on 7/27/2016 at 1:19 PM

<html>
<head>

<script>
function myFunction(val){
alert(val);
}
</script>

</head>
<body>
<div>
<label>Enter Country name:</label>
<input type="text" list="countries" onchange="myFunction(this.value)"/>

<datalist id="countries"/>
<option value="Afghanistan">
<option value="Africa">
<option value="Zambia">
<option value="Zimbabwe">
</datalist>
</div>
</body>

</html>

Comment 54 (In reply to #47) by Raymond Camden posted on 7/27/2016 at 1:19 PM

Try the "input" event - that worked for me.

Comment 55 (In reply to #54) by Ranjan Kumar Gochhayat posted on 7/27/2016 at 1:22 PM

You are talking about event listner. But I am not using Jquery. Please share the code snippet.

Comment 56 (In reply to #55) by Raymond Camden posted on 7/27/2016 at 2:05 PM

To be clear, event listeners have nothing to do with jQuery. They are part of JavaScript. If you aren't using jQuery, use document.addEventListener. This is the reference for change: https://developer.mozilla.o...

Comment 57 (In reply to #56) by Ranjan Kumar Gochhayat posted on 7/27/2016 at 2:33 PM

could you plz share exmpl. using datalist

Comment 58 (In reply to #57) by Raymond Camden posted on 7/28/2016 at 2:06 AM
Comment 59 (In reply to #58) by Ranjan posted on 7/29/2016 at 8:56 AM

Hi Raymond,

I tried your example that, its working fine but the search is not working in firefox, Please follow the screen shot. I am searching with r, it should come with start with r but the data returns where r find. But in chrome its working fine.

Comment 60 (In reply to #59) by Raymond Camden posted on 7/29/2016 at 12:20 PM

Well the screen shot is of my JSBin sample and nothing is actually tied to the form. It doesn't actually search anything. Right?

Comment 61 by Okokoh Benjamin Ekuma posted on 3/23/2017 at 12:37 PM

can i se the JSON data returned in the server request, the structure..
This place-->
artservice.cfc?method=getart&returnformat=json

i need to see the structure format of the JSON

Comment 62 (In reply to #61) by Raymond Camden posted on 3/23/2017 at 3:20 PM

It was an array of strings. The JSON doesn't matter though - it was just an example.

Comment 63 by Chip Toll posted on 4/3/2017 at 4:44 AM

Hi Ray - wondering is there a simple way for each option in a datalist to link over to an html page?

Comment 64 (In reply to #63) by Raymond Camden posted on 4/3/2017 at 11:44 AM

I would say just use the value, but it does weird things in datalists:

http://stackoverflow.com/qu...

So all I can think of is if your values are unique, load up code that says, "on select and value is Ray, that means go to this URL..."

Comment 65 by Nishanth posted on 1/30/2018 at 11:16 AM

Is there a way for datalist to work as <select> so that when onchange event of options the current value should display in input list.
(if you press the downarrow key, the event will moves on the option list, doing so whenever the selector is going on the option selection that particular option value should display in the input list)

Comment 66 (In reply to #65) by Raymond Camden posted on 1/30/2018 at 1:44 PM

I've read your comment a few times and I'm not quite sure what you are asking. Can you rephrase maybe?

Comment 67 (In reply to #66) by Nishanth posted on 1/31/2018 at 6:20 AM

in datalist option when i move my cursor on the different options i need that particular option value in my input filed is it possible?

Comment 68 (In reply to #67) by Raymond Camden posted on 1/31/2018 at 1:45 PM

You mean just by moving scrolling over an item you want it selected? I don't think you can. I believe you must hit enter, or click, on the item to set it.

Comment 69 (In reply to #68) by Nishanth posted on 2/1/2018 at 11:41 AM

okay , Thank you

Comment 70 by Nishanth posted on 2/6/2018 at 11:41 AM

When i fill a Datalist wih an Ajax-Function Firefox does not work correctly but the Google-Chrome works correct.
The same functionallity wih Firefox requires first to call the Back-button that the consens of the list is shown correctly. why is this so?

Comment 71 (In reply to #70) by Raymond Camden posted on 2/6/2018 at 4:41 PM

I am not able to reproduce this in Firefox. Here is a codepen showing it working:

https://codepen.io/cfjedima...

It isn't using Ajax, but that shouldn't matter. If you have an online copy of your code I can check, let me know.

Comment 72 by JagadeeshwarReddy posted on 7/17/2018 at 8:49 AM

Hi, the datalist search causes browser freeze in chrome and it's working fine in Firefox. May I know the reason.

Comment 73 (In reply to #72) by Raymond Camden posted on 7/17/2018 at 11:07 AM

Do you have your version online where I can test?