Reputation: 5774
I wanted to implement functionality where if I click on one DOM element then it should automatically populate one typeahead with designated value inside it, it should trigger the typeahead:selected
for the same.
I found many queries related to it and answer was jQuery#typeahead('val', val)
or jQuery#typeahead('setQuery', myQuery)
but both did only select the option I wanted, it did not trigger the click on dropdown option. is there any way to do that?
Upvotes: 3
Views: 4317
Reputation: 398
To trigger it like if the user has made the click on the item you must update the value in the field with your data.
The short answer is like Sergey Stativa posted: $('.typeahead').val(yourValue).trigger('change');
The long answer with a case usage example is here, and I'm adding a sollution that uses Bloodhound, but the core of your question is not this complex, I just hope it may help someone in the future, so it's all here.
Lets assume you have a template like this:
var arrNames = ['Luke','Han','Leia'];
var nameDisplayBh = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.RebelNames);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: arrNames
});
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},{
name: Names Display,
source: nameDisplayBh.ttAdapter(),
display:"RebelNames",
templates:
{
suggestion: function(data)
{
return "<div>data.name</div>";
}
}
});
$('.typeahead').bind('typeahead:select', function(ev, suggestion)
{
console.log(suggestion.name);
});
var nameInYourList = arrNames[0];
$('.typeahead').val(nameInYourList).trigger('change');
Upvotes: 3
Reputation: 61
You should call change
event to apply a new value
$('.typeahead').val(Your value).trigger('change');
Upvotes: -1