[英]Hitting enter in any textbox in chrome triggers the form submit, even when there is no submit button
I am building a site which uses jQUery validation plugin and want things validated before submitting the form. 我正在建立一个使用jQUery验证插件的站点,并希望在提交表单之前先对事物进行验证。 My code looks like follows
我的代码如下
<form>
<input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">
function validateAndSubmit(){
//do some validation and then submit
}
</script>
In Firefox, this works perfectly. 在Firefox中,这非常有效。 In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either.
在Chrome浏览器中,当我在页面上的任意位置点击Enter时,都会触发表单提交并且验证也不起作用。 Is there something to avoid this ?
有什么可以避免的吗? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?
如果没有提交按钮,当我们按下Enter键时,浏览器是否应该不提交表单?
use this syntax: 使用以下语法:
<form onsubmit="return validateAndSubmit()">
...
if you need to catch the return-key maybe you can handle it by binding an keydown event to the input and perform some action on keyCode #13 如果您需要捕获返回键,也许可以通过将keydown事件绑定到输入并对keyCode#13执行一些操作来处理它
Try this method: 试试这个方法:
<form onsubmit="return validateAndSubmit(this);">
<input type="submit" value="Submit the Form"/>
</form>
<script language="javascript">
function validateAndSubmit(form_obj){
if(some_variable == 'correct_value') {
form_obj.submit();
return true;
} else {
alert('Wrong value');
return false;
}
//do some validation and then submit
}
</script>
I'm not sure if there's a standard regarding this or not. 我不确定是否有与此相关的标准。
Regardless, you can save yourself the trouble altogether by simply adopting a stronger strategy: implement the validation as an onsubmit
action on the form, rather than an onclick
action for the button. 无论如何,您只需采取一种更强大的策略就可以完全避免麻烦:将验证实现为对表单的
onsubmit
操作,而不是对按钮的onclick
操作。 I almost never use buttons in forms; 我几乎从不使用表格中的按钮。 having to do so for yours would only throw me off, and that's not good for users.
不必为您自己做,只会让我失望,这对用户不利。
So anyway. 所以无论如何。 Form
onsubmit
is the way to go. 表单
onsubmit
是必经之路。 And I'd appreciate it if you used unobtrusive Javascript instead of the HTML attributes :) 如果您使用兼容的Javascript而不是HTML属性,我将不胜感激:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.