When using JQuery UI's autocomplete, the dropdown results appear to never appear. However, when debugging, the list appears for a short number of statements before disappearing. My code is as follows:
HTML:
<input type="text" placeholder="search" class="myautocomplete" />
<script>
$(document).load(function(){initializeAutocomplete()});
</script>
Javascript:
function initializeAutocomplete() {
$('.myautocomplete').autocomplete({delay: 300, minLength: 2, source: autocomplete});
}
function autocomplete(request, responseCallback) {
var dataUrl = "http://something.com/Suggestions.json?search_string=" + request.term;
var suggestions = [];
$.getJSON(dataUrl, function(json) {
$.each(json.AutoSuggestions, function(index) {
suggestions.push(this.SearchTerm);
});
});
responseCallback(suggestions);
}
What is causing the autocomplete list to instantly disappear?
It's because the
getJSONis async, so theresponseCallbackfunction is called when the array is empty, move the function after the each loop inside the getJSON function.Try change it in: