Javascript jQuery UI 自动完成对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28176552/
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-23 01:19:36  来源:igfitidea点击:

jQuery UI autocomplete with objects

javascriptjqueryjquery-uijquery-ui-autocomplete

提问by Darc Nawg

I'm using jQuery 1.11.2 and trying to get the autocomplete widget to parse a data array. I have to people in the array, Will Smith and Willem Dafoe. I expected to see both of the names be added to the dropdown list when I enter Wi in the text field, yet I get no response. Here is a copy of the code:

我正在使用 jQuery 1.11.2 并尝试使用自动完成小部件来解析数据数组。我必须在阵列中的人,威尔史密斯和威廉达福。当我在文本字段中输入 Wi 时,我希望看到这两个名称都添加到下拉列表中,但我没有收到任何响应。这是代码的副本:

<script src="js/jquery/jquery-1.11.2.js"></script>
<script src="js/jquery/jquery-ui.js"></script>
<link rel="stylesheet" href="js/jquery/jquery-ui.css"/>
<link rel="stylesheet" href="js/jquery/jquery-ui.theme.css"/>

<script type="text/javascript">
$(function() {
    var data = [
        {
            "id": 1,
            "first_name": "Will",
            "last_name": "Smith",
            "created_at": "2015-01-27T13:09:20.243Z",
            "updated_at": "2015-01-27T13:09:20.243Z"
        },
        {
            "id": 2,
            "first_name": "Willem",
            "last_name": "Dafoe",
            "created_at": "2015-01-27T13:17:23.479Z",
            "updated_at": "2015-01-27T13:17:23.479Z"
        }
    ];
    // Below is the name of the textfield that will be autocomplete    
    $('#search').autocomplete({
        // This shows the min length of charcters that must be typed before the autocomplete looks for a match.
        minLength: 2,
        // This is the source of the auocomplete suggestions. In this case a list of names from the people controller, in JSON format.
        source:data,
        // This updates the textfield when you move the updown the suggestions list, with your keyboard. In our case it will reflect the same value that you see in the     suggestions which is the person.given_name.
        focus: function(event, ui) {
            $('#search').val(ui.item.first_name);
            return false;
        },
        // Once a value in the drop down list is selected, do the following:
        select: function(event, ui) {
            // place the person.given_name value into the textfield called 'select_origin'...
            $('#search').val(ui.item.first_name);
            // and place the person.id into the hidden textfield called 'link_origin_id'. 
            $('#link_origin_id').val(ui.item.id);
                return false;
        }
    }).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" ).data( "ui-autocomplete-item", item ).append( "<a>" + item.first_name + "</a>" ).appendTo( ul );
        // For now which just want to show the person.given_name in the list.                             
    };
});
</script>


Search: <input type="text" id="search" />

The code is all in a single html folder on the local drive. No server is involved at this point. Also, I've checked the inspect element tool for errors, but none are shown and all resources are found and loaded.

代码全部位于本地驱动器上的单个 html 文件夹中。此时不涉及服务器。此外,我已经检查了检查元素工具是否有错误,但没有显示任何资源,并且找到并加载了所有资源。

回答by Runcorn

The problem was Autocompletecouldn't render the source for its functioning.

问题是自动完成无法呈现其功能的来源。

You need to set the source of the autocomplete based on the JSON data present using ,

您需要根据使用的 JSON 数据设置自动完成的来源,

source: function (request, response) {
           //data :: JSON list defined
           response($.map(data, function (value, key) {
                return {
                    label: value.first_name,
                    value: value.id
                }
            }));

    },

And, I also removed the .datacallback from the code.

而且,我还.data从代码中删除了回调。

See the working code here

此处查看工作代码

回答by gene b.

Working answer - with correct filtering.The filtering in the accepted answer wasn't working because nothing was being checked against request.term.

工作答案 - 正确过滤。接受的答案中的过滤不起作用,因为没有针对request.term.

 var mydata = 
[{"id": 1, "name": "John", "age": 23},
 {"id": 2, "name": "Mary", "age": 33},
 {"id": 3, "name": "Richard", "age": 53},
 {"id": 4, "name": "Ashley", "age": 25},
 {"id": 5, "name": "Kyle", "age": 17},
 {"id": 6, "name": "Samantha", "age": 29},
 {"id": 7, "name": "David", "age": 43},
 {"id": 8, "name": "Charles", "age": 27},
 {"id": 9, "name": "Elaine", "age": 41},
 {"id": 10, "name": "William", "age": 22}
];

$('#myautocomplete').autocomplete({
  minLength: 2,
  source: function (request, response) {
   response($.map(mydata, function (obj, key) {
    
    var name = obj.name.toUpperCase();
    
    if (name.indexOf(request.term.toUpperCase()) != -1) {    
     return {
      label: obj.name + " (" + obj.age + ")", // Label for Display
      value: obj.id // Value
     }
    } else {
     return null;
    }
   }));   
  },    
  focus: function(event, ui) {
   event.preventDefault();
  },
  // Once a value in the drop down list is selected, do the following:
  select: function(event, ui) {
            event.preventDefault();
   // place the person.given_name value into the textfield called 'select_origin'...
   $('#myautocomplete').val(ui.item.label);
   // ... any other tasks (like setting Hidden Fields) go here...
  }
}); 
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>    
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>

e.g. Try the string "ar" for filtering<br/>
<input id="myautocomplete" type="text" placeholder="type some key string..." />

回答by Fernando León

I have managed to make it work wonderfully in the following way:

我设法通过以下方式使其出色地工作:

$(document).on('ready',function(){
  $(function() {
    var arrLinks = [
    {% for u in users %}
      {
        nombres: "{{ u.names }} {{u.sur_names}}",
        email: "{{ u.username }}",
        documento: {{ u.identificationNumber }},
        telefono: {{ u.phone }},
        label: '{{ u.names }} {{u.sur_names}} / {{ u.username }} * Doc: {{ u.identificationNumber }} - Cel: {{ u.phone }}'
      },
    {% endfor %}
    ];
    $("input[name=search]").autocomplete({
        source: arrLinks
    }).data("autocomplete")._renderItem = function(ul, item) {
        return $("<li>").data("item.autocomplete", item).append("<a>" + item.nombres + "</a>").appendTo(ul);
    };
  });

});

Note: I work with symfony, from the controller I am sending an object with users and in the view (twig) I make a FOR with which I assign the javascript object the data I need. It is important to define in the label all the parameters for which you want to search.

注意:我使用 symfony,从控制器向用户发送一个对象,并在视图(twig)中创建一个 FOR,我用它为 javascript 对象分配我需要的数据。在标签中定义要搜索的所有参数非常重要。

Demo image!

演示图像!

$(document).on('ready',function(){
      $(function() {
        var arrLinks = [
          {
            nombres: "Fernando León",
            email: "[email protected]",
            documento: 10695846754,
            telefono: 3208123307,
            label: 'Fernando León / [email protected] * Doc: 10695846754 - Cel: 3208123307'
          },
          {
            nombres: "Edgar Molina",
            email: "[email protected]",
            documento: 736282826,
            telefono: 30087654637,
            label: 'Edgar Molina / [email protected] * Doc: 736282826 - Cel: 30087654637'
          }
        ];
        $("input[name=search]").autocomplete({
            source: arrLinks
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            return $("<li>").data("ui-autocomplete-item", item).append("<a>" + item.nombres + "</a>").appendTo(ul);
        };
      });

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<input type="text" name="search">

回答by Tyson Swing

Here is a working example that performs the autocomplete action:

这是一个执行自动完成操作的工作示例:

source: function(request, response) {
                if (!request || request.term.length < 2)
                    return;
                var term = request.term.toLowerCase();
                var r = $.grep(
                    myObjectArray,
                    function(v, i) {
                        return (v.Name.toLowerCase().indexOf(term) >= 0);
                    }).map(function(v, i) {
                    return {
                        label: v.Name,
                        value: v.Name,
                        data: v  // in case you need the data from object array
                    }
                });
                response(r);
            }