Sunday, March 21, 2010

JQuery UI Autocomplete widget with customize JSON data and Spring MVC

One of my favorite newly added widget in jQuery UI 1.8, is Autocomplete. However, it took me a long time to figure it out how to use customized JSON data. So I wrote this as supplementary for you to use your own format JSON data.


The Default JSON Data Format

The Autocomplete widget will looking for an Array of object with label, value property pair, for example, data from jQury UI's remote datasource example.
[ { "id": "Dromas ardeola", "label": "Crab-Plover", "value": "Crab-Plover" }, { "id": "Larus sabini", "label": "Sabine`s Gull", "value": "Sabine`s Gull" }, { "id": "Vanellus gregarius", "label": "Sociable Lapwing", "value": "Sociable Lapwing" }, { "id": "Oenanthe isabellina", "label": "Isabelline Wheatear", "value": "Isabelline Wheatear" } ]

Customized JSON Data

But my country name JSON data looks like this:
 {"countries":[{"name":"Australia","id":14},{"name":"Austria","id":15},{"name":"Guinea-bissau","id":96},{"name":"Macau","id":133},{"name":"Mauritania","id":143},{"name":"Mauritius","id":144},{"name":"Nauru","id":157},{"name":"Palau","id":172},{"name":"Saudi Arabia","id":197},{"name":"Tokelau","id":224}]}

In order to adapt our country names' for auto complete widget, we need to process it at first in "source" callback function:
source: function(request, response) {
  $.ajax({
   url: "countries/",//request url
   dataType: "json",
   data: {
                term: request.term //this will enable countires?term=au
               
            },
   success: function(data) {
    response($.map(data.countries, function(item) {
     return {
      label: item.name,
      value: item.name
     }
    }))
   }
  })
 },

The Complete Example





3 comments:

andrew said...

ah yes, you are excellent.
i have spent half the day trying to sort out my JSON autocompleter. my data is automatically converted to json by coldfusion, and looks like
{"QUERY":{"COLUMNS":["SUB_ID","SUB_NAME","SUB_STATE","STA_NAME"],"DATA":[[12833,"AARONS PASS",2,"NSW"],[21538,"BAALA CREEK",7,"VIC"],[2728,"YAAPEET",7,"VIC"]]},"STATUS":true}
finally thanks to you i can map it back to the id, value, label that the autocompleter expects.

Sasha said...
This comment has been removed by the author.
Satriana said...

Hi Ke Cai,
Need your tips here :
what if i want to display member ID to another input text based on selection on name in autocomplete?

I try include as below :
[code]
select: function( event, ui ) {
var x=$('#memberID').val(ui.item.label);
}
[/code]

but unfortunately it said ui.item.label is undefined. any trick here?