簡體   English   中英

jQuery UI 自動完成對象

[英]jQuery UI autocomplete with objects

我正在使用 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" />

代碼全部位於本地驅動器上的單個 html 文件夾中。 此時不涉及服務器。 此外,我已經檢查了檢查元素工具是否有錯誤,但沒有顯示任何資源,並且找到並加載了所有資源。

問題是自動完成無法呈現其功能的來源。

您需要根據使用的 JSON 數據設置自動完成的來源,

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

而且,我還從代碼中刪除了.data回調。

此處查看工作代碼

工作答案 - 正確過濾。 接受的答案中的過濾不起作用,因為沒有針對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"/> eg Try the string "ar" for filtering<br/> <input id="myautocomplete" type="text" placeholder="type some key string..." />

我設法通過以下方式使其出色地工作:

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

});

注意:我使用 symfony,從控制器向用戶發送一個對象,並在視圖(twig)中創建一個 FOR,我用它為 javascript 對象分配我需要的數據。 在標簽中定義要搜索的所有參數非常重要。

演示圖像!

 $(document).on('ready',function(){ $(function() { var arrLinks = [ { nombres: "Fernando León", email: "efleon9@gmail.com", documento: 10695846754, telefono: 3208123307, label: 'Fernando León / efleon9@gmail.com * Doc: 10695846754 - Cel: 3208123307' }, { nombres: "Edgar Molina", email: "fleon@fitpal.co", documento: 736282826, telefono: 30087654637, label: 'Edgar Molina / fleon@fitpal.co * 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">

這是一個執行自動完成操作的工作示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM