jqueryeventsjquery-ui-autocomplete

Auto open jQuery UI autocomoplete on focus


I want the autocomplete to open the drodown automatically on input focus.

Here is my example:

$(".tag-input").autocomplete({
            source: tagInputOptions,
            sortResults: true,
            select: function (event, ui) {
                var selectedValue = ui.item.value;
                if (selectedValue !== "") {
                    $(this).next(".tag-input-button").click();
                }
                return false;
            }
        }).keydown(function(event) {
            if (event.originalEvent.keyCode === 13) {
                // Enter key pressed
                event.preventDefault();
                var selectedValue = $(this).val();
                if(selectedValue !== "") {
                    $(this).next(".tag-input-button").click();
                }
            }
        }).on("focus", function () {
            $(this).autocomplete("search", " ");
        });

I have tried triggering search for it to open and it doesn´t open: $(this).autocomplete("search", " ");

I was expecting it to open with a non-filtered list.

I actually will not open and there are no errors.


Solution

  • Add minLength and focus function like this.

    var tagInputOptions = [
          "ActionScript",
          "AppleScript",
          "Asp",
          "BASIC",
          "C",
          "C++",
          "Clojure",
          "COBOL",
          "ColdFusion",
          "Erlang",
          "Fortran",
          "Groovy",
          "Haskell",
          "Java",
          "JavaScript",
          "Lisp",
          "Perl",
          "PHP",
          "Python",
          "Ruby",
          "Scala",
          "Scheme"
        ];
    $(".tag-input").autocomplete({
                source: tagInputOptions,
                sortResults: true,
                minLength : 0,              //add this line            
            }).keydown(function(event) {
                if (event.originalEvent.keyCode === 13) {
                    // Enter key pressed
                    event.preventDefault();
                    var selectedValue = $(this).val();
                    if(selectedValue !== "") {
                        $(this).next(".tag-input-button").click();
                    }
                }
            }).focus(function() {         //add this line 
                $(this).autocomplete("search", $(this).val());
            });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    
    <div class="ui-widget">
      <label for="tags">Tags: </label>
      <input id="tags" class="tag-input">
    </div>