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

Bootstrap typeahead: show different text in box once selected

我正在使用 bootstrap 提前输入搜索:

 $('.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"}, ...

效果很好。当用户开始输入 "label" 时,数据会显示在输入下方的列表中。但是,一旦用户单击列表项之一,我希望 "value" 文本出现在输入文本框中,而不是搜索到的所有标签信息!

这可能吗?

这是 fiddle:

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

我会强烈建议你升级到 https://github.com/bassjobsen/Bootstrap-3-Typeahead 它是 exact 相同的好旧 bootstrap 2.x typeahead,自从 bootstrap 3.0 跳过了 typeahead 以支持 typeahead.js(BTW 根本不再维护)后,就在自己的存储库中进行了维护和错误修复。这将使您的生活更轻松。

在那之后你可以跳过所有的扭曲并简单地这样做:

$('#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/ 作为 AJAX 来源 fiddle。

只是 return 更新事件的数据是这样的:

    updater: function (item) {
        $('#id').val(map[item].id);

        //Here we return the text to display on the input control
        return map[item].autocomplete;
    },