JQuery UI autocomplete disappears immediately

374 views Asked by At

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?

1

There are 1 answers

0
Irvin Dominin On BEST ANSWER

It's because the getJSON is async, so the responseCallback function is called when the array is empty, move the function after the each loop inside the getJSON function.

Try change it in:

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);
    });
}