My code is working fine with local data, but if I copy the local data to a json file and use the prefetch option it doesn't work, it just returns an undefined list.
I'd like to use prefetched data and listen to the custom event handle typeahead:selected to populate multiple input fields. Any suggestion to fix this issue? Thanks.
My code is here:
<form>
<input type="text" class="typeahead" id="subject_label" /><br/>
<input type="text" id="subject_id" /><br/>
</form>
var s = [{"id":"1234","label":"fish"},{"id":"5678","label":"histo"}]
var labels = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.label);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
// local option is working
// local: s
// If using prefetch url option with exactly same dataset, the code is broken, I'm
//sure the url format is correct.
prefetch: '/sample.json'
});
labels.initialize();
var subjectLabelTypeahead = $('#subject_label.typeahead');
var subjectIdTypeahead = $('#subject_id');
// Initialise typeahead
subjectLabelTypeahead.typeahead({
highlight: true
}, {
name: 'label',
displayKey: 'label',
source: labels.ttAdapter()
});
// Set-up event handlers so that the ID is auto-populated when select label
var subjectLabelItemSelectedHandler = function (e, datum) {
subjectIdTypeahead.val(datum.id);
};
subjectLabelTypeahead.on('typeahead:selected', subjectLabelItemSelectedHandler);
Your "prefetch" value should reference a javascript object instead of the URL string (see the documentation here).
Try changing it to this:
var labels = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.label);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/sample.json',
filter: function(items) {
return $.map(items, function(item) {
return {
label: item.label,
id: item.id };
});
}
});