I am using Twitter\'s typeahead.js (https://github.com/twitter/typeahead.js/) on an input field which is pre filled from a query string. After loading the page, i\'d like to
I tried every method here but it was not working, only by using
$(".typeahead").val('hi').trigger('keyup');
$(".typeahead").val('hi').trigger('keydown');
The above code it worked for me. Don't know what exactly happened but using neither one worked only by using both it got worked.
Triggering input seems to do it.
$(".typeahead").eq(0).val("Uni").trigger("input");
Tested this on the example page.
I used this to manually trigger a selection, when 1 item was in the tt-dataset. It just made sense to add this.
$("#mytypeahead").keyup(function (e) {
var charCode = (typeof e.which === "number") ? e.which : e.keyCode;
if (charCode == 13) {
if ($(this).parent().find(".tt-dataset").children().length == 1) {
//This is how we are submitting a single selection on enter key
$(this).parent().find(".tt-dataset").children(0).addClass("tt-cursor");
var kde = jQuery.Event("keydown");
kde.which = 13;
$(this).trigger(kde);
}
}
});
According to my tests (see fiddle), the focus() method is necessary in order to display the dropdown. So:
theVal = $('.typeahead').val();
$(".typeahead").typeahead('val', '')
$(".typeahead").focus().typeahead('val',theVal).focus();
I actually needed this to strongly encourage users to select from the Bloodhound suggestions coming from a geocoding API call so I could ensure the coordinates were obtained by the client prior to submitting a form.
This should work with the "old" bootstrap typeahead plugin:
$(".typeahead").eq(0).trigger("keyup");
Haven't tested with IE unfortunately... Don't know about the new typeahead plugin...
Looking through the source code, it appears to store a TypeaheadView
object in the element data under the key typeahead
. This TypeaheadView
object has an internal method, _showDropdown
, which is internally bound to the focus event (and a few others).
I would not recommend doing this, but you should be able to call that internal method manually:
$('#yourTypeaheadElement').data('typeahead')._showDropdown();
Alternatively, have you just tried simply focusing your typeahead element when the page loads (after initializing it as a typeahead element, of course):
// after page loads and yourTypeaheadElement is initialized as a typeahead
$('#yourTypeaheadElement').focus();