jQuery 引导程序预先输入返回名称和 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14136973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:18:08  来源:igfitidea点击:

bootstrap typeahead return name and id

jquerytwitter-bootstraptypeaheadbootstrap-typeahead

提问by iMoldovean.com

Hy! I'm using twitter bootstraps typeahead:

嗨!我正在使用 twitter bootstraps typeahead:

I'm calling a page that returns a response with json_encode the page returns a name and an ID,

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

I want that the typeahead list will show me the list of names, and when I select one of the name to write the id value to a hidden field.

我希望 typeahead 列表会显示名称列表,当我选择名称之一将 id 值写入隐藏字段时。

the calling works fine, and to write a field should be easy. what i dont know what to do is how to divide the name from the id.

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

now, when i search something, in the suggesstion list I can see the returning results like this:

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

name1:id1 name2:id2

姓名1:id1 姓名2:id2

i only want to see names but to carry the value of id too.

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

how can i do that?

我怎样才能做到这一点?

 $(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);
                                }
                            });                 
                    }
        });
});

回答by Corby Page

A typical JSON document that contains name/ID pairs is going to look like this:

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

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

The strategy here is to build an object literal that maps names to IDs as you parse the result, while only using the name to populate the typeahead:

这里的策略是构建一个对象文字,在解析结果时将名称映射到 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 } );
        } );

Once the user selects an item from the typeahead, you can reference the selected item with:

一旦用户从 typeahead 中选择了一个项目,您可以通过以下方式引用所选项目:

$( '#product' ).val()

and you can get the ID associated with the selected item with:

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

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

From your question, it looks like your JSON document may be structured a little bit differently, so you would change the parsing as appropriate, but the same general strategy applies.

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

回答by user2969295

Sorry to "resurect" this post but i was going to be crazy !

很抱歉“复活”这篇文章,但我要疯了!

If some of you have problems using theses sample codes ( none of them were working, all were returning "Undefined" instead of showing the name

如果你们中的一些人在使用这些示例代码时遇到问题(它们都没有工作,都返回“未定义”而不是显示名称

Just add

只需添加

displayKey: 'name',

Replace of course 'name' by your label var name returned by your remote source

用远程源返回的标签 var 名称替换课程“名称”

( Quite hard to find up to date samples on it, most of samples found on the net are for the previous version of typeahead and not compatibles with new ones ... )

(很难在上面找到最新的样本,网上找到的大多数样本都是针对先前版本的 typeahead 而不是与新版本兼容的......)

回答by Jhanvi

......updater: function (item) {
        var item = JSON.parse(item);
        console.log(item.name); 
        $('#VehicleAssignedTechId').val(item.id);       
        return item.name;
    }

On updater of the typeahead call you can put as above code which allows you to add selcted value in the textbox or where you have to put its value in other hidden field.

在 typeahead 调用的更新程序上,您可以放置​​如上代码,该代码允许您在文本框中添加选择的值,或者您必须将其值放在其他隐藏字段中的位置。

Full ajax call is as below:

完整的ajax调用如下:

$('#VehicleAssignedTechName').typeahead({
    source: function(query, process) {
        var $url =SITE_URL+ 'api/vehicle_techfield_typeahead/' + query + '.json';
        var $items = new Array;
        $items = [""];
        $.ajax({
            url: $url,
            dataType: "json",
            type: "POST",
            success: function(data) {
                console.log(data);
                $.map(data, function(data){
                    var group;
                    group = {
                        id: data.id,
                        name: data.name,                            
                        toString: function () {
                            return JSON.stringify(this);
                            //return this.app;
                        },
                        toLowerCase: function () {
                            return this.name.toLowerCase();
                        },
                        indexOf: function (string) {
                            return String.prototype.indexOf.apply(this.name, arguments);
                        },
                        replace: function (string) {
                            var value = '';
                            value +=  this.name;
                            if(typeof(this.level) != 'undefined') {
                                value += ' <span class="pull-right muted">';
                                value += this.level;
                                value += '</span>';
                            }
                            return String.prototype.replace.apply('<div style="padding: 10px; font-size: 1.5em;">' + value + '</div>', arguments);
                        }
                    };
                    $items.push(group);
                });

                process($items);
            }
        });
    },
    property: 'name',
    items: 10,
    minLength: 2,
    updater: function (item) {
        var item = JSON.parse(item);
        console.log(item.name); 
        $('#VehicleAssignedTechId').val(item.id);       
        return item.name;
    }
});

回答by Kate.spot

My solution is:

我的解决办法是:

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

In my case, product.id is a code, so it is useful to display it in typeahead control. In this way i avoided duplicated names risk.

在我的例子中,product.id 是一个代码,所以在 typeahead 控件中显示它很有用。通过这种方式,我避免了重名风险。

回答by osyntax

I noticed when using this code that if the match included the letters 'st', the typeahead suggestions include the style tag in the typeahead suggestions.

我在使用此代码时注意到,如果匹配项包含字母“st”,则预先输入建议在预先输入建议中包含样式标记。

For example the suggested matches would show

例如,建议的匹配将显示

style="padding: 10px; font-size: 1.5em;">standard

style="padding: 10px; font-size: 1.5em;">标准

instead of

代替

standard

标准

I changed the replace function to this:

我将替换功能更改为:

replace: function (string) {
  return String.prototype.replace.apply(this.name, arguments);
}

Obviously you lose the additional formatting, but it doesn't break on 'st' matches (I assume it would also break on 'di', or other substrings of the div tag.

显然你失去了额外的格式,但它不会在“st”匹配上中断(我认为它也会在“di”或div标签的其他子字符串上中断。

回答by ysk

I had the same issue when i tried to process username and id.I had a tricky fix but later on i have fixed it with proper solution.

当我尝试处理用户名和 ID 时,我遇到了同样的问题。我有一个棘手的修复,但后来我用正确的解决方案修复了它。

Have a look at this one,

看看这个,

$('#search').typeahead({
 source: function(query, process) {
 var $url = "/controller/function/list_users/?q="+query;
 var $datas = new Array;
 $datas = [""];
 $.ajax({
 url: $url,
 dataType: "json",
 type: "GET",
 success: function(data) {
 $.map(data, function(data){
 var group;
 group = {
 id: data.id,
 name: data.user_name,
 toString: function () {
 return JSON.stringify(this);
 //return this.variable;
 },
 toLowerCase: function () {
 return this.name.toLowerCase();
 },
 indexOf: function (string) {
 return String.prototype.indexOf.apply(this.name, arguments);
 },
 replace: function (string) {
 var value = '';
 value += this.name;
 if(typeof(this.name) != 'undefined') {
 value += ' <span class="pull-right muted">';
 //value += this.name;
 value += '</span>';
 }
 return String.prototype.replace.apply('<div style="padding: 10px; font-size: 1em;">' + value + '</div>', arguments);
 }
 };
 $datas.push(group);
 });
process($datas);
 }
 });
 },
 property: 'user_name',
 items: 10,
 minLength: 2,
 updater: function (item) {
 var item = JSON.parse(item);
 $('#hiddenId').val(item.id);
 $('#username').val(item.name);
//you can perform your actions here
//example</p>
//location = '/controller/function/'+item.id+'/edit';
 //document.redirect = location;
}
});

look at this link also.

也看看这个链接。

http://vaisakhvm.wordpress.com/2013/07/31/twitter-bootstrap-typeahead-process-multiple-values/

http://vaisakhvm.wordpress.com/2013/07/31/twitter-bootstrap-typeahead-process-multiple-values/