I have defined a custom template for suggestions in Bootstrap's Typeahead as mentioned below. But when I select any of the suggestions, I get only the country name in input. Since I have passed country in displayKey parameter. Is there anyway that I can select both the country and city name in input (Same as in template)?
Here is the JsFiddle: http://jsfiddle.net/geekowls/agrg3xhj/
I have also read the Examples on Typeahead website. But didn't find anything relevant. All I Know is that the displayKey parameter can take a function.
$(document).ready(function () {
var dataSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country', 'city'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function (obj) { return obj.country; },
prefetch: "../Data/1.json"
});
function dataSourceS(q, sync) {
dataSource.search(q, sync);
}
$('.typeahead').typeahead( {
minLength: 0,
highlight: true
}, {
name: 'countries',
displayKey: 'country',
source: dataSourceS,
templates: {
empty: [
'<div class="empty">No Matches Found</div>'
].join('\n'),
suggestion: function (data){
return '<div>' + data.country + ' – ' + data.city + '</div>'
}
}
}
);
});
Here is the Json file.
[
{
"country": "Holland",
"city": "Amsterdam"
},
{
"country": "Belgium",
"city": "Brussel"
},
{
"country": "Germany",
"city": "Berlin"
},
{
"country": "France",
"city": "Paris"
}
]
The function was simple enough. Just needed to update the display parameter as:
display: function(item){ return item.country+'–'+item.city}
Also updated the code on fiddle here: http://jsfiddle.net/geekowls/agrg3xhj/1/
Cheers!