Reputation: 3715
Is it possible to add two sources to the Bootstrap Typeahead with custom separator?
Currently I have
source: function (query, process) {
...
process(data.names.merge(data.areas));
...
}
However I would very much like to add custom HTML between the results from the two. Right now they are also mixed together when shown, where I want them in two separate lists with the custom HTML being the separator.
Is it possible?
Upvotes: 2
Views: 1506
Reputation: 22332
The answer is yes. You will need to know where the separator should occur in the combined list, which will be widdled down to what matches the user's typed-in "query" (this.query
).
You can change the generated HTML by overriding the render
method, which you need direct access to the typeahead
object to do:
var typeahead = $("#myTypeahead").typeahead(/* ... */).data('typeahead');
typeahead.render = function(items) {
var that = this
// this "map"s the items, which iterates over them and generates a new
// li for each item _by default_; I have modified it
items = $(items).map(function (i, item) {
// return an array containing raw HTML Elements
var elements = []
// determine if separator is necessary, but make sure that it
// is not the first li (which this would be if it matched the
// i === 0 item!)
if (item === "worthSeparating") {
// put whatever you want as the separator in the elements array,
// which will appear in the position that you return it
// you probably don't want text, rather you want some CSS class
elements.push($("<li/>").addClass("menu-separator")[0])
}
// ordinary li that is displayed:
i = $(that.options.item).attr('data-value', item)
i.find('a').html(that.highlighter(item))
elements.push(i[0])
return elements
});
items.first().addClass('active')
this.$menu.html(items)
return this
};
The render
method above is modified from the default one. You have complete control over what happens. In fact, if you don't like the default menu, then you can convert the menu by passing it different options that are supplied by default as:
{
menu: '<ul class="typeahead dropdown-menu"></ul>',
item: '<li><a href="#"></a></li>'
}
Changing those will require different changes to the render
method.
Upvotes: 1