Bootstrap typeahead:选中后在框中显示不同的文本
我使用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"}, ...
它工作得很好。 当用户开始键入“标签”时,数据显示在输入下的列表中。 但是,一旦用户点击其中一个列表项,我希望“值”文本出现在输入文本框中,而不是所有搜索到的标签信息!
这可能吗?
这是一个小提琴:
http://jsfiddle.net/michels287/qdgo651h/
我强烈建议你升级到https://github.com/bassjobsen/Bootstrap-3-Typeahead它是完全相同的好旧引导2.x typeahead,只是在自己的存储库中维护和bugfixed,因为bootstrap 3.0跳过了typeahead in type支持typeahead.js
(BTW不再维护)。 这将使您的生活更轻松。
之后,您可以跳过所有扭曲,只需执行此操作:
$('#contact').typeahead( { source: jsonData, displayText: function(item) { return item.label }, afterSelect: function(item) { this.$element[0].value = item.value } })
更新小提琴 – > 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) }) } })
应该这样做。 从下面的评论更新小提琴 – > http://jsfiddle.net/hwbnhbdd/1/您可以在更新中使用http://myjson.com/作为小提琴中的AJAX源代码。
只需返回updater事件的数据,如下所示:
updater: function (item) { $('#id').val(map[item].id); //Here we return the text to display on the input control return map[item].autocomplete; },