Reputation: 10044
Using twitter typeahead: https://twitter.github.io/typeahead.js
I'm trying to initialize multiple typeaheads via a data-typeahead
attribute which represents part of the URL I want to use as the source.
I need to be able to call this after dynamic new [data-typeahead]
elements are added to the page.
My code is not working at all. It doesn't even work on [data-typeahead]
elements which are already on the page.
$('[data-typeahead]').typeahead({
source: function (query, process) {
$.get(this.$element.data('typeahead')+'/'+query, function (data) {
alert(data);
process(data);
});
},
items: 10
});
Any help would be greatly appreciated.
Upvotes: 0
Views: 585
Reputation: 10044
Had to create a new function containing an each loop and call it when the page loads, as well as any time a new typeahead element is added to the DOM.
The each loop destroys all existing typeaheads and then re-initializes them.
I spent hours on this and this is the only solution that worked.
function initialize_typeaheads () {
$('[data-typeahead]').each(function () {
var element = $(this);
element.typeahead('destroy');
var results = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: element.data('typeahead')+'/'+'%QUERY',
wildcard: '%QUERY'
}
});
element.typeahead(null, {
source: results,
limit: 10
});
});
}
Upvotes: 0