jQuery - 在自动完成中使用键/值对 [英] jQuery - Use key/value pair in autocomplete

查看:17
本文介绍了jQuery - 在自动完成中使用键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 ASP MVC 视图中,我从控制器传回一个键/值对.在查看 fiddler 并在 Chrome 的调试器中查看后,我可以看到信息被正确传回.

In my ASP MVC view, I am passing a key/value pair back from the controller. After looking at fiddler and viewing in Chrome's debugger I can see that the information is being passed back correctly.

我希望键/值对的 value 成为显示在 autocomplete 列表中的项目.当用户从列表中选择一个项目时,我希望将该项目的 key 放入文本框中.

I would like for the value of the key/value pair to be the item that is displayed in the autocomplete list. When the user selects an item from the list, I would like that item's key to be placed into the text box.

这是我的 jQuery 代码

Here is the jQuery code from my view

$(function () {
    $('#DRMCompanyId').autocomplete({
        source: '@Url.Action("compSearch", "AgentTransmission")',
        minLength: 2,
        select: function (event, ui) {
            $('#DRMCompanyId').val(ui.item.label);
        }
    });
});

我注意到的一件事 - 如果我将 ui 变量添加到浏览器调试器的监视列表中,我会注意到标签和值完全相同.然而,我再次看到返回的是完整的键/值对.

One thing I noticed - if I add the ui variable to the watch list in the browser's debugger I notice that the label and the value are the exact same. Again, however, I'm seeing that what's being returned is the complete key/value pair.

这是搜索完成后网络/响应控制台的屏幕截图.有些数据是私有的,所以我把它涂黑了,但是你可以看到有一个键/值对被返回.

Here is a screen shot of the Network/Response console after the search is complete. Some of the data is private so I blacked it out however you can see there is a key/value pair being returned.

推荐答案

您需要自己发出 AJAX 请求并将数据转换为 jQueryUI 期望的格式:

You'll need to make the AJAX request yourself and transform the data to the format that jQueryUI expects:

$(function () {
    $('#DRMCompanyId').autocomplete({
        source: function (request, response) {
           $.ajax({
               url: '@Url.Action("compSearch", "AgentTransmission")',
               type: 'GET',
               dataType: 'json',
               data: request,
               success: function (data) {
                   response($.map(data, function (value, key) { 
                        return {
                            label: value,
                            value: key
                        };
                   }));
               }
           });
        },
        minLength: 2
    });
});

此外,自动完成项目的 value 属性会在选择该项目时自动放置在 input 中,因此不需要自定义 选择处理程序.

Also, the value property of an autocomplete item is automatically placed in the input when that item is selected, so there should be no need for a custom select handler.

示例: http://jsfiddle.net/Aa5nK/60/

这篇关于jQuery - 在自动完成中使用键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆