I have an array like
["JOAQUIN", "BERNARDINO", "MODOC","ALASKA","MADERA", "ANDERSON"]
where I'm populating them in a jQuery UI Autocomplete
. However the order of sorting seems to be weird.
For example:(But I have more no.of records) When I type "a" it returns
JOAQUIN
BERNARDINO
ALASKA
MADERA
ANDERSON
What I'm trying is to get (starting with)
ALASKA
ANDERSON
JSFiddle for my example
Is it possible? Can someone point me in a right direction.
Updates:
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With