72

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!

22 Answers 22

103

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.

7
  • 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, 2010 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, 2011 at 1:56
  • Glad it worked! And thanks for the clarification, cnanney! I didn't consider that at the time. Apr 11, 2012 at 15:22
  • 2
    This is the correct answer. Would be nice if there was a .show() option though!
    – Josh M.
    Apr 27, 2012 at 15:39
  • just got what I wanted..great solution. Final problem solved by @cnanney too.
    – Arfeen
    Sep 29, 2012 at 19:55
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)

2
  • 4
    I like this answer the best because if you use <key>Tab</key> 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 1, 2012 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, 2020 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
});
2
  • 2
    See Tom Pietrosanti's answer bellow for the way to do this without using a trigger or a button.
    – njfife
    Jan 2, 2014 at 17:18
  • 2
    See Craig's answer below as well. Sep 29, 2015 at 2:04
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", ""); });
6

try this:

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

and minLength set to 0

works every time :)

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

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

3
 $j(".auto_complete").focus(function() { $j(this).keydown(); })
2
  • 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, 2010 at 15:35
  • $(".auto_complete").focus(function() { $(this).trigger("keydown") }) -> This works!
    – ariel
    Oct 6, 2010 at 11:25
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', '');
  });
})
2

you can use this:

$("#example").autocomplete( "search",  $("#input").val() );
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", "%" );
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
        })
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");
}
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 ...

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

2
  • You may need to set minChars to 0.
    – Spongeboy
    Dec 8, 2010 at 4:29
  • is it working if you do: $("#example").autocomplete( "search", " " ); ?
    – Youssef
    Jan 11, 2013 at 11:34
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");
0

You can also use search function without parameters:

jQuery("#id").autocomplete("search", "");
0
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.