Javascript 表单提交 keyCode == "enter" (13)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8803376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Form submit on keyCode == "enter" (13)
提问by sorin
I need to submit the content of a form when I press the Enterkey, but only if the form has no error message. I built up the following function:
当我按下Enter键时,我需要提交表单的内容,但前提是表单没有错误消息。我建立了以下功能:
$(targetFormID).submit(function (e) {
var mess = error_m(targetDiv);
if (e.keyCode == 13 && mess.length > 0) {
e.preventDefault();
e.stopPropagation();
}
if (mess.length == 0 && e.keyCode == 13) $(targetFormID).submit();
});
In this function the mess variable is getting the error message returned by function error_m
, the rest is simple code condtion but it doesn't work.
在这个函数中, mess 变量正在获取 function 返回的错误消息error_m
,其余的是简单的代码条件,但它不起作用。
Need some help with this!!
需要一些帮助!
回答by Tim Down
Submitting the form when the Enterkey is pressed is default browser behaviour. Don't mess with it. Just validate the form in the submit
event.
Enter按下键时提交表单是浏览器的默认行为。不要惹它。只需验证submit
事件中的表单。
$(targetFormID).submit(function (e) {
var mess = error_m(targetDiv);
if (mess.length > 0) {
e.preventDefault();
}
});
One other possible problem: what is targetFormID
? If it's actually a string containing an element ID, you'll need
另一个可能的问题:什么是targetFormID
?如果它实际上是一个包含元素 ID 的字符串,则需要
$("#" + targetFormID).submit(/* Same function as above */);
If it's a reference to the form element then $(targetFormID)
is fine but your variable is misleadingly named.
如果它是对表单元素的引用,那么$(targetFormID)
很好,但您的变量名称具有误导性。