I'm using typeahead.js for a typeahead.
I basically want to do the reverse of this: Programmatically triggering typeahead.js result display
I've tried to do a .trigger('blur');
on the typeahead, but I set the value right before that by doing .typeahead('setQuery', value);
. Doing 'setQuery' fires off an ajax request to fetch results with the new query term. So the "blur" takes place, but the box is opened soon thereafter.
I'm using typeahead.js for a typeahead.
I basically want to do the reverse of this: Programmatically triggering typeahead.js result display
I've tried to do a .trigger('blur');
on the typeahead, but I set the value right before that by doing .typeahead('setQuery', value);
. Doing 'setQuery' fires off an ajax request to fetch results with the new query term. So the "blur" takes place, but the box is opened soon thereafter.
6 Answers
Reset to default 17The proper way to do this, as of version 0.11:
$('.typeahead').typeahead('close');
Manual: https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#jquerytypeaheadclose
Ref: https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
$('.typeahead-input').typeahead('close');
Undocumented but there is way to set precondition and not allow dropdown to open:
$('.typeahead-input').on('typeahead:beforeopen', function() {
return false;
});
In case someone comes across this in the future, the best way to do this now is:
$('.tt-dropdown-menu').css('display', 'none')
If you open Chrome developer tools and watch what happens as you type and erase, this is all Typeahead is doing, nothing magical.
Besides, if you try with the current version (10.5) to set the query, you'll get an error that looks like this:
Uncaught TypeError: Cannot assign to read only property 'highlight' of
In my particular case the dedicated close method from typeahead API ([email protected]
) did not work. Maybe because of custom CSS or some bug in my code.
While the method described in the other answer of hiding the menu by setting the display property to none worked, I needed to set it then back to display:block
to show it back for subsequent use. Plus it is not using the API.
Another better way for me was to clear the value of the input so the dropdown gets hidden:
$('.typeahead').typeahead('val', '');
or
$('#place_typeahead_control').typeahead('val', '');
in case you have multiple search controls on the page and you want to target a specific one.
You can trigger 'blur' in the "opened" event handler. If the drop down flickers for a moment, you can use CSS to hide it for the interim.
Instead of calling setQuery, add another function that doesnt do getSuggestions, and youll have a good time.
setQuery
? FYI this might require some changes to the plugin itself. – Dan-Nolan Commented Aug 14, 2013 at 23:51