$('.typeahead').typeahead({
ajax: {
url: './test.php',
triggerLength: 1
},
onSelect: function(item) {
console.log(item); // return full object
console.log(item.value); // return value - it your id
return item;
}
});
Bootstrap 3 with Typeahead - how get id from json?
-
22-07-2023 - |
Pregunta
$('.typeahead').typeahead({
ajax: {
url: './test.php',
triggerLength: 1
}
});
test.php returns json:
[{"id":"13","name":"\u0410\u0420\u0425\u0418\u0412"},
{"id":"12","name":"\u041a\u043e\u043f\u0438\u0440\u0430\u0439\u0442\u0435\u0440"},
{"id":"11","name":"\u041f\u043e\u043c\u043e\u0449\u043d\u0438\u043a \u043c\u0435\u043d\u0435\u0434\u0436\u0435\u0440\u0430"}]
Tell me please how me output in console.log()
or in alert()
element id
from json when we select value typeahead?
P.S.: or only how get id
from json ?
Solución
Otros consejos
Assign this to some variable, and then using index get element, and then its field ID:
var a = [{"id":"13","name":"\u0410\u0420\u0425\u0418\u0412"}, {"id":"12","name":"\u041a\u043e\u043f\u0438\u0440\u0430\u0439\u0442\u0435\u0440"},
{"id":"11","name":"\u041f\u043e\u043c\u043e\u0449\u043d\u0438\u043a \u043c\u0435\u043d\u0435\u0434\u0436\u0435\u0440\u0430"}]
And then you get:
a[0].id = 13
This is the common way to work with Typeahead (100% working code from a project I did):
var films = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: './test.php'
});
films.initialize();
$('.typeahead').typeahead(null, {
displayKey: 'value',
source: films.ttAdapter(),
templates: {
suggestion: Handlebars.compile('<p>{{value}} ({{year}}) <span class="label label-elegant">{{videoRes width height}}</span></p>')
}
});
It uses Handlebars for templating and Bloodhound as suggestion engine https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md
Now, as you said, you need to make a console.log
of your received data, here is the example code:
var films = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: './test.php'
});
films.initialize();
var autocomplete_template = Handlebars.compile('<p>{{value}} ({{year}}) <span class="label label-elegant">{{videoRes width height}}</span></p>');;
function suggestions_html(x){
// Log function
console.log(JSON.stringify(x));
return autocomplete_template(x);
}
$('.typeahead').typeahead(null, {
displayKey: 'value',
source: films.ttAdapter(),
templates: {
suggestion: suggestions_html
}
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow