jQuery-ui自动完成多个值按字母顺序排序结果

时间:2013-02-09 03:57:34

标签: jquery jquery-ui sorting jquery-ui-autocomplete

参考这个问题Sorting Autocomplete UI Results based on match location,有一个解决方案可以提供单值jQuery自动完成,但是有可能为多个值jQuery自动完成(http://jqueryui.com/autocomplete/#multiple)获得类似的解决方案吗?

2 个答案:

答案 0 :(得分:2)

这里唯一的区别是你需要确保并且像你所链接的演示一样调用extractLast。以下是应该使用多个值的完整代码(特别注意source选项):

$("#tags")
    .on("keydown", function (event) {
        if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
            event.preventDefault();
        }
    })
    .autocomplete({
        minLength: 0,
        source: function (request, response) {
            var term = $.ui.autocomplete.escapeRegex(extractLast(request.term))
                // Create two regular expressions, one to find suggestions starting with the user's input:
                , startsWithMatcher = new RegExp("^" + term, "i")
                , startsWith = $.grep(source, function(value) {
                    return startsWithMatcher.test(value.label || value.value || value);
                })
                // ... And another to find suggestions that just contain the user's input:
                , containsMatcher = new RegExp(term, "i")
                , contains = $.grep(source, function (value) {
                    return $.inArray(value, startsWith) < 0 &&
                        containsMatcher.test(value.label || value.value || value);
                });            

            // Supply the widget with an array containing the suggestions that start with the user's input,
            // followed by those that just contain the user's input.
            response(startsWith.concat(contains));
        },
        focus: function () {
            return false;
        },
        select: function (event, ui) {
            var terms = split(this.value);
            terms.pop();
            terms.push(ui.item.value);
            terms.push("");
            this.value = terms.join(", ");
            return false;
        }
});

示例: http://jsfiddle.net/Aa5nK/1/

答案 1 :(得分:0)

在回复中,您应该返回与查询中所需内容匹配的结果列表:

e.g。

list_of_terms = {"term0","term1","term2",...};

$("#inputsearch").autocomplete({
    var term = request.term
    var list = new Array();
    source: function( request, response ) {
        var cnt = 0;
        $.each(list_of_terms, function(i) {
            var rSearchTerm = new RegExp('^' + RegExp.quote(term),'i');
            if (list_of_terms[i].match(rSearchTerm)) {                 
                list[cnt] = list_of_terms[i];
                cnt++;
            }
       });
     response(list);
    }
});



RegExp.quote = function(str) {
    return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};

如果我没有错过括号,如果输入的术语等于list_of_terms数组中术语的开头,则应该在下拉列表中为您提供多个值