如何在自动完成jquery中选择项目时提交表单?

时间:2012-03-31 08:03:12

标签: javascript jquery html autocomplete

这是我的应用的JavaScript和HTML

<script>
$(function() {
    $( "#searchfield" ).autocomplete({
        source: "http://localhost/search.php",
        minLength: 1,
        select: function( event, ui ) {
                        $("#search_form").submit(); 
        }
    });
});
</script>

<form id="search_form" action="search" method="get">
                <input id="searchfield" type="text" name="q" value="Search..." onfocus="if (this.value == 'Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search...';}" />
                <input id="searchbutton" type="submit" name="submit" value="Search" />
                </p>
            </form>

当有人按下下拉菜单中所选项目的回车键时,我希望这样。表格应该提交。和页面导航到目标页面。 问题是这段代码不起作用。当我按下回车键时表单不提交。 请给我一些代码。感谢

enter image description here

在这种情况下,我想提交表格。

1 个答案:

答案 0 :(得分:2)

当按下ENTER键并且菜单打开时,该插件可防止事件冒泡:

case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
    // when menu is open and has focus
    if (self.menu.active) {
        // #6055 - Opera still allows the keypress to occur
        // which causes forms to submit
        suppressKeyPress = true;
        event.preventDefault();
    }​

您可以重新绑定keydown事件并检查ENTER键是否按下以提交表单:

$( "#searchfield" )
    .autocomplete()
    .bind('keydown', function() {
        var key = event.keyCode;
        if (key == $.ui.keyCode.ENTER || key == $.ui.keyCode.NUMPAD_ENTER) {
            $('#search_form').submit();
        }
    });​

<强> DEMO