最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Form submit on keyCode == "enter" (13) - Stack Overflow

programmeradmin3浏览0评论

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

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.

Need some help with this!!

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

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.

Need some help with this!!

Share Improve this question edited Aug 14, 2013 at 19:40 Fabián 5751 gold badge7 silver badges30 bronze badges asked Jan 10, 2012 at 12:36 sorinsorin 4611 gold badge5 silver badges14 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

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

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 */);

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

发布评论

评论列表(0)

  1. 暂无评论