我需要使用typeahead的自动完成功能来处理名称字段,当点击该项目时,会收集id值。
$('.autocomplete').typeahead({
source: function (query, process) {
return $.get('view/_list.php', { query: query }, function (data)
{
data = $.parseJSON(data);
return process(data);
});
}
});
_list.php
[
{
"id":"47",
"nome":"Maril\u00e2ndia"
},
{
"id":"57",
"nome":"Pi\u00fama"
},
{
"id":"71",
"nome":"Sooretama"
}
]
自动完成只有在json没有id,只有name字段的情况下才有效,但如果你在json示例中添加name字段,则无效。控制台中的错误是b.toLowerCase is not a function
答案 0 :(得分:1)
您可以在对象上添加所需的所有属性,只要 你提供一个名字"属性或您提供自己的displayText 方法(source)。
Here is the defaultText
method:
displayText: function (item) {
return typeof item !== 'undefined' && typeof item.name != 'undefined' ? item.name : item;
}
因为_list.php中的对象中有nome
属性,而不是name
属性,所以需要设置displayText
方法:
$.get("_list.php", function(data){
$(".autocomplete").typeahead({ source:data,
displayText : function(item) {
return item.nome;
}
});
},'json');
答案 1 :(得分:0)
解决。
$('.autocomplet').typeahead({
displayText: function(item) {
return item.nome
},
afterSelect: function(item) {
this.$element[0].value = item.nome;
$("#field_id").val(item.id);
},
source: function (query, process) {
return $.getJSON('_list.php', { query: query }, function(data) {
process(data)
})
}
})