JQuery autocomplete result order

I am using the jQuery-autocomplete plugin to get suggestions for completing a line input using an AJAX call to the server. In addition, the server will take care of returning the results in the order in which I want them to be displayed, but autocomplete shows them in a different order.

How can I set jQuery autocomplete to not change the output order? I do not require any processing on the client side, as the data has already been ranked / sorted as needed.

+6
source share
3 answers

Well, that turned out to be easier than I thought. I decided to read the plugin code and change it, commenting on the code sorting my output.

That is, when I found the variable "sortResults: true" in the default values. So, all I needed was to set this variable to false. I did not find this in the documentation though.

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

Now the output is executed in the order that I need.

I had the idea to read the code to find / solve the problem from here: jQuery "Autofill" plugin interferes with the order of my data (This is not the same plugin)

Thanks.:)

+8
source

Just sort the server results before sending them to autocomplete.

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 create an array of matches that begin with this term, and then combine them with matches that contain this term, but not 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: fooobar.com/questions/600380 / ...

+18
source

Since there are no sortResults parameters in the current jQuery Autocomplete plug-in assembly, I had to look for another solution to this problem and find out the only reason the plug-in sorting result is that the server response is normalized every time when it is not a clean array with objects {label : ..., value: ...}.

Given PHP as your use language, json_encode (array_values ​​($ your_array)); gotta do the trick.

+1
source

Source: https://habr.com/ru/post/917626/


All Articles