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
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.
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.
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.
@Pinapple: That would work for a static list, not sure how well it would work with the dynamic data source example.
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.
I only do example 0 when I realize example 1 needs to be 'backtracked' a bit.
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.
I'm not quite sure I get what you are asking, Gokul. Can you provide an example?
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
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
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...
Thanks Ray, forgot to say so earlier. I understand the code now and modifying aspects freely.
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!
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.
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.
Can you post the artservice.cfc code too?
Here: https://gist.github.com/cfj...
Thanks.. Figured out why it wasn't calling it. ie8... :(
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.
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.
could you please send me the sample code in JSP code.
Thanx
I don't know JSP.
Thanks for the autocomplete=off tip :)
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.
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. :\
Yeah I think I got it...Thank you :)
hi. do u have any idea or see somthing about rtl support datalist, such as persian (or arabic)?
No idea. Have you tried it?
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.
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.)
Very Useful code
Thnx
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.
Make your back end service only return 10 items.
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?
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.
Thanks a lot Raymond, i will the test....
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!
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");
});
});
});
I assume the console.log shows the right value?
(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.
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 ?
Datalists don't match in the middle, you can't change that unfortunately.
i am trying this....
http://stackoverflow.com/qu...
need some detail, but it is working.
Ah they "fake" it by prefixing the item with the input. So yeah, just follow what they do.
Hi how can i impliment onchange method in datalist
You can't do an onchange on the datalist, but you can on the input field it is bound to.
Hi, I have implemented onchange on input field but unless i click on the html body, that event not fires.
Can you post a link to your code? Or to a Gist of your code. (Do not post all the code in a comment.)
Did you get my html file?
Please find the screen shot.
Nope. Is it online at least?
I have shared the snap. But I dont have idea how to post online.
<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>
Try the "input" event - that worked for me.
You are talking about event listner. But I am not using Jquery. Please share the code snippet.
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...
could you plz share exmpl. using datalist
http://output.jsbin.com/kut...
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.
Well the screen shot is of my JSBin sample and nothing is actually tied to the form. It doesn't actually search anything. Right?
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
It was an array of strings. The JSON doesn't matter though - it was just an example.
Hi Ray - wondering is there a simple way for each option in a datalist to link over to an html page?
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..."
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)
I've read your comment a few times and I'm not quite sure what you are asking. Can you rephrase maybe?
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?
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.
okay , Thank you
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?
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.
Hi, the datalist search causes browser freeze in chrome and it's working fine in Firefox. May I know the reason.
Do you have your version online where I can test?