linuxeasy
linuxeasy

Reputation: 6499

JQuery Autocomplete without using label, value, id

Is it possible to have JQuery Autocomplete work without using conventional id,label,value?

For instance, I do not wish to use:

[ { "id": "Botaurus stellaris", "label": "Great Bittern", "value": "Great Bittern" }, 
{ "id": "Asio flammeus", "label": "Short-eared Owl", "value": "Short-eared Owl" }]

but rather:

[ { "my_id": "Botaurus stellaris", "first_name": "Great Bittern", "last_name": "Great Bittern" }, 
{ "my_id": "Asio flammeus", "first_name": "Short-eared Owl", "last_name": "Short-eared Owl" }]

So like, what JQuery autocomplete normally takes id,value,label, can I make it to take my_id, first_name, last_name and make Jquery Autocomplete treat like same id,label,value?

This might be useful, when I don't wish to modify data's keys coming from a datasource, to display it on JQuery Autocomplete.

Upvotes: 4

Views: 5830

Answers (2)

Jonas Geiregat
Jonas Geiregat

Reputation: 5432

There's an even better solution. It's even documented on the jquery-ui website.

http://jqueryui.com/demos/autocomplete/#custom-data

$("input").autocomplete({..})
.data( "autocomplete" )._renderItem = function( ul, item ) {return $( "<li></li>" )
    .data( "item.autocomplete", item )
            .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
            .appendTo( ul );
    };

Upvotes: 1

linuxeasy
linuxeasy

Reputation: 6499

Never mind,

Found the answer from JQueryUI's Autocomplete example source:

    $( "#city" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "http://ws.geonames.org/searchJSON",
                dataType: "jsonp",
                data: {
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    name_startsWith: request.term
                },
                success: function( data ) {
                    response( $.map( data.geonames, function( item ) {
                        return {
                            label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                            value: item.name
                        }
                    }));
                }
            });
        },
        minLength: 2
    });

Here, source is been assigned a function, that can convert and return any type of keys to required be converted to JQuery's Autocomplete's id,value,label.

May be it helps some.

Upvotes: 2

Related Questions