我正在使用 bootstrap typeahead 进行搜索,如下所示:
$('.lookup').typeahead({
source: function (query, process) {
return $.getJSON(
'json_autocomplete.php',{ query: query },
function (data) {
var newData = [];
$.each(data, function(){
newData.push(this.label);
//populate hidden field with id
$('#contact_id').val(this.id);
});
return process(newData);
});
}
});
JSON 数据如下所示:
[{"label":"Contact: Jeff Busch-> Busch, Jeff: 1975-11-24","value":"Busch, Jeff","id":"2096"}, ...
它运行得很好。当用户开始键入“标签”时,数据将显示在输入下方的列表中。但是,一旦用户单击列表项之一,我希望“值”文本显示在输入文本框中,而不是搜索到的所有标签信息!
这可能吗?
这是一个 fiddle :
最佳答案
我强烈建议您升级到 https://github.com/bassjobsen/Bootstrap-3-Typeahead 它与旧的 bootstrap 2.x typeahead 完全一样,只是在自己的存储库中进行维护和错误修复,因为 bootstrap 3.0 跳过了 typeahead,转而使用 typeahead.js
(顺便说一句,根本不再维护)。这将使您的生活变得更加轻松。
之后您可以跳过所有扭曲并简单地执行以下操作:
$('#contact').typeahead( {
source: jsonData,
displayText: function(item) {
return item.label
},
afterSelect: function(item) {
this.$element[0].value = item.value
}
})
更新了 fiddle -> http://jsfiddle.net/qdgo651h/1/
<小时/>根据评论更新。我相信你把 source
过于复杂化了部分
$('.lookup').typeahead({
displayText: function(item) {
return item.label
},
afterSelect: function(item) {
this.$element[0].value = item.value
},
source: function (query, process) {
return $.getJSON('json_autocomplete.php', { query: query }, function(data) {
process(data)
})
}
})
应该这样做。从下面的评论更新了 fiddle -> http://jsfiddle.net/hwbnhbdd/1/ 您可以使用http://myjson.com/ 作为更新中的 fiddle 中的 AJAX 源。
关于jquery - Bootstrap 提前输入 : show different text in box once selected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36340499/