I’m trying out jQuery.UI library.Developing web interfaces is very easy with this library.I was referring to the documentation and demo of using auto complete with “Remote JSONP Datasource” Here
this is the complete code for getting data from a remote source in to a autocomplete text box.
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).attr( "scrollTop", 0 );
}
$( "#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,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
I want to know what is the exact functionality of the following code segment.
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
Specially of
$.map( data.geonames, function( item )
Thanks in advance
That is an interesting piece of code.
The widget expects an array of objects where each object has properties
labeland/orvalue. What that code is attempting to create is an array that looks like that.So the call to
$.map(which is a pretty useful utility function) is transforming the array of objects retrieved from the JSONP call into an array of objects in the format described above.One way to read this:
would be: “Create a new array by taking each element of the
data.geonamesarray and transforming the element using the given function”In this case, the function just builds up an object with a
labelandvalueproperty so that it will work with the autocomplete widget.Then, that new array is immediately passed as an argument to the
responsefunction.