jquery - Bootstrap 提前输入 : show different text in box once selected

标签 jquery twitter-bootstrap typeahead.js typeahead 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"}, ...

它运行得很好。当用户开始键入“标签”时,数据将显示在输入下方的列表中。但是,一旦用户单击列表项之一,我希望“值”文本显示在输入文本框中,而不是搜索到的所有标签信息!

这可能吗?

这是一个 fiddle :

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

最佳答案

我强烈建议您升级到 https://github.com/bassjobsen/Bootstrap-3-Typeahead 它与旧的 bo​​otstrap 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/

相关文章:

html - 是否可以使 Font Awesome 图标大于 'fa-5x' ?

javascript - Twitter Typeahead.js 和返回两个列表而不是一个列表的远程 URL

javascript - 使用 Algolia 和 Typeahead 在网站中提及用户

html - 什么是数据分析放置和数据分析链接?

javascript - jQuery - 未捕获的类型错误 : Object [object Object] has no method 'typeahead'

php - Ajax 发送第一个空白数据

javascript - 使用 jquery 单击 td 元素时更改其文本

javascript - 加载 gif 图像显示另一帧。使用 jquery

javascript - 单页全JavaScript动态网站

twitter-bootstrap - Bootstrap 3固定顶部导航栏显示水平滚动