Sort the values in the jQuery Autocomplete

一个人想着一个人 提交于 2019-11-29 07:03:36
var myarray= ["JOAQUIN", "BERNARDINO", "MODOC","ALASKA","MADERA", "ANDERSON"]
myarray.sort();

Read More

See Demo

we are passing two arguments into source one is request and second is response,

  • request is stands for request object we are making, in our case it is the letter we are typing into textbox.

  • response is function which will return us auto complete selection options.

now inside $.map we are checking typed words with array we have named json.

json.toUpperCase().indexOf(request.term.toUpperCase()) this line convert typed word and array to same case and return it.

and matches would be the final result which has list of item that you have asked.

and response(matches); will send it to autocomplete.

I faced the same issue with objects rather than simple string array, and sorting needs to be done after retrieving the results (to achieve "startswith" suggestions at the top of the list). so for future searchers, i'll add my solution.

using JQuery you can search for strings within your results object's .label that start with the user input, and merge the rest of the result to those, after merging use Underscore.js library to remove duplicates.

for example:

var objects_array = [{"label":"A_ABC","value":"0"},{"label":"B_ABC","value":"1"},{"label":"C_ABC","value":"2"}];

$(document).ready ( function() {

$('#search').autocomplete({
    source: function (request, response) {

        var results = $.ui.autocomplete.filter(objects_array, request.term);               

        var top_suggestions = $.grep(results, function (n,i) {
                                 return (n.label.substr(0, request.term.length).toLowerCase() == request.term.toLowerCase());
                              });

        var merged_results = $.merge(top_suggestions,results);

        var final_results = _.uniq(merged_results,"label");

        response(final_results);
    }
});

});

result example: http://i.stack.imgur.com/GKJ8d.png

Try it

<input type='text' />


var json = ["JOAQUIN", "BERNARDINO", "MODOC","ALASKA","MADERA", "ANDERSON", "KINGSTONE"].sort();
$('input').autocomplete({
  source: json
 });

http://jsfiddle.net/Gm9Bz/5/

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