jquery autocomplete renderItem

拜拜、爱过 提交于 2019-12-05 00:48:05

It seems that .data('autocomplete') is now .data('ui-autocomplete').

Source: http://jqueryui.com/upgrade-guide/1.10/#removed-data-fallbacks-for-widget-names

By default, autocomplete expects your source array to contain objects with either a label property, a value property, or both.

With that in mind you have two options:

  1. Add a label or value property to your source objects when you process the array from your AJAX call:

    var data_results = $("Entry", xmlResponse).map(function () {
        return {
            var1: $.trim($("Partno", this).text()),
            var2: $.trim($("Description", this).text()),
            var3: $.trim($("SapCode", this).text()),
            var4: $("Title", this).text(),
            var5: $.trim($("File", this).text()),
            var6: $.trim($("ItemID", this).text()),
            value: $.trim($("Description", this).text())
        };
    }).get();
    

    The value you assign will be used on focus, select, and to search on.

  2. Change the source function to perform custom filtering logic:

    $("#searchresults").autocomplete({
        source: function (request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
    
            response($.grep(data, function (value) {
                return matcher.test(value.var1) || 
                       matcher.test(value.var2);
                /* etc., continue with whatever parts of the object you want */
            }));
        },
        minLength: 3,
        select: function (event, ui) {
            event.preventDefault();
            this.value = ui.var1 + ui.var2;
        },
        focus: function (event, ui) {
            event.preventDefault();
            this.value = ui.var1 + ui.var2;
        }
    }).data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" ).data("item.autocomplete", item)
                .append( "<a>" + item.var1 + "<br>" + item.var2 + "</a>")
                .appendTo( ul );
    };
    

    Note that with this strategy you have to implement custom select and focus logic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!