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

7

我正在使用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/

你的HTML长什么样?这是唯一的脚本吗?也许可以用jsfiddle演示一下? - trenthaynes
抱歉,我创建了一个演示用的fiddle。我喜欢下拉菜单中显示的“标签”信息,但一旦选择了一个项目,我希望只显示“值”信息在输入框中。我已经更新了我的原始问题,并提供了一个fiddle,希望能有所帮助。 - chris.cavage
2个回答

16
我强烈建议您升级到 https://github.com/bassjobsen/Bootstrap-3-Typeahead,它是完全相同的好老式bootstrap 2.x typeahead,在bootstrap 3.0中由于倾向于 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/ 您可以像更新中那样在fiddles中使用http://myjson.com/作为AJAX源。


谢谢。我正在尝试将您的代码适应到我的项目中。我制作了一个fiddle作为示例。然而,我是通过AJAX远程获取我的typeahead数据,并将信息返回为JSON。我不知道如何在fiddle中复制这个过程,但是我在这个新的fiddle中展示了我正在使用的代码。如果您查看它,请假设顶部的JSON数据是ajax调用返回的数据。我还根据您的要求更新了对bootstrap typeahead 3的引用。如何在您的fiddle中使用我的ajax请求完成相同的操作?http://jsfiddle.net/michels287/hwbnhbdd/ - chris.cavage
1
是的,我把它复杂化了!太感谢了!非常感谢! - chris.cavage

0

只需像这样在更新器事件中返回数据:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接