jQuery Autocomplete order of results

前端 未结 3 2142
无人共我
无人共我 2021-02-14 08:34

I am using the jQuery-autocomplete plugin to get suggestions for completion of the input string using an AJAX call to a server. Also, the server takes care of returning the resu

3条回答
  •  梦谈多话
    2021-02-14 09:34

    Simply sorting the server results before sending it to autocomplete should do it.

    So before you echo json_encode($return_arr); use the sort() function on $return_arr

    You can also try something like this:

    The logic is to build up an array of matches that start with the term, and then concatenate that with matches that contain the term but don't start with it.

    $(document).ready(function () {
        var source = ['Adam', 'Benjamin', 'Matt', 'Michael', 'Sam', 'Tim'];
        $("input").autocomplete({
            source: function (request, response) {
                var term = $.ui.autocomplete.escapeRegex(request.term)
                    , startsWithMatcher = new RegExp("^" + term, "i")
                    , startsWith = $.grep(source, function(value) {
                        return startsWithMatcher.test(value.label || value.value || value);
                    })
                    , containsMatcher = new RegExp(term, "i")
                    , contains = $.grep(source, function (value) {
                        return $.inArray(value, startsWith) < 0 &&
                            containsMatcher.test(value.label || value.value || value);
                    });
    
                response(startsWith.concat(contains));
            }
        });
    });
    

    Example: http://jsfiddle.net/zkVrs/

    Source: https://stackoverflow.com/a/8302996/973155

提交回复
热议问题