Limit results in jQuery UI Autocomplete
Asked Answered
V

15

138

I am using jQuery UI Autocomplete.

 $("#task").autocomplete({
     max:10,
     minLength:3,
     source: myarray
 });          

The max parameter doesn't work and I still get more than 10 results. Am I missing something?

Vortical answered 1/10, 2011 at 0:43 Comment(1)
There is no option called max in autocompleteAntetype
S
287

Here is the proper documentation for the jQueryUI widget. There isn't a built-in parameter for limiting max results, but you can accomplish it easily:

$("#auto").autocomplete({
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(myarray, request.term);

        response(results.slice(0, 10));
    }
});

You can supply a function to the source parameter and then call slice on the filtered array.

Here's a working example: http://jsfiddle.net/andrewwhitaker/vqwBP/

Sumach answered 1/10, 2011 at 1:50 Comment(8)
Works like a charm. Is it very usefull if your autocompletion list is very long (~10k results) and slows html rendering.Rabideau
Thank you so very much for this! Now I can let users have a massive list in localStorage, but the website feels really fast! Lovely! :D thank you so much for this! :D so happy I happend to find this solution ^__^Rubi
what if one has two autocomplete boxes on the same page? When I do the response slice on both, the both stop slicing at all :/Rubi
+1 for this solution. I will add minLength:3 to narrow more the results. jsfiddle.net/vqwBP/295Stull
In the jsFiddle the solution provided, change the slice value from 10 to 3 and then in the input box, enter the character C. you will only receive 3 values which to an end user could lead them to believe those are the only three values available and may not continue entering characters. All I'm suggesting is to provide good help text to accompany this solution (e.g. Only the top XX matched results will be displayed. Continue typing to refine the results." Something along those lines.Trexler
Perfect one which I was looking for, it uses default jQuery functionalities and achives and even loads 10k items faster. Thanks man.Fiveandten
In my Source i gave url as like this, Eg: source: '{{ url("/companySearch") }}', Is there any chance for me. To limit the results.Cautious
based on Andrew's solution I would like to add that this works for remote sources via AJAX as well. here's a working code example: [code]source: function(request, response) { jQuery.ajax({ url: 'api/autosuggest.php', data: 'term='+encodeURIComponent(request.term), dataType: 'json', success: function(results) { if (results.length > 10) { var crop = results.slice(0, 10); crop.push({ id: -1, label: 'Limited 10/'+results.length }); response(crop); } else { response(results); } } }) }[/code]Eimile
A
49

You can set the minlength option to some big value or you can do it by css like this,

.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}
Antetype answered 1/10, 2011 at 1:1 Comment(6)
Genius. I love the simplicity of this and it lets the user decide.Violence
This is quite hacky. If you have a really long list, and autocomplete returns thousands of matches, it will be bloody slow...Ideal
Agree with Vajk. This is a poor solution from a scalabilty point of view.Sciurine
Agree with Vajk. Do not play with CSS when the game is in JS.Stull
I did the same thing in my dictionary application. Its worthy!Lindyline
Years have passed but I must say one thing. If the result is more than 30-40-50 lines it gets unusable pretty quick. Do you really help the user if there are thousands o_O of lines? I'd rather show only 20 results and say "there are 2391 more results" than show them all.Cutwork
W
26

Same like "Jayantha" said using css would be the easiest approach, but this might be better,

.ui-autocomplete { max-height: 200px; overflow-y: scroll; overflow-x: hidden;}

Note the only difference is "max-height". this will allow the widget to resize to smaller height but not more than 200px

Wallford answered 20/4, 2012 at 17:0 Comment(2)
Because of your solution. Even it is a valid one we are discussing jQuery solutions. Offering a CSS solution to a programmer is not a good idea when the problem can be solved to jQuery. And at the end this is just mask the results not solving the problem as in the accepted answer. Here you go!Stull
@SamBattat Using css for a programming problem is a horrible hack. Imagine trying to debug that!Phylloid
C
24

Adding to Andrew's answer, you can even introduce a maxResults property and use it this way:

$("#auto").autocomplete({ 
    maxResults: 10,
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(src, request.term);
        response(results.slice(0, this.options.maxResults));
    }
});

jsFiddle: http://jsfiddle.net/vqwBP/877/

This should help code readability and maintainability!

Cashmere answered 18/11, 2014 at 4:50 Comment(0)
C
11

here is what I used

.ui-autocomplete { max-height: 200px; overflow-y: auto; overflow-x: hidden;}

The overflow auto so the scroll bar will not show when it's not supposed to.

Consistory answered 30/7, 2013 at 13:17 Comment(0)
C
6

I could solve this problem by adding the following content to my CSS file:

.ui-autocomplete {
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;
}
Creditable answered 24/11, 2017 at 15:21 Comment(3)
Please don't add "thanks" as answers. They don't actually provide an answer to the question, and can be perceived as noise by its future visitors. Instead, upvote answers you like. This way future visitors of the question will see a higher vote count on that answer, and the answerer will also be rewarded with reputation points. See Why is voting important.Draughtsman
this is xactly what I was looking for ! not limiting the number of results but the number of shwn items ! thxDottiedottle
Why this answer has so little upvotes? Is there something wrong with it? Worked for me, at least at the first sight.Motley
H
3

If the results come from a mysql query, it is more efficient to limit directly the mysql result:

select [...] from [...] order by [...] limit 0,10

where 10 is the max numbers of rows you want

Helluva answered 18/11, 2012 at 13:35 Comment(1)
Not good to query a DB every mouse up! Can be slow on some servers or huge DB. By the way, I didn't vote down but write this explanation. What people should do when they vote down. Thanks.Stull
U
2

I did it in following way :

success: function (result) {
response($.map(result.d.slice(0,10), function (item) {
return {
// Mapping to Required columns (Employee Name and Employee No)
label: item.EmployeeName,
value: item.EmployeeNo
}
}
));
Unitarianism answered 31/8, 2014 at 5:33 Comment(0)
V
2

jQuery allows you to change the default settings when you are attaching autocomplete to an input:

$('#autocomplete-form').autocomplete({
   maxHeight: 200, //you could easily change this maxHeight value
   lookup: array, //the array that has all of the autocomplete items
   onSelect: function(clicked_item){
      //whatever that has to be done when clicked on the item
   }
});
Vet answered 23/4, 2015 at 1:42 Comment(0)
H
2

Plugin: jquery-ui-autocomplete-scroll with scroller and limit results are beautiful

$('#task').autocomplete({
  maxShowItems: 5,
  source: myarray
});
Hanoverian answered 18/8, 2016 at 19:43 Comment(0)
T
2

I've tried all the solutions above, but mine only worked on this way:

success: function (data) {
    response($.map(data.slice (0,10), function(item) {
    return {
    value: item.nome
    };
    }));
},
Teston answered 21/10, 2016 at 0:58 Comment(0)
M
0

There is no max parameter.

http://docs.jquery.com/UI/Autocomplete

Mercurous answered 1/10, 2011 at 0:55 Comment(2)
I see the max parameter from this link, docs.jquery.com/UI/Autocomplete/autocomplete under the options menuVortical
I don't see any "max" param on your link.Stull
O
0

In my case this works fine:

source:function(request, response){
    var numSumResult = 0;
    response(
        $.map(tblData, function(rowData) {
            if (numSumResult < 10) {
                numSumResult ++;
                return {
                    label:          rowData.label,
                    value:          rowData.value,
                }
            }
        })
    );
},
Oyster answered 28/11, 2017 at 7:50 Comment(0)
A
0

I'm leaving this one for anyone who is using this library

JavaScript-autoComplete/1.0.4/auto-complete.js

This might be helpful as the Demo version doesn't show how to limit results. Based on Andrew response.

new autoComplete({
    selector: 'input[name="name_of_searchbox"]',
    minChars: 1,
    source: function(term, suggest){
    term = term.toLowerCase();
    var choices = [];
     var matches = []; //For Pushing Selected Terms to be always visible, can be adapter later on based on user searches
      for (i=0; i<choices.length; i++)
          if (~choices[i].toLowerCase().indexOf(term)) matches.push(choices[i]);
      suggest(matches.slice(0,10));
     }
    });

Hope this is of use to anyone. Cheers!

Abbess answered 4/1, 2022 at 16:8 Comment(0)
K
0
.ui-menu-item{
    display: none;
}
.ui-menu-item:nth-child(-n+5){
    display: block;
}
Kiki answered 22/6, 2023 at 7:15 Comment(1)
Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?Hobbyhorse

© 2022 - 2024 — McMap. All rights reserved.