在keyCode =="enter"上提交表单(13)

问题描述:

当我按下 Enter 键时,我需要提交表单的内容,但前提是该表单没有错误消息.我建立了以下功能:

I need to submit the content of a form when I press the Enter key, but only if the form has no error message. I built up the following function:

$(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();
}); 

在此函数中,mess变量获取函数error_m返回的错误消息,其余的只是简单的代码处理,但无效.

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.

需要一些帮助!

当按下 Enter 键时提交表单是默认的浏览器行为.不要惹它.只需在submit事件中验证表单即可.

Submitting the form when the Enter key is pressed is default browser behaviour. Don't mess with it. Just validate the form in the submit event.

$(targetFormID).submit(function (e) {
    var mess = error_m(targetDiv);
    if (mess.length > 0) {
        e.preventDefault();
    }
});

另一个可能的问题:什么是targetFormID?如果实际上是包含元素ID的字符串,则需要

One other possible problem: what is targetFormID? If it's actually a string containing an element ID, you'll need

$("#" + targetFormID).submit(/* Same function as above */);

如果它是对form元素的引用,则$(targetFormID)很好,但是您的变量的名称具有误导性.

If it's a reference to the form element then $(targetFormID) is fine but your variable is misleadingly named.