jquery disable form submit on enter

2019-01-01 12:49发布

I have the following javascript in my page which does not seem to be working.

$('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {               
    e.preventDefault();
    return false;
  }
});

I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.

16条回答
孤独寂梦人
2楼-- · 2019-01-01 13:07

Complete Solution in JavaScript for all browsers

The code above and most of the solutions are perfect. However, I think the most liked one "short answer" which is incomplete.

So here's the entire answer. in JavaScript with native Support for IE 7 as well.

var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});

This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

查看更多
梦寄多情
3楼-- · 2019-01-01 13:14

In firefox, when you at input and press enter, it will submit it's upper form. The solution is in the will submit form add this:

<input type="submit" onclick="return false;" style="display:none" />
查看更多
听够珍惜
4楼-- · 2019-01-01 13:14

3 years later and not a single person has answered this question completely.

The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.

Assuming the form has a submit button, whether a <button id="save-form"> or an <input id="save-form" type="submit">, do:

$("#save-form").on("click", function () {
    $.ajax({
        ...
    });
    return false;
});
查看更多
骚的不知所云
5楼-- · 2019-01-01 13:15

Usually form is submitted on Enter when you have focus on input elements.

We can disable Enter key (code 13) on input elements within a form:

$('form input').on('keypress', function(e) {
    return e.which !== 13;
});

DEMO: http://jsfiddle.net/bnx96/325/

查看更多
登录 后发表回答