Twitter: raymondcamden


Address: Lafayette, LA, USA

Example of a dynamic HTML5 datalist control

06-14-2012 55,583 views jQuery, JavaScript, HTML5 40 Comments

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.

40 Comments

  • Eric Reeves #
    Commented on 06-14-2012 at 9:52 AM
    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.
  • Commented on 06-14-2012 at 9:54 AM
    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.
  • Pinapple #
    Commented on 07-05-2012 at 4:15 AM
    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.
  • Commented on 07-05-2012 at 9:04 AM
    @Pinapple: That would work for a static list, not sure how well it would work with the dynamic data source example.
  • Commented on 07-31-2012 at 1: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.
  • Commented on 07-31-2012 at 9:08 AM
    I only do example 0 when I realize example 1 needs to be 'backtracked' a bit.
  • Commented on 10-18-2012 at 4:23 AM
    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.
  • Commented on 10-19-2012 at 10:55 AM
    I'm not quite sure I get what you are asking, Gokul. Can you provide an example?
  • Kent #
    Commented on 10-30-2012 at 7:08 AM
    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
  • Commented on 10-30-2012 at 8:45 AM
    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
  • Commented on 02-20-2013 at 7:16 AM
    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...
  • Kent #
    Commented on 02-20-2013 at 8:04 AM
    Thanks Ray, forgot to say so earlier. I understand the code now and modifying aspects freely.
  • Commented on 02-24-2013 at 3:30 PM
    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!
  • Commented on 02-24-2013 at 4:01 PM
    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.
  • Commented on 02-24-2013 at 4:53 PM
    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.
  • BillF #
    Commented on 04-08-2013 at 3:26 PM
    Can you post the artservice.cfc code too?
  • Commented on 04-08-2013 at 3:41 PM
    Here: https://gist.github.com/cfjedimaster/5340357
  • BillF #
    Commented on 04-08-2013 at 4:30 PM
    Thanks.. Figured out why it wasn't calling it. ie8... :(
  • Raman #
    Commented on 04-12-2013 at 5:29 AM
    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.
  • Commented on 04-12-2013 at 6:17 AM
    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.
  • Raman #
    Commented on 04-16-2013 at 11:55 PM
    could you please send me the sample code in JSP code.
    Thanx
  • Commented on 04-17-2013 at 5:56 AM
    I don't know JSP.
  • Rémi #
    Commented on 04-24-2013 at 3:55 PM
    Thanks for the autocomplete=off tip :)
  • Johnny #
    Commented on 08-28-2013 at 2: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.
  • Commented on 08-28-2013 at 2: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. :\
  • Johnny #
    Commented on 08-29-2013 at 11:36 AM
    Yeah I think I got it...Thank you :)
  • Amin #
    Commented on 12-20-2013 at 12:08 PM
    hi. do u have any idea or see somthing about rtl support datalist, such as persian (or arabic)?
  • Commented on 12-20-2013 at 1:17 PM
    No idea. Have you tried it?
  • Commented on 02-11-2014 at 2:31 PM
    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.
  • Commented on 02-11-2014 at 3:27 PM
    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.)
  • Navneet #
    Commented on 03-15-2014 at 2:02 AM
    Very Useful code
    Thnx
  • Carlos #
    Commented on 07-28-2014 at 2: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.
  • Commented on 07-28-2014 at 2:22 PM
    Make your back end service only return 10 items.
  • Carlos #
    Commented on 07-28-2014 at 2: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?
  • Commented on 07-28-2014 at 2: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.
  • Carlos #
    Commented on 07-28-2014 at 2:42 PM
    Thanks a lot Raymond, i will the test....
  • Dylan #
    Commented on 09-27-2014 at 10:40 AM
    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!
  • usuario042 #
    Commented on 09-30-2014 at 3:28 PM
    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");
                                                 });   
                                              
                                              
                                              
                                              
                                           });
                                        
                                        });
  • Commented on 09-30-2014 at 3:31 PM
    I assume the console.log shows the right value?
  • usuario042 #
    Commented on 09-30-2014 at 3:42 PM
    (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.

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty