我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。

当按下回车键时,如何防止表单被提交?


当前回答

<div class="nav-search" id="nav-search">
        <form class="form-search">
            <span class="input-icon">
                <input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
                <i class="ace-icon fa fa-search nav-search-icon"></i>
            </span>
            <input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
        </form>

</div>

<script type="text/javascript">
    $("#search_value").on('keydown', function(e) {
        if (e.which == 13) {
             $("#search").trigger('click');
            return false;
        }
    });
    $("#search").on('click',function(){
        alert('You press enter');
    });
</script>

其他回答

重写表单的onsubmit动作,调用你的函数,并在后面添加return false,即:

<form onsubmit="javascript:myfunc();return false;" >

使用两个事件。which和event.keyCode:

function (event) {
    if (event.which == 13 || event.keyCode == 13) {
        //code to execute here
        return false;
    }
    return true;
};

在我看来,一个更简单有效的方法应该是:

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}

如果你正在使用jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});

使用TypeScript,避免多次调用该函数

let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;

function SearchListEnter(event: KeyboardEvent) {
    if (event.which !== 13) {
        return;
    }
    // more stuff
}