20

I'm using jQuery UI Autocomplete with some AJAX (the data isn't pulled until after they stop typing). I would like to make it so once the data is found, Autocomplete will then pop-up as a search result. This works, however only when I start typing again (the dropdown doesn't trigger until I type because it's not initialized until after I stop typing).

My code:

var availableTags = [
    "Perl",
    "PHP",
    "Python",
    "Ruby"
];
$('input#mainSearchBox').autocomplete({
    source: availableTags,
        minLength: 0
});
    $('input#mainSearchBox').data('autocomplete').menu.active;

The last part was an attempt to activate autocomplete, but it fails.

1
  • You're using autocomplete with some AJAX. In that case, the popup will appear when (i) you've typed minLength characters (ii) delay milliseconds have passed since your last keystroke (iii) Ajax results have been fetched and processed. Are you sure you understand this?
    – Salman A
    Dec 3, 2012 at 15:35

3 Answers 3

53

The search method should do the trick:

$('input#mainSearchBox').autocomplete("search");

Fiddle

4
  • 1
    Ah! OMG, I used: $('input#mainSearchBox').autocomplete('search', 'demo-value'); I should have removed that...
    – TheFrack
    Dec 3, 2012 at 15:36
  • haha, the minLength is the key here. does not work without it. Dec 14, 2015 at 15:53
  • yeah, the search method was spot on!
    – break7533
    May 4, 2018 at 12:06
  • Make sure you set minLength to 0 when instantiating autocomplete. This enables it to show all options when the input is empty. autocomplete("search") uses the current input value to search and autocomplete("search", "") will show all available values
    – Maarten
    Mar 10, 2023 at 8:49
4

You can use the following script to toggle the autocomplete manually:

var textbox = $('input#mainSearchBox');
var autocompleteBox = textbox.autocomplete('widget');

// toggle the autocomplete widget
autocompleteBox.is(':hidden') ? 
    textbox.autocomplete('search', textbox.val()).focus() :
    autocompleteBox.hide();

This code can be found in the source of the combobox example on the jquery autocomplete demo site (lines 127-141).

1

For https://github.com/devbridge/jQuery-Autocomplete, you can use:

$('input#mainSearchBox').autocomplete("getSuggestions", $('input#mainSearchBox').val())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.