Preventing “Enter” from submitting form, but allow

2019-02-21 11:13发布

This question already has an answer here:

$(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });

The above is the code I got which effectively kills the "enter" key as a form submitter throughout the system, which is exactly what I want. However, the enter key is also disabled on textarea tags - which the users should be able to hit enter on in order to go to the next rows. So is there a way to modify the above code to detect IF the enter is coming from within a textarea tag, it doesn't run the event.preventDefault(); line?

I have so many forms throughout the site - having to configure them individually would be a nightmare, and probably doesn't make sense - there's gotta be a universal way. The above code runs on every single page of the site to prevent accidental submits by hitting "enter".

7条回答
▲ chillily
2楼-- · 2019-02-21 12:03

I have found this works best. Especially if you want to use enter key behaviors in other elements just not to send the form back. I am just expanding on 3nigma's answer.

 $("form").keypress(function (event) {
            if (event.keyCode == 13 && ($(event.target)[0]!=$("textarea")[0])) {
                return false;
            }
        });
查看更多
登录 后发表回答