如何使jQuery自动完成列表显示所有选项onfocus并在选择选项后隐藏? [英] How to make jQuery autocomplete list display all options onfocus and hide after option is selected?

查看:175
本文介绍了如何使jQuery自动完成列表显示所有选项onfocus并在选择选项后隐藏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自动完成功能的表单,该表单会启动"onfocus"搜索,并在用户单击搜索字段时显示选项列表,即使他们没有输入任何内容.

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.

问题是自动完成功能需要使用键盘(向下箭头,然后按Tab/返回或双击)来选择选项.我首先想到的是,单击一下鼠标即可将焦点保留在搜索字段中,从而使自动完成功能保持可见.但是,第二次单击后,搜索字段仍保持焦点,但是第二次单击后,自动完成功能消失了.

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.

有什么想法吗?

<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.

推荐答案

不确定这是否可以接受,但是一种解决方法是用焦点值填充input.这样可以防止菜单显示两次:

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;
},

以下是示例: http://jsfiddle.net/wxQf7/

尝试删除focus事件处理程序以查看问题中的症状.

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

这篇关于如何使jQuery自动完成列表显示所有选项onfocus并在选择选项后隐藏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆