jQuery AJAX HTML5 Datalist Autocomplete Example

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

<input list="suburbs" name="suburb" type="text" autocomplete="on"/>
<datalist id="suburbs"></datalist>

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('<option data-value='+i+' data-postcode='+v.postcode+' data-state='+v.state+'>'+i+'</option>');
            });

            //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:

<ul>
    <li class="field">
        <label class="inline" for="suburb">*Suburb:</label>
        <input class="text input xwide" list="suburbs" name="suburb" type="text" placeholder="" autocomplete="on" required/>

        <!-- populated on load via JSON -->
        <datalist id="suburbs"></datalist>
    </li>
    <li class="field">
        <label class="inline" for="postcode">*Postcode:</label>
        <input class="text input narrow narrow-margin" name="postcode" type="text" placeholder="" required/>
        <label class="inline" for="state">State:</label>
        <input class="text input narrow" name="state" type="text" placeholder="" required/>
    </li>
</ul>

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 book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.