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


当前回答

为了防止在文本区域或输入字段中按enter键时提交表单,请检查submit事件以查找发送该事件的元素类型。

示例1

HTML

<button type="submit" form="my-form">Submit</button>
<form id="my-form">
...
</form>

jQuery

$(document).on('submit', 'form', function(e) {
    if (e.delegateTarget.activeElement.type!=="submit") {
        e.preventDefault();
    }
});

更好的解决方案是,如果没有提交按钮,而使用普通按钮触发事件。这是因为在第一个示例中触发了2个提交事件,而在第二个示例中只触发了1个提交事件。

示例2

HTML

<button type="button" onclick="$('#my-form').submit();">Submit</button>
<form id="my-form">
...
</form>

jQuery

$(document).on('submit', 'form', function(e) {
    if (e.delegateTarget.activeElement.localName!=="button") {
        e.preventDefault();
    }
});

其他回答

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

我是这样解决的:

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的字段中。

请查看这篇文章如何防止按ENTER键提交web表单?

$(“.pc_prevent_submit”)时函数(){ 美元(窗口).keydown(函数(事件){ 如果事件。keyCode == 13) { event.preventDefault (); 返回错误; } }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <form class= " pc_prevent_submit " action= " " method= " post " > <input type= " text " name= " username " > <input type= " password " name= " userpassword " > <input type= " submit " value= " submit " > > < /形式

我认为,你可以在javascript的表单中捕获键下,防止冒泡。网页上的ENTER基本上只是提交当前所选控件所在的表单。

I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.

[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;