jquery - bootstrap typeahead 返回名称和 id

标签 jquery twitter-bootstrap typeahead bootstrap-typeahead

嘿!我正在使用 twitter bootstraps typeahead:

我正在调用一个返回带有 json_encode 的响应的页面 该页面返回一个名称和一个 ID,

我希望输入列表能够显示姓名列表, 当我选择其中一个名字时 将 id 值写入隐藏字段。

调用工作正常,并且编写字段应该很容易。 我不知道该怎么做是如何将名称与 ID 分开。

现在,当我搜索某些内容时,在建议列表中我可以看到如下返回结果:

名称1:id1 名称2:id2

我只想看到名称,但也想携带 id 的值。

我该怎么做?

 $(function(){
    $("#typeahead_<? print $key; ?>").typeahead(
        {
        source: function(query, process)
                    {
                    $.ajax({
                        url:    '/getAjaxProducts',
                        type:   'POST',
                        data:   'query=' + query,
                        dataType: 'JSON',
                        async: true,
                        success: function(data)
                                {
                                process(data);
                                }
                            });                 
                    }
        });
});

最佳答案

包含名称/ID 对的典型 JSON 文档如下所示:

[
  {
    "id": 1
    "name": "firstName"
  },
  {
    "id": 2
    "name": "secondName"
  }
]

这里的策略是构建一个对象文字,在解析结果时将名称映射到 ID,同时仅使用名称来填充预先输入:

var productNames = new Array();
var productIds = new Object();
$.getJSON( '/getAjaxProducts', null,
        function ( jsonData )
        {
            $.each( jsonData, function ( index, product )
            {
                productNames.push( product.name );
                productIds[product.name] = product.id;
            } );
            $( '#product' ).typeahead( { source:productNames } );
        } );

用户从预输入中选择一个项目后,您可以通过以下方式引用所选项目:

$( '#product' ).val()

您可以通过以下方式获取与所选项目关联的 ID:

productIds[$( '#product' ).val()]

从您的问题来看,您的 JSON 文档的结构可能略有不同,因此您将根据需要更改解析,但适用相同的一般策略。

关于jquery - bootstrap typeahead 返回名称和 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14136973/

相关文章:

jquery - 如何从具有相同类的唯一 div 获取文本值

javascript - 如何将此 html 脚本应用到 jQuery 中?

html - Bootstrap 4.0 input-group-append 和 prepend 显示错误的高度

javascript - 无法在 jQuery 上对我的 html 列表进行排序

javascript - 当用户向上滚动到标题时,jQuery 显示 div

javascript - Angular ui-bootstrap typeahead 选择多个

javascript - 带有远程数据源的 Typeahead.js

twitter-bootstrap - 如何在多个属性上搜索对象(knockout.js+ twitter bootstrap typeahead)?

javascript - 使用 jQuery UI 问题使 Bootstrap 模式可调整大小

jquery - Bootstrap 时间选择器禁用字母输入