Sort values ​​in jQuery autocomplete

I have an array like

["JOAQUIN", "BERNARDINO", "MODOC","ALASKA","MADERA", "ANDERSON"] 

where I fill them in jQuery UI Autocomplete . However, the sort order seems strange.
For example: (but I have more no.of entries) When I type "a" , it returns

 JOAQUIN BERNARDINO ALASKA MADERA ANDERSON 

I am trying to get ( starting from )

 ALASKA ANDERSON 

JSFiddle for my example

Is it possible? Can someone point me in the right direction.

Update:

enter image description here

+6
source share
3 answers
 var myarray= ["JOAQUIN", "BERNARDINO", "MODOC","ALASKA","MADERA", "ANDERSON"] myarray.sort(); 

More details

See demo

we pass two arguments to the source code: request , and the second - response ,

  • request is the request object that we create, in our case, this is the letter that we enter in the text box.

  • response is a function that will automatically return full selection parameters to us.

now inside $.map we test typed words with an array that we called json.

json.toUpperCase().indexOf(request.term.toUpperCase()) this string converts the entered word and array to the same register and returns it.

and matches will be the end result, which has a list of items that you specified.

and response(matches); send it to autocomplete.

+5
source

I ran into the same problem with objects, not with a simple string array, and sorting should be done after retrieving the results (to achieve the β€œstartswith” sentences at the top of the list). therefore, for future search engines I will add my solution.

using jQuery, you can search for lines in your result object label that begin with user input and combine the rest of the result with them, after merging, use the Underscore.js library to remove duplicates.

eg:

 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); } }); }); 

jquery ui starts with

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

+3
source

Try

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

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

enter image description here

+1
source

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


All Articles