I am trying to get a value and the id from this data-set.
Getting one thing is easy, but I don't know how I can get the second information?
Important to know is, that in my site can be a dynamically number of input fields which all have to use this function.
This is the JS Code
// Datas
var datas = new Bloodhound({
datumTokenizer: function(d) { return d.tokens; },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'autocomplete.php?s=1&li=5&query=%QUERY',
wildcard: '%QUERY' }
});
$('#orga_id').typeahead(null,
{
name: 'orga_id_autosuggest',
displayKey: 'desc',
input: 'value',
highlight: true,
hint: false,
limit: 5,
minLength: 2,
wildcard: '%QUERY',
source: datas.ttAdapter(),
templates: {
suggestion: Handlebars.compile([
'<div class=\"media\">',
'<div class=\"pull-left\">',
'<div class=\"media-object\">',
'<img src=\"{{img}}\" width=\"50\" height=\"50\"/>',
'</div>',
'</div>',
'<div class=\"media-body\">',
'<h4 class=\"media-heading\">{{value}}</h4>',
'<p>{{desc}}</p>',
'</div>',
'</div>',
].join(''))
}
});
And in the html form something like this
<input type="text" name="3_orga_name[]" class="form-control autosugbtn" value="" />
<input type="hidden" name="3_orga_id[]" value="">
That's the Feedback of the PHP File
$results[] = array(
"value" => $res['DS'],
"desc" => $res['ORG_NAME'],
"img" => "http://lorempixel.com/50/50/?" . (rand(1, 10000) . rand(1, 10000)),
"tokens" => array($query, $query . rand(1, 10))
);
To get more than one values from your dataset, you have to transform your result set and return a key-value pair. So in the example below, the response
is a JSON string that I receive, and then I get all the values I need.
A friendly reminder to everyone who are still using Twitter-Typeahead is to move away from this repository as it is no longer maintained. Instead redirect yourself to corejavascript/typeahead.js which is a fork of the original repository, and the same author (@JakeHarding) maintains this repository.
I am using v0.11.
HTML
<div id="prefetch">
<input class="typeahead" type="text" placeholder="Countries">
</div>
JS
var tags = new Bloodhound({
datumTokenizer: function(datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'http://www.yourwebsite.com/js/data.json',
cache: false,
transform: function(response) {
return $.map(response, function (tag) {
return {
name: tag.tagName,
id: tag.tagId
}
});
}
}
});
$('#prefetch .typeahead').typeahead({
minLength: 3,
highlight: true
}, {
name: 'tags-dataset',
source: tags,
display: 'name',
templates: {
suggestion: function (data) {
return '<p><strong>' + data.id + '</strong> - ' + data.name + '</p>';
}
}
})
.bind('typeahead:select', function (ev, suggestion) {
console.log(ev);
console.log(suggestion);
$('#your-id').attr('value', ev.id);
});
Here is a working JSFIDDLE example to get you started.