bootstrap typeahead - changing source
You have to update the data field associated as indicated here :
$("selector").data('typeahead').source = list2;
None of these answers worked for me when using the Bootstrap-3-Typeahead library. I was able to update the source by destroy the initialized typeahead and re initializing it with a new source:
$(".typeahead").typeahead("destroy");
$(".typeahead").typeahead({ source: result });
I'm not sure I understand your situation right, but as you said "and depend on the case, I'd like to have the typeahead workingin with a different source.", I think you can use a function as a source to typeahead
instead of an array. Like so:
function typeAheadSourceFunc(inputText) {
if(inputText.length === 1) {
return ['Amsterdam', 'Washington', 'Sydney', 'Beijing', 'Cairo'];
} else {
return ['OtherAmsterdam', 'OtherWashington', 'OtherSydney'];
}
}
$("SOMESELECTORHERE").typeahead({ source: typeAheadSourceFunc });
typeAheadSourceFunc
in this example will fire every time a keypressed
fires on input and returns a different source. You probably can handle your situation there.
p.s: I am using bootstrap3-typeahead.js v4.0.2
Unfortunately, the accepted answer didn't work for me. It could be an issue with newer versions of the library. For me, data('typeahead') isn't defined - instead there is data('ttTypeahead') and data('ttAttrs'). Neither of those has a source attribute.
After some code reading I came up with this:
$('selector').data('ttTypeahead').dropdown.datasets[0].source = mySourceFunction
And it seems to work. There might be instances where more than one dataset is defined, though.