Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically triggering typeahead.js result display

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 programmatically trigger the display of typeahead results without the user needing to type anything in the form field.

Out of the box, typeahead.js is only triggered if the user manually types something into the input field and i can not find any method in typeahead.js which i could call to trigger the display of results.

Any pointers would be greatly appreciated.

Thanks!

like image 345
zıəs uɐɟəʇs Avatar asked Feb 27 '13 14:02

zıəs uɐɟəʇs


5 Answers

Triggering input seems to do it.

$(".typeahead").eq(0).val("Uni").trigger("input");

Tested this on the example page.

like image 148
epascarello Avatar answered Nov 04 '22 22:11

epascarello


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();
  • On line 1, we're assigning the current value of the Typeahead input to the variable theVal;
  • On line 2 we simply reset typeahead's computed value; and
  • On line 3 we're putting back the original value and the focus, which results in the suggestion dropdown displaying as if the user had typed something.

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.

like image 21
Sam_Butler Avatar answered Nov 04 '22 22:11

Sam_Butler


$(".typeahead").typeahead('lookup').focus();

triggers with existing value of input. you can change the value in advance of course

like image 10
webenformasyon Avatar answered Nov 04 '22 22:11

webenformasyon


To anyone finding this issue with twitter's typeahead after version 0.11.1, here is how I solved it with one line:

$(".typeahead-input").typeahead('val', "cookie")
                     .trigger("input")
                     .typeahead('open');
like image 9
kcent Avatar answered Nov 04 '22 21:11

kcent


As of Typeahead v0.10.1, changing the value of the typeahead will trigger another query and open the dropdown:

var val = $(".typeahead").typeahead('val');
$(".typeahead").typeahead('val', '');
$(".typeahead").typeahead('val', val);
like image 8
Megan Avatar answered Nov 04 '22 20:11

Megan