Sort the values in the jQuery Autocomplete
Asked Answered
E

5

8

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

Ensoll answered 20/9, 2013 at 4:12 Comment(0)
H
6
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.

Heliocentric answered 20/9, 2013 at 4:15 Comment(4)
if you read my question, I'm trying to show something like startwith. I have updated a sample screenshot.Ensoll
@user1671639 we have read your question and Dipesh did exact as you want startwith when type a word display which start with a. i have also check demo of dipesh.Bandung
@user1671639 see i have modified demo...is that you meaning..?Heliocentric
Thank you @DipeshParmar. How can I complete the list of results with the words which contain the researched term ? Like if I type "a" I get "alaska, anderson, bernardino, joaquin, madera"Enki
C
5

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: https://i.sstatic.net/GKJ8d.png

Cronus answered 25/8, 2016 at 13:54 Comment(0)
E
1

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

Elenoraelenore answered 20/9, 2013 at 4:20 Comment(4)
if you read my question, I'm trying to show something like startwith. I have updated a sample screenshot. Hope you understand.Ensoll
pressing k should returned KINGSTONE first.Ensoll
I think it is not downvoted, In this fiddle jsfiddle.net/Gm9Bz/15, if you enter "a" it is returning in reverse order.Anyway +1 I appreciate your effortEnsoll
This does not work, if you type A it will give you MADERA, JOAQUIN, BERNARDINO, ALASKA, ANDERSON in that order which is all wrong it does not do start with at all. You got king-stone first due to luck on what was in the item list.Claybourne
L
0

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)));
  }
});
Lacking answered 30/4, 2020 at 15:48 Comment(0)
A
0

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

    });
}
Adahadaha answered 9/6, 2022 at 0:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.