jQuery Autocomplete order of results

前端 未结 3 2143
无人共我
无人共我 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:20

    Well, it turned out to be simpler than I thought. I decided to read the code of the plugin and modify it by commenting out the code that sorts my output.

    That is when I found a variable 'sortResults:true' in defaults. So, all I needed was to set that variable to false. I didn't find this in the documentation though.

    $('#search').autocomplete ( { url: "index.php", sortResults: false } )

    Now the output is in the exact order that I require.

    I got the idea of reading the code to find/solve the problem from here : jQuery "Autocomplete" plugin is messing up the order of my data (That isn't the same plugin)

    Thanks. :)

    0 讨论(0)
  • 2021-02-14 09:32

    Since there's no sortResults options in current build of jQuery Autocomplete plugin, I had to search another solution to this problem and found out the only reason the plugin is sorting result is that server response is being normalized everytime it's not a pure array with objects {label: ..., value: ...}.

    Considering PHP as a language of your use, json_encode(array_values($your_array)); should do the trick.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题