I'm using typeahead/bloodhound for suggestions pulling from an ajax source:
var protags = new Bloodhound({
datumTokenizer: function(protags) {
return Bloodhound.tokenizers.whitespace(protags.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/ajax/getinfo.php?q=%QUERY',
wildcard: '%QUERY',
filter: function(response) {
return response.protags;
}
}
});
JSON result from getinfo.php looks like this:
{
"protags": [
{"tag": {
"tagid": "1",
"tagtitle": "titleone"}
},
{"tag": {
"tagid": "2",
"tagtitle": "titletwo"}
},
{"tag": {
"tagid": "3",
"tagtitle": "titlethree"}
}]}
I'm able to retrieve all the information i want (tagtitle AND tagid) and display it using:
$('.typeahead').typeahead(
{ hint: true,
highlight: true,
minLength: 1
},
{
name: 'protags',
displayKey: function(protags) {
return protags.tag.tagtitle+'-'+protags.tag.tagid;
},
source: protags.ttAdapter()
});
But i'm confused about that: how can i display just the tagtitle in the suggestion field, but getting the protags.tag.tagid as well for more serverside actions?
Use the :select event (v 0.11.x), or :selected event (v.0.10.x). Read the bloodhound/typeahead docs as they made a lot of changes between 0.10.x and 0.11.x
I'm using 0.10.5 and in my case it looks like this:
EDIT: looking at your json, I'm not sure what data goes into template and :selected function. You may need to use data.protags.tag etc
$(selector).typeahead(
// options, key, source etc
templates: {
suggestion: function (data) {
return '<div class="tt-name">' + data.tag.tagtitle + '</div>';
}
}
// end of options
)
.on('typeahead:selected',
function(event, data) {
// you should be able to get your data here, if I'm correct like so:
console.log(data.tag.tagid);
}
);