Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Autocomplete order of results

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 results in the order I would want them to appear but autocomplete shows them in a different order.

How can I configure jQuery autocomplete to not reorder the output ? I don't require any kind of processing on the client's end as the data has already been ranked/sorted as required.

like image 692
rajatkhanduja Avatar asked Jun 08 '12 12:06

rajatkhanduja


1 Answers

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

like image 173
Farhan Ahmad Avatar answered Nov 16 '22 00:11

Farhan Ahmad