235

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.

zessx
  • 68,042
  • 28
  • 135
  • 158
Adam Levitt
  • 10,316
  • 26
  • 84
  • 145

21 Answers21

475

If keyCode is not caught, catch which:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

EDIT: missed it, it's better to use keyup instead of keypress

EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.

EDIT 3: Changed bind() to on()

Aamir Afridi
  • 6,364
  • 3
  • 42
  • 42
zessx
  • 68,042
  • 28
  • 135
  • 158
  • 16
    jQuery normalises it to `e.which`, so you don't need to test for `e.keyCode`, but +1 for the most likely cause of this issue. – Bojangles Jun 27 '12 at 22:30
  • 2
    @zessx This doesn't seem to work if keyup is used though. See http://jsfiddle.net/bD9jN/1/ – tundoopani Apr 05 '13 at 19:39
  • why keyup is better than keypress? I'm in situation when I've had to register to both to stop the form submitting. – Danubian Sailor Apr 19 '13 at 13:15
  • `ENTER` is a key, not a char. Depending of your browser, you can have some issues as `keypress` is only fired when a char is typed (generally with webkit). Using `keyup` assure you to catch any kind of key, like a-z, enter, arrows... – zessx Apr 19 '13 at 14:00
  • 2
    This (and the fiddle) don't seem to work any longer (FF21) :( – s.krueger Jun 12 '13 at 07:42
  • 1
    Controverse to the EDIT of this answer: I had an issue w/ 'keyup'. It seemed that the submit was already done before the key came up and the event was triggered. Thus keypress works for me. – Dirk Schumacher Feb 25 '15 at 08:52
  • 4
    Do you need `return false;` for this? `e.preventDefault();` seems enougth – chromigo Jul 05 '16 at 07:17
  • 13
    Important! This solution block breaks in textarea. – German Khokhlov Sep 27 '16 at 13:49
  • 1
    This is not working any more in chrome, does any one has some better solution – Krushna Oct 05 '16 at 08:14
  • 4
    The problem is if I have in the same form a textbox, now I can't add an enter(to make a new line) in textbox. – Tikky Mar 02 '17 at 12:44
  • Good code example, but my opinion is best use `BIND` (depend a version jquery) and key events jquery-ui (Look: https://api.jqueryui.com/jQuery.ui.keyCode/) enjoy ;-) ... thanks zessx – KingRider Apr 28 '17 at 13:09
  • 6
    `keyCode === 13 && !$(e.target).is('textarea')` – teran Dec 07 '17 at 10:11
  • This submit normally happens on enter within `input` & `textarea` so adding `if(keyCode === 13 && event.target.nodeName === 'INPUT' && event.target.nodeName === 'TEXTAREA')` should do the trick. – MattClaff Mar 28 '18 at 10:34
  • this safe my day. Actually i'm using it because my input have to do something before submit press, so to make sure that work, i have to disable my enter key on that form. Thanks in advance :) – Mauliardiwinoto Sep 05 '21 at 02:42
66

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/

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • iOS Go button was my problem on a custom autocomplete input field. This solved it. – Dylan Valade Sep 27 '13 at 12:47
  • 12
    This prevents the **enter** key from being used in `textareas` within the same form. Using `$("form input")` instead of `$("form :input")` seems to fix it. DEMO: http://jsfiddle.net/bnx96/279/ – shaneparsons Apr 27 '15 at 17:43
43

Even shorter:

$('myform').submit(function() {
  return false;
});
user1017926
  • 663
  • 6
  • 5
  • 35
    But this will prevent user click as well? – haibuihoang Oct 10 '14 at 05:17
  • 5
    @haibuihoang Yes this will disable form submission. – Tom Nov 19 '14 at 21:50
  • 8
    You should use `function(e) {e.preventDefault();}` as return values in event handlers are deprecated: http://stackoverflow.com/a/20045473/601386 – flu Jun 04 '15 at 15:39
  • 6
    @user1111929 This does work great but it shouldn't be the top answer because the question asked only about `Enter` and not about disabling form submission by the `Submit` button. – daveslab Aug 20 '15 at 13:35
  • A common situation in which you may want to preserve the form submission, but disable submission on pressing the 'enter' key, is if you decide to use a jQuery `onClick` event to validate a form, and still submit using jQuery. In other words, there are cases where you only want to submit via javascript/jQuery. While you can still use AJAX with this solution, it disables the base functionality of the `submit` method. – JRad the Bad Jan 19 '17 at 16:44
  • In my case I wanted to allow the user to submit the form exactly once by pressing Enter. I used a method very similar to this one, but instead I set a "form_enabled" variable to false after the first form submission, then I checked that variable to determine whether to return false on form submission. – John Langford Feb 01 '18 at 18:19
24
$('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.

gdoron
  • 147,333
  • 58
  • 291
  • 367
17
$(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.

Buzogany Laszlo
  • 921
  • 11
  • 19
12

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;
}
jean-baptiste
  • 674
  • 7
  • 18
10

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.

Perica Zivkovic
  • 2,610
  • 24
  • 32
10

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();
});
Zvi Redler
  • 1,708
  • 1
  • 18
  • 29
9

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.

Costa
  • 4,851
  • 33
  • 30
  • I added an invisible input box to counter "form will be submitted upon ENTER key" caused by "the form has only 1 input field and that field is a 'text' input". – Luo Jiong Hui Dec 09 '19 at 19:23
5

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...

Community
  • 1
  • 1
Tarik
  • 4,270
  • 38
  • 35
  • 2
    Actually it should be `e.target.nodeName === 'INPUT' && e.target.type !== 'textarea'`. With the specified code it will allow to submit forms if a radio or checkbox are focused. – afnpires May 18 '16 at 13:50
3

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

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" />
wade
  • 21
  • 2
2
$('#FormID').on('keyup keypress', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode === 13) {
            e.preventDefault();
            return false;
        }
    });
Tayyeb
  • 127
  • 7
1

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> 
Radish
  • 157
  • 1
  • 1
  • 9
1

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;
});
derekm
  • 429
  • 1
  • 4
  • 12
1

Here is a simple JavaScript solution without using different variations of handling keydown or keypress events:

document.forms[0].addEventListener('submit', function(e) {
    if(document.activeElement.getAttribute('type') !== 'submit') {
        e.preventDefault();
    }
});

Submitting the form will occur only when the active element on your page is the submit button. So you can submit the form by clicking on your submit button or by pressing the ENTER key when the submit button has focus.

ge333
  • 303
  • 1
  • 4
  • 7
0

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

KABA
  • 313
  • 3
  • 8
0

Use EnterByTab() for elimnated Enter->Submit form

function EnterByTab(){  //only in form
  $('body').on('keydown', 'input, select, radio', function(e) {
    if (e.key === "Enter") {
      var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
      focusable=form.find(':input,a,select,button,textarea').filter(':visible');
      next = focusable.eq(focusable.index(this)+1);
      var i=1;
      while (next.attr('readonly') || next.prop("type")=="radio") {
        i++;
        next = focusable.eq(focusable.index(this)+i);
      }
      if (next.length) {
        next.focus();
      } else {
        form.submit(); //original behavior
      }
      return false;
    }
  });
}
Jan Tungli
  • 35
  • 6
-2

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>
Yvan1263
  • 80
  • 2
  • 14
-4

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.

Community
  • 1
  • 1
Tarandeep Singh
  • 1,322
  • 16
  • 16
  • 8
    This also prevents the form from being submitted if you click the "Submit" button. – Mario Werner Jun 30 '17 at 09:24
  • @MarioWerner if you look at the question, it says specifically to avoid form submit. and this is the purpose of this code. so the user does not want the form submit for a single form which is why this should work. Yes this should not work on form submit, since user want to do stuff on any kind of submit action. – Tarandeep Singh Oct 07 '20 at 15:46
  • @TarandeepSingh No, the title and the question say "disable form submit *on enter*" – Mario Werner Oct 08 '20 at 19:02
-10

How about this:

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

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