如何防止在基于web的应用程序中按ENTER键提交表单?


当前回答

放入javascript外部文件

   (function ($) {
 $(window).keydown(function (event) {  

    if (event.keyCode == 13) {

        return false;
    }
});

 })(jQuery);

或者在body tag里面

<script>


$(document).ready(function() {
    $(window).keydown(function(event) {
        alert(1);

        if(event.keyCode == 13) {

            return false;
        }
    });
});

</script>

其他回答

[2012修订版,没有内联处理程序,保留textarea进入处理]

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

现在你可以在表单上定义一个按键处理程序: <形式[…onkeypress="return checkEnter(event)">

document.querySelector('form').onkeypress = checkEnter;

如果这些答案都不适合你,试试这个。在实际提交表单的按钮之前添加一个提交按钮,对事件什么都不做。

HTML

<!-- The following button is meant to do nothing. This button will catch the "enter" key press and stop it's propagation. -->
<button type="submit" id="EnterKeyIntercepter" style="cursor: auto; outline: transparent;"></button>

JavaScript

$('#EnterKeyIntercepter').click((event) => {
    event.preventDefault(); //The buck stops here.
    /*If you don't know what this if statement does, just delete it.*/
    if (process.env.NODE_ENV !== 'production') {
        console.log("The enter key was pressed and captured by the mighty Enter Key Inceptor (⌐■_■)");
    }
});

将这个标签添加到你的表单- onsubmit="return false;" 然后只能使用JavaScript函数提交表单。

我也遇到了同样的问题(表单包含大量的文本字段和不熟练的用户)。

我是这样解决的:

function chkSubmit() {
    if (window.confirm('Do you want to store the data?')) {
        return true;
    } else {
        // some code to focus on a specific field
        return false;
    }
}

在HTML代码中使用这个:

<form
    action="go.php" 
    method="post"
    accept-charset="utf-8"  
    enctype="multipart/form-data"
    onsubmit="return chkSubmit()"
>

通过这种方式,ENTER键按计划工作,但需要确认(通常是第二次按ENTER键)。

我留给读者的任务是,如果用户决定继续使用表单,那么脚本会将用户发送到按ENTER的字段中。

在我的案例中,这个jQuery JavaScript解决了这个问题

jQuery(function() {
            jQuery("form.myform").submit(function(event) {
               event.preventDefault();
               return false;
            });
}