I'm using Typeahead.js in an autocomplete text input, and it's great. But I need to activate the dropdown menu with all the available options when the input gets focus. Every possible solution I've seen involves initializing the input with some value, but I need to show all the options.
How could I achieve this?
Any answer that says "minLength: 0 is all you need", is NOT TRUE.
"Out Of The Box" Typeahead v0.11.1 'does need' minLength set to 0, but ALSO if you are using the out of the box Bloodhound Engine, then you need to be sure to set
identify: function(obj) { return obj.team; },
on your Bloodhound Object..
You also need a "middle man" function to handle your "empty query", which is where you will tell Bloodhound to cooperate..
function nflTeamsWithDefaults(q, sync) {
if (q === '') {
sync(nflTeams.all()); // This is the only change needed to get 'ALL' items as the defaults
} else {
nflTeams.search(q, sync);
}
}
You can see the FULL EXAMPLE here..
var nflTeams = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) { return obj.team; },
prefetch: '../data/nfl.json'
});
function nflTeamsWithDefaults(q, sync) {
if (q === '') {
sync(nflTeams.all()); // This is the only change needed to get 'ALL' items as the defaults
}
else {
nflTeams.search(q, sync);
}
}
$('#default-suggestions .typeahead').typeahead({
minLength: 0,
highlight: true
},
{
name: 'nfl-teams',
display: 'team',
source: nflTeamsWithDefaults
});
MORE SPECIFICALLY YOU CAN SEE THE OFFICIAL TWITTER TYPEAHEAD DEFAULT SUGGESTION ON FOCUS EXAMPLE AT THE FOLLOWING ADDRESS, WITH THE SIMPLE CHANGE FROM .get() TO .all() (SEE ABOVE OR BELOW)
http://twitter.github.io/typeahead.js/examples/#default-suggestions
... hope this helps someone, as it took me some time to find this information (found it by following all the bug reports & experimenting to find .all() method) ...
You need to use the option minLength: 0
Note:
There's a pull request which solved this issue
I made a quick modification to 10.2 that made "the basics" example found here display on focus.
i changed the mixin _onFocus (line 1459) FROM:
_onFocused: function onFocused() {
this.isActivated = true;
this.dropdown.open();
},
TO:
_onFocused: function onFocused() {
this.isActivated = true;
var val = this.input.getInputValue();
var query = Input.normalizeQuery(val);
this.dropdown.update(query);
this.dropdown.open();
},
It's hardly official but it got the job done.
Using 0.10.4
To return all results for blank query add the following at line 450 of bloodhound.js
if (query == "") { return that.datums; }
To trigger the match on focus trigger the key down event on your input when focused
$(input_element).on("click", function () {
ev = $.Event("keydown")
ev.keyCode = ev.which = 40
$(this).trigger(ev)
return true
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With