[javascript] jquery disable form submit on enter

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.

This question is related to javascript jquery forms form-submit

The answer is


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.


Even shorter:

$('myform').submit(function() {
  return false;
});

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

I heard which is not recommended, so change Best rated answer to this.

$('#formid').on('keyup keypress', function(e) {
  if (e.key === 'Enter') { 
    e.preventDefault();
    return false;
  }
});

ref. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which


When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.

<script>
            $(document).ready(function () {
                $(window).keydown(function(event){
                    if(event.keyCode == 13) {
                        e.preventDefault(); // Disable the " Entry " key
                        return false;               
                    }
                });
            });
        </script>

if you just want to disable submit on enter and submit button too use form's onsubmit event

<form onsubmit="return false;">

You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.


The simple way is to change type of button to button - in html and then add event in js...

Change from this:

<form id="myForm">
   <button type="submit">Submit</button>
</form>

To

<form id="myForm">
   <button type="button" id="btnSubmit">Submit</button>
</form>

And in js or jquery add:

$("#btnSubmit").click(function () {
    $('#myForm').submit();
});

You can do this perfectly in pure Javascript, simple and no library required. Here it is my detailed answer for a similar topic: Disabling enter key for form

In short, here is the code:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

This code is to prevent "Enter" key for input type='text' only. (Because the visitor might need to hit enter across the page) If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...


$('form').keyup(function(e) {
  return e.which !== 13  
});

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

which docs.


Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :

var keyCode = e.keyCode || e.which;
if (keyCode === 13 && !$(document.activeElement).is('textarea')) {
  e.preventDefault();
  return false;
}

How about this:

$(":submit").closest("form").submit(function(){
    $(':submit').attr('disabled', 'disabled');
});

This should disable all forms with submit buttons in your app.


I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!

$j(':input:not(textarea)').keydown(function(event){
    var kc = event.witch || event.keyCode;
    if(kc == 13){
    event.preventDefault();
        $j(this).closest('form').attr('data-oldaction', function(){
            return $(this).attr('action');
        }).attr('action', 'javascript:;');

        alert('some_text_if_you_want');

        $j(this).closest('form').attr('action', function(){
            return $(this).attr('data-oldaction');
        });
        return false;
    }
});

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" />

The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.

<script type="text/javascript">
        function stopRKey(evt) {
          var evt = (evt) ? evt : ((event) ? event : null);
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
          if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio") || (node.type=="checkbox")) )  {return false;}
        }

        document.onkeypress = stopRKey;
</script> 

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/


$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.


The overkill of having to capture and test every keystroke for the ENTER key really bugs me, so my solution relies on the following browser behavior:

Pressing ENTER will trigger a click event on the submit button (tested in IE11, Chrome 38, FF 31) ** (ref: http://mattsnider.com/how-forms-submit-when-pressing-enter/ )

So my solution is to remove the standard submit button (i.e. <input type="submit">) so that the above behavior fails because there's no submit button to magically click when ENTER is pressed. Instead, I use a jQuery click handler on a regular button to submit the form via jQuery's .submit() method.

<form id="myform" method="post">
  <input name="fav_color" type="text">
  <input name="fav_color_2" type="text">
<button type="button" id="form-button-submit">DO IT!</button>
</form>

<script>
 $('#form-button-submit').click(function(){
    $('#myform').submit();
  });
</script>

Demo: http://codepen.io/anon/pen/fxeyv?editors=101

** this behavior is not applicable if the form has only 1 input field and that field is a 'text' input; in this case the form will be submitted upon ENTER key even if no submit button is present in the HTML markup (e.g. a search field). This has been standard browser behavior since the 90s.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to form-submit

Setting onSubmit in React.js Jquery function BEFORE form submission How to locate and insert a value in a text box (input) using Python Selenium? Submit form without reloading page How to check if text fields are empty on form submit using jQuery? Submitting HTML form using Jquery AJAX Serializing and submitting a form with jQuery and PHP How do I use an image as a submit button? How to pass value from <option><select> to form action validation of input text field in html using javascript