This examples demonstrates how to setup an input field with autocomplete functionality backed by data from an external web service. Here we use the web service Geonames and bind it to an input field via AJAX.

Setting up an input field with autocomplete functionality. Here we retrieve a list of cities from the web service Geonames.

First of all, we need to create a function for retrieving the data from the web service and pre-processing it so that it can be used with Xima® Formcycle. For this we make use the ajax function provided by jQuery, see their help pages for further information.

function geonamesCity( request, response ){
    $.ajax({
        url: "http://api.geonames.org/searchJSON",
        dataType: "jsonp",
        data: {
            q:"US",
            country:"US",
            lang:"EN",
            username:"ximademo",
            featureClass: "P",
            style: "full",
            maxRows: 12,
            name_startsWith: request.term
        },
        success: function( data ) { // pre-process the data
           response($.map( data.geonames, function( item ) {
               return {
                    label: item.name + (item.adminName1 ? ", " + item.adminName1 : ""),
                    value: item.name
                }
            }));
        }
    });
}

Once the data has been loaded successfully, we can select the input field named tf1 and setup the autocomplete functionality. jQuery UI offers a function for converting an input field to an autocomplete field, see their help pages on autocomplete for further details. The function geonamesCity we created for retrieving the data must be passed to the autocomplete function.

$("[name=tf1]").autocomplete({
    source: geonamesCity // tell the autocomplete function where it should get the data from
});

Download a form with the example above.

Tags:
Copyright 2000-2024