I looking for a way to change source
for typeahed.
For instance, assume I have the following 2 lists, and depend on the case, I'd like to have the typeahead workingin with a different source.
var list1 = ["this", "is", "first", "list"],
list2 = ["second", "list", "comes", "here"];
$("selector").typeahead({source: list1})
Then, when I do
$("selector").typeahead({source: list2})
and start typing into the input box, the first list appears underneath the new one.
I tried doing
$("selector")
.removeData()
.typeahead({source: list2})
Yet, it has no effect.
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 });
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.
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
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