How to make jQuery autocomplete list display all options onfocus and hide after option is selected?

Michael picture Michael · Nov 21, 2011 · Viewed 9.6k times · Source

I have a form with an autocomplete that starts the search "onfocus" and shows the option list when the user clicks into the search field, even when they do not enter anything.

The problem is the autocomplete requires the option to be selected with either the keyboard (down arrow followed by tab/return or with a double click). My first thought was that a single click causes the focus to remain in the search field, and thus the autocomplete to stay visible. However, the search field remains focused after the second click, but the autocomplete disappears after the second click.

Any ideas?

<script>
$(document).ready(function() {

    var autocomplete_focus = function(){           
        if ($(this).val().length == 0) {
            $(this).autocomplete("search", "%");
        }
    }   

    $( ".autocomplete" ).autocomplete({
            source: "../../db/autocomplete_list.php",
            minLength: 0
    });

    $( ".autocomplete" ).focus(autocomplete_focus);

});
</script>

I realize a similar question has been posted on here before; however, the proposed solutions are not working for me.

Answer

Andrew Whitaker picture Andrew Whitaker · Nov 21, 2011

Not sure if this is an acceptable solution, but one way to do this is to populate the input with the focused value. This prevents the menu from showing twice:

/* snip: */
focus: function (event, ui) {
    this.value = ui.item.value;
},

Here's an example: http://jsfiddle.net/wxQf7/

Try removing the focus event handler to see the symptom in the question.