Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap typeahead - changing source

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.

like image 782
Tzury Bar Yochay Avatar asked Nov 26 '12 10:11

Tzury Bar Yochay


4 Answers

You have to update the data field associated as indicated here :

$("selector").data('typeahead').source = list2;
like image 65
Samuel Caillerie Avatar answered Nov 10 '22 18:11

Samuel Caillerie


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 });
like image 31
Neil.Allen Avatar answered Nov 10 '22 19:11

Neil.Allen


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.

like image 1
KonstantinK Avatar answered Nov 10 '22 18:11

KonstantinK


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

like image 1
Pouria Moosavi Avatar answered Nov 10 '22 17:11

Pouria Moosavi