JavaScript
Article

jQuery AJAX HTML5 Datalist Autocomplete Example

By Sam Deering

This code uses HTML5 Datalist tag to setup autocomplete options for a text field. It grabs the data from a JSON file with an AJAC request (data which can be stored in the browser persistently if need be or locally on a js object). It then uses the selection of a suburb to autopopulate other fields postcode and state when the suburb changes. Works like a treat in pretty much all browser except Safari.

Notes: HTML Datalist still not compatiable with all browsers. See compatibility. For backfill plugin use this one: jQuery.relevantdropdowns.js – It inserts a UL tag with LI for options in replace of the datalist options.

postcode

HTML5 Datalist Tag


Full jQuery

This code populates the datalist via JSON and auto fills other fields based on the field’s auto complete selection by the user.

window.DATALIST = {

    cache: {},

    init: function()
    {
        var _this = this,
            this.cache.$form = $('formid');
            this.cache.$suburbs = this.cache.$form.find('datalist#suburbs');
            this.cache.$suburbInput = this.cache.$form.find('input[name="suburb"]');
            this.cache.$postcodeInput = this.cache.$form.find('input[name="postcode"]');
            this.cache.$stateInput = this.cache.$form.find('input[name="state"]');

        //grab the datalist options from JSON data
        var checkMembershipRequest = $.ajax({
            type: "GET",
            dataType: "JSON",
            url: "/php/suburbs.php"
        });

        checkMembershipRequest.done(function(data)
        {
            console.log(data);

            //data could be cached in the browser if required for speed.
            // localStorage.postcodeData = JSON.stringify(data);

            //add options to datalist
            $.each(data.suburbs, function(i,v)
            {
                _this.cache.$suburbs.append('');
            });

            //hook up data handler when suburb is changed to autocomplete postcode and state
            _this.cache.$suburbInput.on('change', function()
            {
                // console.log('suburb changed');
                var val = $(this).val(),
                    selected = _this.cache.$suburbs.find('option[data-value="'+val+'"]'),
                    postcode = selected.data('postcode'),
                    state = selected.data('state');
                _this.cache.$postcodeInput.val(postcode);
                _this.cache.$stateInput.val(state);
            });

        });

        checkMembershipRequest.fail(function(jqXHR, textStatus)
        {
            console.log( "postcode request fail - an error occurred: (" + textStatus + ")." );
            //try again...
        });

    }

}

Full HTML

This is what your HTML might look like:

Full JSON

PHP file returns JSON – could be .json or .php and grab data from a database if required.

{
    "suburbs": {
        "suburb1": {
            "postcode": "2016",
            "state": "NSW"
        },
        "suburb2": {
            "postcode": "4016",
            "state": "QLD"
        },
        "suburb3": {
            "postcode": "3016",
            "state": "CA"
        },
        "suburb4": {
            "postcode": "8016",
            "state": "WA"
        },
        "suburb5": {
            "postcode": "6016",
            "state": "SA"
        }
    }
}

html5 trigger datalist

Use ALT+down arrow to simulate user action. You’ll need to use jQuery to simulate a multiple trigger keypress.

keycode ALT = 18 (also modifier key called altKey)
keycode Down Arrow = 40

var e = jQuery.Event("keydown");
e.which = 40;
e.altKey = true;
$("input").trigger(e);

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.