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?

FOX 9000
  • 123
  • 1
  • 1
  • 6
santhosh
  • 1,894
  • 3
  • 18
  • 23

15 Answers15

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/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 7
    Works like a charm. Is it very usefull if your autocompletion list is very long (~10k results) and slows html rendering. – Benjamin Crouzier Oct 09 '11 at 21:39
  • 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* ^__^ – Alisso Jan 12 '13 at 05:00
  • 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 :/ – Alisso Jan 12 '13 at 17:45
  • +1 for this solution. I will add minLength:3 to narrow more the results. http://jsfiddle.net/vqwBP/295/ – Adrian P. Jun 19 '13 at 21:28
  • 2
    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. – HPWD Dec 13 '13 at 17:45
  • Perfect one which I was looking for, it uses default jQuery functionalities and achives and even loads 10k items faster. Thanks man. – Balasubramani M Jun 23 '16 at 05:56
  • In my Source i gave url as like this, Eg: source: '{{ url("/companySearch") }}', Is there any chance for me. To limit the results. – Siva Ganesh Jan 08 '18 at 10:36
  • 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] – snucky May 20 '19 at 15:51
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;}
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
  • Genius. I love the simplicity of this and it lets the user decide. – denislexic Jan 07 '12 at 16:26
  • 20
    This is quite hacky. If you have a really long list, and autocomplete returns thousands of matches, it will be bloody slow... – Vajk Hermecz Dec 10 '12 at 08:40
  • 1
    Agree with Vajk. This is a poor solution from a scalabilty point of view. – Kiksy Apr 16 '13 at 09:55
  • 4
    Agree with Vajk. Do not play with CSS when the game is in JS. – Adrian P. Jun 19 '13 at 21:29
  • I did the same thing in my dictionary application. Its worthy! – Moxet Jan Oct 09 '14 at 15:44
  • 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. – pid Jun 08 '17 at 07:29
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

Sam Battat
  • 5,725
  • 1
  • 20
  • 29
  • 4
    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! – Adrian P. Aug 16 '13 at 02:10
  • 3
    @SamBattat Using css for a programming problem is a horrible hack. Imagine trying to debug that! – Christian Payne Oct 03 '13 at 02:03
23

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!

Community
  • 1
  • 1
SNag
  • 17,681
  • 10
  • 54
  • 69
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.

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
Desto
  • 111
  • 1
  • 2
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;
}
Sam
  • 147
  • 3
  • 10
  • 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](https://stackoverflow.com/help/privileges/vote-up) 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](https://stackoverflow.com/help/why-vote). – jps Nov 24 '17 at 15:42
  • this is xactly what I was looking for ! not limiting the number of results but the number of shwn items ! thx – Serge insas Dec 12 '17 at 22:35
  • Why this answer has so little upvotes? Is there something wrong with it? Worked for me, at least at the first sight. – Szybki May 28 '19 at 19:34
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

the_nutria
  • 75
  • 5
  • 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. – Adrian P. Jun 19 '13 at 21:12
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
}
}
));
AH Jamali
  • 31
  • 4
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
   }
});
myjeeed
  • 21
  • 3
2

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

$('#task').autocomplete({
  maxShowItems: 5,
  source: myarray
});
KingRider
  • 2,140
  • 25
  • 23
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
    };
    }));
},
Tatiana
  • 31
  • 5
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,
                }
            }
        })
    );
},
tlberio
  • 36
  • 2
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!

Hasan Patel
  • 412
  • 7
  • 19
0

There is no max parameter.

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

dteoh
  • 5,794
  • 3
  • 27
  • 35
0
.ui-menu-item{
    display: none;
}
.ui-menu-item:nth-child(-n+5){
    display: block;
}
Jasbir Rana
  • 259
  • 3
  • 13
  • 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? – Jeremy Caney Jun 27 '23 at 00:17