代码之家  ›  专栏  ›  技术社区  ›  Rudi

在下拉jquery自动完成中显示两个值

  •  2
  • Rudi  · 技术社区  · 11 年前

    我正在使用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”。

    1 回复  |  直到 11 年前
        1
  •  3
  •   Mouser    11 年前

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

    因此,在标签对象中执行以下操作:

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

    应返回全名。