如何防止在基于web的应用程序中按ENTER键提交表单?
当前回答
只需从onsubmit处理程序返回false
<form onsubmit="return false;">
或者如果你想要一个中间的处理程序
<script>
var submitHandler = function() {
// do stuff
return false;
}
</script>
<form onsubmit="return submitHandler()">
其他回答
防止“ENTER”提交表单可能会给一些用户带来不便。所以你最好按照下面的步骤来做:
在你的表单标签中写入'onSubmit'事件:
<form name="formname" id="formId" onSubmit="return testSubmit()" ...>
....
....
....
</form>
编写Javascript函数如下:
function testSubmit(){
if(jQuery("#formId").valid())
{
return true;
}
return false;
}
(OR)
不管是什么原因,如果你想阻止按Enter键提交表单,你可以用javascript写下面的函数:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
谢谢。
在我的案例中,这个jQuery JavaScript解决了这个问题
jQuery(function() {
jQuery("form.myform").submit(function(event) {
event.preventDefault();
return false;
});
}
以下是我的做法:
window.addEventListener('keydown', function(event)
{
if (event.key === "Enter" && event.target.tagName !== 'TEXTAREA')
{
if(event.target.type !== 'submit')
{
event.preventDefault();
return false;
}
}
});
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.
我花了一些时间制作这款跨浏览器,适用于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;
}
}
}
}