【问题标题】:Display two values in the dropdown jquery autocomplete在下拉 jquery 自动完成中显示两个值
【发布时间】:2015-08-07 12:05:47
【问题描述】:

我正在使用 jQuery 自动完成功能制作搜索功能,其中数据来自 json。 搜索应该显示一个人的全名,但由于名字和姓氏在 json 中的两个不同字段中,我发现很难在自动完成下拉列表中同时显示名字和姓氏。

当一个人搜索两个值并在下拉列表中显示全名时,是否可以将两个值连接在一起?

JSON 示例:

{
    "GetContactsResult": [
    {
        "FirstName": "John",
        "LastName": "Doe",
        "LocalNumber": "555000",
        "MobileNumber": "555000"
            },
            {
                "FirstName": "Jane",
                "LastName": "Doe",
                "LocalNumber": "555000",
                "MobileNumber": "555000"

                    }]}

这是我的代码/html:

        <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
        <script type="text/javascript">



        $(document).ready(function(){
            $("#typedText").autocomplete({
                source: function ( request, response ) {
                    $.ajax({
                        url: "data.json",
                        dataType: "json",
                        success: function (data) {
                            var sData = data.GetContactsResult.filter(function(v) { 
                                var re = new RegExp( request.term, "i" );
                                return re.test(v.FirstName);

                            });

                            response( $.map( sData, function ( item ) {
                                return {
                                    label: item.FirstName
                                };
                            }));
                        }
                    });
                },
                minLength: 2,
            });
        });

        </script>
        <meta charset="utf-8">
        <title>click function</title>
    </head>
    <body>
        <input  id="typedText">
        <input type="button" id="getValue" value="Type value">
    </body>
    </html>

所以为了更清楚,我试图让“John Doe”显示在自动完成中,而不仅仅是“John”。

【问题讨论】:

  • 只需做label: item.FirstName + " " + item.LastName;

标签: javascript jquery jquery-ui jquery-ui-autocomplete


【解决方案1】:

您将完整的项目对象传递给响应函数。

所以在你的标签对象中这样做:

label: item.FirstName + " " + item.LastName;

应该返回全名。

【讨论】:

  • 谢谢!!!我早些时候试图做这个标签:item.FirstName +“”+标签:item.LastName;。但是你知道如果我先输入姓氏是否可以获得相同的结果吗?
  • 最后,是的,但是您需要在过滤函数中包含另一个条件。
  • 请注意搜索值带有 + |等等将在您的正则表达式测试中失败,因为它们没有被转义。
  • 好的,我一直在尝试向我的过滤器函数添加一个条件,但我必须说我不知道​​在哪里放置它。关于正则表达式没有被转义。在第二个条件起作用之前我需要这样做吗?
  • return re.test(v.FirstName) || re.test(v.LastName);
猜你喜欢
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
相关资源
最近更新 更多