jQuery-ui autocomplete multiple values sort results alphabetically

陌路散爱 提交于 2019-12-02 08:21:48

The only difference here is that you need to make sure and call extractLast like the demo you linked to is doing. Here's the complete code that should work with multiple values (pay particular attention to the source option):

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

Example: http://jsfiddle.net/Aa5nK/1/

In the response, you should return a list of result that match what you want in your query:

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

provided i didn't miss a parenthesis, this should give you multiple values in your dropdown if the term entered equals the start of a term in your list_of_terms array

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