Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing "Enter" from submitting form, but allow it on textarea fields (jQuery) [duplicate]

$(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".

like image 949
jeffkee Avatar asked Mar 12 '12 17:03

jeffkee


People also ask

How do you prevent form submit on Enter in jQuery?

Disallow enter key anywhere$(document). on("keydown", "form", function(event) { return event. key != "Enter"; });

How do I stop a form submission on enter?

To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.

How do you disable the Enter key of an input textbox?

Disabling enter key for the form keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } }); If you want to prevent Enter key for a specific textbox then use inline JS code.

How do I stop Enter key press to submit a web form?

What ever the reason, if you want to prevent the form submission on pressing Enter key, you can write the following function in javascript: $(document). ready(function() { $(window). keydown(function(event){ if(event.


1 Answers

You may try this

$(document).ready(function(){
    $(window).keydown(function(event){
        if(event.keyCode == 13 && event.target.nodeName!='TEXTAREA')
        {
          event.preventDefault();
          return false;
        }
    });
});

A fiddle is here.

like image 77
The Alpha Avatar answered Sep 26 '22 02:09

The Alpha