71

I'm using jQuery's autocomplete in a relatively simple way:

$(document).ready(function() {
  var data = [ {text: "Choice 1"}, 
               {text: "Choice 2"}, 
               {text: "Choice 3"} ]

$("#example").autocomplete(data, {
  matchContains: true,
  minChars: 0,
  formatItem: function(item) 
    { return item.text; }
    }
  );
  });

How do I add an onclick event (like a button or a link) that will display all the available choices for the autocomplete? Basically I'm looking to make a hybrid of an autocomplete and a select/dropdown element.

Thanks!

dyve
  • 5,893
  • 2
  • 30
  • 44
Rio
  • 14,182
  • 21
  • 67
  • 107

22 Answers22

102

You can trigger this event to show all of the options:

$("#example").autocomplete( "search", "" );

Or see the example in the link below. Looks like exactly what you want to do.

http://jqueryui.com/demos/autocomplete/#combobox

EDIT (from @cnanney)

Note: You must set minLength: 0 in your autocomplete for an empty search string to return all elements.

Tom Pietrosanti
  • 4,184
  • 2
  • 24
  • 29
  • 4
    This worked PERFECTLY! I changed a little, and on my input element put `onfocus="javascript:$(this).autocomplete('search','');"` . Thanks for the help! – eidylon Sep 21 '10 at 15:42
  • 45
    Worked great for me. You must set `minLength: 0` in your autocomplete for an empty search string to return all elements. Mine was set to 1 and took a little while to figure out why wasn't working. – cnanney Feb 18 '11 at 01:56
  • Glad it worked! And thanks for the clarification, cnanney! I didn't consider that at the time. – Tom Pietrosanti Apr 11 '12 at 15:22
  • 2
    This is the correct answer. Would be nice if there was a `.show()` option though! – Josh M. Apr 27 '12 at 15:39
  • just got what I wanted..great solution. Final problem solved by @cnanney too. – Arfeen Sep 29 '12 at 19:55
  • I've added @cnanney's comment into the solution for more visibility. – Tom Pietrosanti Jan 16 '13 at 14:32
  • Note in this answer really gets me out of the trouble!! I'been trying to figure for hour why sometime `autocomplete("search","")` won't show all the result. – chanp May 12 '13 at 05:52
41

I found this to work best

var data = [
    { label: "Choice 1", value: "choice_1" },
    { label: "Choice 2", value: "choice_2" },
    { label: "Choice 3", value: "choice_3" }
];

$("#example")
.autocomplete({
    source: data,
    minLength: 0
})
.focus(function() {
    $(this).autocomplete('search', $(this).val())
});

It searches the labels and places the value into the element $(#example)

Craig
  • 2,093
  • 3
  • 28
  • 43
  • 4
    I like this answer the best because if you use Tab to switch focus between inputs, it becomes clear that the the text input has autocomplete available. Some people don't use the mouse to click everything ;) – styfle Nov 01 '12 at 17:19
  • 1
    This is great! For all those who are having difficulties to get this working, the `minLength: 0` parameter seems to be essential to get this working! ;) – Andreas Jul 21 '20 at 12:48
20

I can't see an obvious way to do that in the docs, but you try triggering the focus (or click) event on the autocomplete enabled textbox:

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});
karim79
  • 339,989
  • 67
  • 413
  • 406
7

In order to show all items / simulate combobox behavior, you should first ensure you have set the minLength option to 0 (default is 1). Then you can bind the click event to perform a search with the empty string.

$('inputSelector').autocomplete({ minLength: 0 });
$('inputSelector').click(function() { $(this).autocomplete("search", ""); });
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Russell Horwood
  • 1,015
  • 1
  • 11
  • 19
6

try this:

    $('#autocomplete').focus(function(){
        $(this).val('');
        $(this).keydown();
    }); 

and minLength set to 0

works every time :)

Cobaltus
  • 61
  • 1
  • 1
5

You must set minLength to zero in order to make this work! Here is the working example.

$( "#dropdownlist" ).autocomplete({
      source: availableTags,
      minLength: 0 
    }).focus(function() {
      $(this).autocomplete('search', $(this).val())
    });
});
Brane
  • 3,257
  • 2
  • 42
  • 53
5

solution from: Display jquery ui auto-complete list on focus event

The solution to make it work more than once

<script type="text/javascript">
$(function() {
    $('#id').autocomplete({
        source: ["ActionScript",
                    /* ... */
                ],
        minLength: 0
    }).focus(function(){     
        //Use the below line instead of triggering keydown
        $(this).data("autocomplete").search($(this).val());
    });
});

Community
  • 1
  • 1
SUF
  • 51
  • 1
  • 1
4
<input type="text" name="q" id="q" placeholder="Selecciona..."/>


<script type="text/javascript">
//Mostrar el autocompletado con el evento focus
//Duda o comentario: http://WilzonMB.com
$(function () {
    var availableTags = [
        "MongoDB",
        "ExpressJS",
        "Angular",
        "NodeJS",
        "JavaScript",                
        "jQuery",
        "jQuery UI",
        "PHP",
        "Zend Framework",
        "JSON",
        "MySQL",
        "PostgreSQL",
        "SQL Server",
        "Oracle",
        "Informix",
        "Java",
        "Visual basic",
        "Yii",
        "Technology",
        "WilzonMB.com"
    ];
    $("#q").autocomplete({
        source: availableTags,
        minLength: 0
    }).focus(function(){            
       $(this).autocomplete('search', $(this).val())
     });
});
</script>

http://jsfiddle.net/wimarbueno/6zz8euqe/

Wilzon
  • 119
  • 4
3
 $j(".auto_complete").focus(function() { $j(this).keydown(); })
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
Tom
  • 31
  • 1
  • I tried this, and it worked fine the first time, but after the textbox was focused and then unfocused, if i went back to it a second time it no longer showed the autocomplete list until i refreshed the page, at which point it would again work only once. – eidylon Sep 21 '10 at 15:35
  • $(".auto_complete").focus(function() { $(this).trigger("keydown") }) -> This works! – ariel Oct 06 '10 at 11:25
2

hope this helps someone:

$('#id')
        .autocomplete({
            source: hints_array,
            minLength: 0, //how many chars to start search for
            position: { my: "left bottom", at: "left top", collision: "flip" } // so that it automatically flips the autocomplete above the input if at the bottom
            })
        .focus(function() {
        $(this).autocomplete('search', $(this).val()) //auto trigger the search with whatever's in the box
        })
Tsonev
  • 435
  • 7
  • 17
2

this shows all the options: "%" (see below)

The important thing is that you have to place it underneath the previous #example declaration, like in the example below. This took me a while to figure out.

$( "#example" ).autocomplete({
            source: "countries.php",
            minLength: 1,
            selectFirst: true
});

$("#example").autocomplete( "search", "%" );
coolguy
  • 7,866
  • 9
  • 45
  • 71
Sebastian
  • 21
  • 1
2

you can use this:

$("#example").autocomplete( "search",  $("#input").val() );
Henrik Karlsson
  • 5,559
  • 4
  • 25
  • 42
2

this is the only thing that works for me. List shows everytime and closes upon selection:

$("#example")
.autocomplete(...)
.focus(function()
{
  var self = this;

  window.setTimeout(function()
  {
    if (self.value.length == 0)
      $(self).autocomplete('search', '');
  });
})
Chris
  • 21
  • 1
1

I have seen all the answers which seem to be complete.

If you want to get the list when the cursor is in the text field OR when you click on the matching label, here how you can do:

//YourDataArray = ["foo","bar"];
$( "#YourID" ).autocomplete({
            source: YourDataArray 
        }).click(function() { $(this).autocomplete("search", " "); });

this works fine in Firefox, IE, Chrome ...

Youssef
  • 2,866
  • 1
  • 24
  • 20
1
$("#searchPkgKeyWord").autocomplete("searchURL",
        {
            width: 298,
            max: 1000,
            selectFirst: false
        }).result(function (event, row, formatted) {
            callback(row[1]);
        }).focus(function(){
            $(this).click(); //once the input focus, all the research will show
        });
Stuart
  • 711
  • 1
  • 11
  • 35
jackqqxu
  • 11
  • 2
1

I solved this using attribute minChars:0 and after, trigger two clicks. (autocomplete shows after 1 click on input) my code

<input type='text' onfocus='setAutocomplete(this)'>

function setAutocomplete(el){
    $(el).unbind().autocomplete("./index.php", {autoFill:false, minChars:0, matchContains:true, max:20});
    $(el).trigger("click");$(el).trigger("click");
}
Mesrop
  • 17
  • 2
0

I needed to do this recently and after trying a few different permutations (using onfocus, onclick of textbox etc), I finally settled on this...

 <input id="autocomplete" name="autocomplete" type="text" 
 value="Choose Document">

 <p>
 <button type="submit" value="Submit" name="submit" id="submit" >
  Submit
 </button>
 </p>

<script type="text/javascript">

$("#autocomplete").autocomplete(
{
source: '@Url.Content("~/Document/DocumentTypeAutoComplete/")' //<--ddl source
, minLength: 0 // <-- This is necessary to get the search going on blank input
, delay: 0
, select: function (event, ui) 
  {
  if (ui.item) {
     $("#autocomplete").val(ui.item.value);//<-- Place selection in the textbox
          $("docForm").submit(); 
          loadDocTypeCreatePartial(ui.item);
          $("#submit").focus(); //This stops the drop down list from reopening 
                                // after an item in the select box is chosen
                                // You can place the focus anywhere you'd like,
                                // I just chose my *submit* button
                }
   }
  }).focus(function () {
    // following line will autoselect textbox text
    // making it easier for the user to overwrite whats in the 
    // textbox
    $(this).select();

    //The below line triggers the search function on an empty string
    $(this).data("autocomplete").search('');
   });
 </script>

This opens the autocomplete ddl list on focus (Even if you have default text in your input box like I do above).

It also auto-selects the text in the text box to prevent the user from having to clear out the text.

Once an item is selected from the auto-complete list, it puts that item into the auto-complete input box and moves the focus to another control (thus preventing the auto-complete from reopening).

I plan on replacing it by adding dynamic Ajax calls to the very nice Chosen select lists with the Melting Ice upgrade when I get a chance.

0

I used this way:

$("#autocomplete").autocomplete({
                source: YourDataArray,
                minLength: 0,
                delay: 0
            });

Then

OnClientClick="Suggest(this); return false;"/>

 function Suggest(control) {
                var acControl = $("#" + control.id).siblings(".ui-autocomplete-input");
                var val = acControl.val();
                acControl.focus();
                acControl.autocomplete("search");
91m0n
  • 1
0

I could not get the $("#example").autocomplete( "search", "" ); part to work, only once I changed my search with a character that exists in my source it work. So I then used e.g. $("#example").autocomplete( "search", "a" );.

Kosmosniks
  • 186
  • 1
  • 10
0

You can also use search function without parameters:

jQuery("#id").autocomplete("search", "");
Iwo Kucharski
  • 3,735
  • 3
  • 50
  • 66
0

When input value is empty search else the value inside input. This code works for me:

$("#your_input").on('focus', function () {
   $(this).autocomplete('search', $(this).val() == '' ? " " : $(this).val());    
});
0

I guess a better option is to put $("#idname").autocomplete( "search", "" ); into the onclick paramter of the text box .

Since on select, a focus is put in by jQuery, this can be a workaround. Don't know if it should be an acceptable solution.

Dula
  • 1,276
  • 5
  • 14
  • 23
human.js
  • 1,342
  • 13
  • 15