JQuery Autocomplete not filling input with selected item
asp.net-mvc, autocomplete, javascript, jquery, jquery-ui
Solution
If you add `event.preventDefault();` as the first line in the select function that should stop the field emptying:
select: function (event, ui) {
event.preventDefault();
$("#FullAddress").val(ui.item['FullAddress']);
...
}
Problem
I have a jQuery UI Autocomplete which is being populated by a third party web service. The autocomplete is working correctly, however when I select an item from the list the autocomplete input field goes blank. The autocomplete is used to search an address, once selected the address gets split into its components which fill out the rest of the form. So I have the following input field ids: `#FullAddress, #AddressLine1,#AddressLine2, #AddressSuburb,#AddressState, #AddressPostcode` with `#FullAddress` being the autocomplete field. The web service returns an array of objects each containing key value pairs named pretty much as above. Originally the JS code looked like: ``` $("#FullAddress").autocomplete({ source: "URL", dataType: "JSONP", autoFocus: true, select: function (event, ui) { $("#FullAddress").val(ui.item['FullAddress']); $("#AddressLine1").val(ui.item['Line1']); $("#AddressLine2").val(ui.item['Line2']); $("#AddressSuburb").val(ui.item['Suburb']); $("#AddressState").val(ui.item['State']); $("#AddressPostcode").val(String(ui.item['Postcode'])); } }); ``` Which contacted the server and was returning results, but they were not being displayed in the dropdown: Clicking any option filled out all fields with address data (you just couldn't see which address you selected) apart from `#FullAddress` which gets blanked out. i.e. in the image above once one was selected the "123 te" disappears. I discovered the following to add to the `create` event which fixed the dropdown display issue, but did not fix the fact that the `#FullAddress` field gets blanked no matter what happens. ``` $("#FullAddress").autocomplete({ source: "URL", dataType: "JSONP", autoFocus: true, create: function () { $(this).data('ui-autocomplete')._renderItem = function (ul, item) { return $("<li>") .append('<a>' + item.FullAddress + '</a>') .appendTo(ul); }; }, select: function (event, ui) { $("#FullAddress").val(ui.item['FullAddress']); $("#AddressLine1").val(ui.item['Line1']); $("#AddressLine2").val(ui.item['Line2']); $("#AddressSuburb").val(ui.item['Suburb']); $("#AddressState").val(ui.item['State']); $("#AddressPostcode").val(String(ui.item['Postcode'])); } }); ``` Does any one know any other reasons why the autocomplete input field would be emptying? It does not appear to care whether or not an item was selected, no matter what happens on blur the field empties. Thanks