如何防止在基于web的应用程序中按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.
其他回答
我认为,你可以在javascript的表单中捕获键下,防止冒泡。网页上的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 " > > < /形式
我花了一些时间制作这款跨浏览器,适用于IE8、9、10、Opera 9+、Firefox 23、Safari(PC)和Safari(MAC)
示例:http://jsfiddle.net/greatbigmassive/ZyeHe/
基本代码-通过“onkeypress”附加到您的窗体和传递窗口调用此函数。事件”。
function stopEnterSubmitting(e) {
if (e.keyCode == 13) {
var src = e.srcElement || e.target;
if (src.tagName.toLowerCase() != "textarea") {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
}
我也遇到了同样的问题(表单包含大量的文本字段和不熟练的用户)。
我是这样解决的:
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键仅仅激活表单的默认提交按钮,这将是第一个
<input type="submit" />
浏览器在表单中查找。
所以不要有提交按钮,而是类似的东西
<input type="button" value="Submit" onclick="submitform()" />
编辑:回应评论中的讨论:
如果只有一个文本字段,这就行不通了——但在这种情况下,这可能是理想的行为。
另一个问题是,这依赖于Javascript来提交表单。从可访问性的角度来看,这可能是一个问题。这可以通过用javascript编写<input type='button'/>来解决,然后在<noscript>标签中放入<input type='submit' />。这种方法的缺点是,对于禁用javascript的浏览器,您将在ENTER时提交表单。在这种情况下,由OP决定期望的行为是什么。
我知道没有办法做到这一点而不调用javascript。