I'm trying to return a specific data from the json but it returns nothing.
I took the example from http://jsfiddle.net/Fresh/1hrk0qso/ It works perfectly when using the example url.
url: 'https://cdn.rawgit.com/twitter/typeahead.js/gh-pages/data/countries.json',
It also works when I do it from localhost
url: '../json/countries.json',
But, when I change the countries.json file to include multiple fields(see JSON below), it does not return anything.
JSON:
[
{"cities_id":"1","city":"Attignat","postal_code":"01340"},
{"cities_id":"2","city":"Beaupont","postal_code":"01270"},
{"cities_id":"3","city":"B\u00e9ny","postal_code":"01370"}
]
JS (modified only to return 'city' in replace for 'name' from the JSON file):
var countries = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('city'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '../json/json_cities.json',
filter: function (countries) {
return $.map(countries, function (city) {
return {
city: city
};
});
}
}
});
// Initialize the Bloodhound suggestion engine
countries.initialize();
$('.typeahead_city').typeahead(null, {
name: 'city',
displayKey: 'city',
source: countries.ttAdapter()
});
I really do not understand because it is mostly the same as the example as well: How do I list objects for Typeahead.js and/or with the Bloodhound engine?
Thanks a lot
Return the following properties in second parameter of typeahead method. If you want to return multiple items you have to use display property, instead of displaykey. While you could customize your suggestions with suggestion property.
$('.typeahead_city').typeahead();
{ name: 'countries',
display: function(item){
return item.city+'–'+item.postal_code},
source: dataSource.ttAdapter(),
suggestion: function (data) {
return '<div>' +data.city + '–' + data.postal_code + '</div>'}
}
Here is the working fiddle.