Alex Alex - 7 months ago 8
Javascript Question

Controlling the display of selected item using jQueryUI Autocomplete widget

I'm using the jQueryUI autocomplete widget to get data from a JSON web service. Its very similar to the example below:

<script>
$(function() {
$( "#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.id
}
}));
}
});
},
minLength: 2
});
});
</script>


My question is how can I control what is put into the input box (#city) when something is selected from the list. At the moment the autocomplete works well and will give a list of labels. However when you select one of the list items it puts the value into the input. In this case its an id that i want to use but I want the input to display the label data rather than the value data.

Answer

Well you would have to make the value the same as the label. In your case it would look like this:

success: function( data ) {
   response( $.map( data.geonames, function( item ) {
      return {
         label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
         value: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
      }

   }));
}

My guess is that you need the value for other purposes. I have had the same situation, and depending on your requirements there are a couple of options.

You could have a hidden field, in which you can store the value when an options is selected.

This is how it would look:

$(function() {
    $( "#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.id,
                            source: item
                        }
                    }));
                }
            });
        },
        minLength: 2,
        change: function(event, ui) {
           if (ui.item) {
              $('#your_hidden_input').val(ui.item.source.id);
              $(this).val(ui.item.value);
           }
        }
    });
});