Question

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:

enter image description here

Was it helpful?

Solution

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.

OTHER TIPS

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

});

jquery ui starts with

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/

enter image description here

Actually there is an Example in the API documentation that touches on what you requested. Here is my (somewhat shortened) take on a solution:

var json = ["JOAQUIN", "BERNARDINO", "MODOC", "ALASKA", "MADERA", "ANDERSON"].sort();
$( "#autocomplete" ).autocomplete({
  source: function(request, response) {
    // Escape regex
    var term = $.ui.autocomplete.escapeRegex(request.term);
    // Search results that start with the search term
    var matcher1 = new RegExp("^" + term, "i");
    // Search results that start differently
    var matcher2 = new RegExp("^.+" + term, "i");

    function subarray(matcher) {
        return $.grep(json, function(item) {
            return matcher.test(item);
        });
    }
    response($.merge(subarray(matcher1), subarray(matcher2)));
  }
});

This should work for ajax/JSON results as well and now the right arrow key also fills the input

function inlineAutoComplete(auto_complete_input, json) {
    var elem = auto_complete_input;
    jQuery('[data-inline-autocomplete]').remove();
    jQuery(elem).parent().append('<span data-inline-autocomplete="' + elem + '" class="inline-auto-complete" style="display:none"></span>');
    jQuery(elem).keyup(function(ev, ui) {
        if(jQuery(this).val() != '')
            jQuery(this).parent().find('[data-inline-autocomplete]').show();

        if(ev.which == 13 || ev.which == 39) {
            jQuery(this).val( jQuery(this).parent().find('[data-inline-autocomplete] em').text() );
            jQuery(this).parent().find('[data-inline-autocomplete]').hide();
            return;
        }

        var term = jQuery(this).val();

        var matcher = new RegExp("^" + term);
        if (typeof json === 'string' || json instanceof String) {
           jQuery.ajax({
                url: json ,
                data: { term: term },
                success: function(response) {
                    jQuery.each(response.json, function(i, item) {
                        if(matcher.test(item)) {
                            jQuery('[data-inline-autocomplete="' + elem + '"]').show();
                            jQuery('[data-inline-autocomplete="' + elem + '"]').html('<em class="d-block">' + item + '</em>');
                            return;
                        } else {
                            jQuery(this).parent().find('[data-inline-autocomplete]').hide();
                        }
                    });
                }
            });
        } else {
            jQuery.each(json, function(i, item) {
                if(matcher.test(item)) {
                    jQuery('[data-inline-autocomplete="' + elem + '"]').show();
                    jQuery('[data-inline-autocomplete="' + elem + '"]').html('<em class="d-block">' + item + '</em>');
                    return;
                } else {
                    jQuery(this).parent().find('[data-inline-autocomplete]').hide();
                }
            });
        }
        jQuery('[data-inline-autocomplete="' + elem + '"]').click(function(ev) {
                    ev.stopPropagation();
                    jQuery(elem).val(jQuery(this).text());
                    jQuery(this).hide();
        });

    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top