Bootstrap typeahead:选中后在框中显示不同的文本

chr*_*age 7 jquery typeahead twitter-bootstrap bootstrap-typeahead typeahead.js

我使用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);

        });
}

 });
Run Code Online (Sandbox Code Playgroud)

JSON数据如下所示:

 [{"label":"Contact: Jeff Busch-> Busch, Jeff: 1975-11-24","value":"Busch, Jeff","id":"2096"}, ...
Run Code Online (Sandbox Code Playgroud)

它工作得很好.当用户开始键入"标签"时,数据显示在输入下的列表中.但是,一旦用户点击其中一个列表项,我希望"值"文本出现在输入文本框中,而不是所有搜索到的标签信息!

这可能吗?

这是一个小提琴:

http://jsfiddle.net/michels287/qdgo651h/

dav*_*rad 12

我强烈建议你升级到https://github.com/bassjobsen/Bootstrap-3-Typeahead这是完全相同的好旧引导2.x预先,只是在自己的存储库中维护和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
  }
}) 
Run Code Online (Sandbox Code Playgroud)

更新小提琴 - > 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)
    })
  }   
})
Run Code Online (Sandbox Code Playgroud)

应该这样做.从下面的评论更新小提琴 - > http://jsfiddle.net/hwbnhbdd/1/ 您可以在更新中使用http://myjson.com/作为小提琴中的AJAX源.