如何防止在基于web的应用程序中按ENTER键提交表单?
当前回答
将这个标签添加到你的表单- onsubmit="return false;" 然后只能使用JavaScript函数提交表单。
其他回答
这个链接提供了一个在Chrome、FF和IE9以及IE7和ie8的模拟器(IE9的开发者工具(F12)中为我工作过的解决方案。
http://webcheatsheet.com/javascript/disable_enter_key.php
//Turn off submit on "Enter" key
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
$("#btnSearch").attr('value');
//add more buttons here
return false;
}
});
另一种方法是仅在表单应该提交时才将提交输入按钮附加到表单,并在表单填充期间将其替换为简单的div
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.
stopSubmitOnEnter (e) {
var eve = e || window.event;
var keycode = eve.keyCode || eve.which || eve.charCode;
if (keycode == 13) {
eve.cancelBubble = true;
eve.returnValue = false;
if (eve.stopPropagation) {
eve.stopPropagation();
eve.preventDefault();
}
return false;
}
}
然后在表格上:
<form id="foo" onkeypress="stopSubmitOnEnter(e);">
不过,如果不使用突兀的JavaScript会更好。