227

How do you prevent an ENTER key press from submitting a form in a web-based application?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
user67722
  • 3,217
  • 5
  • 24
  • 20

30 Answers30

103

[revision 2012, no inline handler, preserve textarea enter handling]

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

Now you can define a keypress handler on the form:
<form [...] onkeypress="return checkEnter(event)">

document.querySelector('form').onkeypress = checkEnter;
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 3
    By the way: you could add a check for the input type (via event source) in the checkEnter function to exclude textarea's. – KooiInc Feb 25 '09 at 23:12
  • 1
    Works. I added this to a single input because I wanted to avoid from submitting the form. It had a button to perform a internal search, and it actually improves usability. – Foxinni Aug 30 '12 at 15:46
  • 1
    One problem with this approach (using this function with an event-handler on the form as a whole), is that it also prevents enters from occurring in textareas that are also in the form (where enters are usually desirable). – Lonnie Best Dec 26 '12 at 07:40
  • 1
    @LonnieBest: thanks for noticing. You *did* read my comment on this answer (see above), did you? Anyway, I revised this rather old answer. – KooiInc Dec 26 '12 at 11:40
  • I noticed this prevents the enter key to be pressed also when focusing on the submit button itself. How can we fix this? – Jonathan Mar 22 '13 at 16:50
  • 1
    @Jonathan: you can attach the handler to single input fields or some div containing a collection of input fields (but not the buttons) in stead of the whole form. – KooiInc Mar 23 '13 at 08:03
58

Here is a jQuery handler that can be used to stop enter submits, and also stop backspace key -> back. The (keyCode: selectorString) pairs in the "keyStop" object are used to match nodes that shouldn't fire their default action.

Remember that the web should be an accessible place, and this is breaking keyboard users' expectations. That said, in my case the web application I am working on doesn't like the back button anyway, so disabling its key shortcut is OK. The "should enter -> submit" discussion is important, but not related to the actual question asked.

Here is the code, up to you to think about accessibility and why you would actually want to do this!

$(function(){
 var keyStop = {
   8: ":not(input:text, textarea, input:file, input:password)", // stop backspace = back
   13: "input:text, input:password", // stop enter = submit 

   end: null
 };
 $(document).bind("keydown", function(event){
  var selector = keyStop[event.which];

  if(selector !== undefined && $(event.target).is(selector)) {
      event.preventDefault(); //stop event
  }
  return true;
 });
});
Pandy
  • 455
  • 4
  • 15
thetoolman
  • 2,144
  • 19
  • 11
  • 12
    In a simplest way: $("#myinput").keydown(function (e) { if(e.which == 13) e.preventDefault(); }); The key is to use "keydown" and event.preventDefault() together. It doesn't work with "keyup". – lepe Jun 09 '10 at 06:45
  • This has the advantage over other solutions which simply block key 13 that the browser's auto-suggest will continue to work properly. – jsalvata Oct 13 '12 at 15:00
  • You are accessing the keyStop array on every keystroke: Not good. I would write if(event.which in keyStop)...instead of accessing an undefined property or better: add a first line like this: if(event.which in keyStop === false) return; – Nadir Nov 01 '20 at 21:33
55

Simply return false from the onsubmit handler

<form onsubmit="return false;">

or if you want a handler in the middle

<script>
var submitHandler = function() {
  // do stuff
  return false;
}
</script>
<form onsubmit="return submitHandler()">
Paul Tarjan
  • 48,968
  • 59
  • 172
  • 213
  • 5
    This seems to be the simplest answer. I tried it on Google Chrome and it works fine. Have you tested this in every browser? – styfle Jan 10 '12 at 02:05
  • 25
    This is not a good idea if you want your form to be submitted by pressing the `submit` button – AliBZ Dec 20 '13 at 17:07
  • 3
    brilliant idea wen we don't need to move from the page – Mo. Aug 13 '14 at 21:49
  • 15
    Doesn't work because the submit button no longer submits the form – paullb Sep 26 '14 at 11:32
  • 47
    @Paul, How did this get 38 upvotes? Stopping `
    ` from getting submitted **at all** is throwing the baby out with the bathwater.
    – Pacerier Mar 01 '15 at 19:44
  • 9
    @Pacerier In the context of an SPA, you'll almost always want to handle form submission manually. Always stopping the browser from submitting a form (and refreshing the page, which restarts the application) is reasonable in this case. – Nathan Friend Mar 30 '15 at 14:59
  • @NathanFriend, In the context of a non-SPA (which **is** the majority), you'll almost always not want to handle form submission manually. – Pacerier Apr 05 '15 at 17:40
  • am I the only one where this is not working? Only time I can prevent submit is if onsubmit only has "return false;" – Don Cheadle Aug 04 '15 at 18:08
  • 1
    follow - up on my above comment -- this only works if there's more than one `` in the form - mentioned by @DanSingerman . Seems like a major limitation... – Don Cheadle Aug 04 '15 at 20:58
  • 1
    @Pacerier It is a good usability practice not to be able to submit the form before client-side validation is passed. Submitting incomplete form makes no sense because server will return it to user and ask to fill it again. This behavior is also implemented in HTML5 validation in all browsers. But if you use JS-driven validation, Paul Tarjan's method is the most reliable and extensible. – Slava Sep 23 '15 at 11:37
  • Genius - a quick fix for what I needed – Gillespie Jun 02 '17 at 17:46
  • Um "How to prevent ENTER keypress to submit a web form?" not "How to prevent a web form from being submitted" – gavin stanley Sep 21 '17 at 03:51
46
//Turn off submit on "Enter" key

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        $("#btnSearch").attr('value');
        //add more buttons here
        return false;
    }
});
mtntrailrunner
  • 761
  • 6
  • 11
  • 5
    This works great. `e.preventDefault()` rather than `return false` will achieve the same end but allow the event to reach handlers in parent elements. The default action (form summission) will still be prevented – willscripted Mar 11 '14 at 14:12
25

You will have to call this function whic will just cancel the default submit behaviour of the form. You can attach it to any input field or event.

function doNothing() {  
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if( keyCode == 13 ) {


    if(!e) var e = window.event;

    e.cancelBubble = true;
    e.returnValue = false;

    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
DanSingerman
  • 36,066
  • 13
  • 81
  • 92
hash
  • 975
  • 2
  • 14
  • 17
  • 2
    e should be an argument and then you should check for the window.event. Also, you should be getting the keycode from the event. Finally, you should return false. – ntownsend Jan 20 '10 at 21:10
  • 11
    Can you please explain where and how to call this function? – mydoghasworms Dec 20 '11 at 05:42
18

The ENTER key merely activates the form's default submit button, which will be the first

<input type="submit" />

the browser finds within the form.

Therefore don't have a submit button, but something like

<input type="button" value="Submit" onclick="submitform()" /> 

EDIT: In response to discussion in comments:

This doesn't work if you have only one text field - but it may be that is the desired behaviour in that case.

The other issue is that this relies on Javascript to submit the form. This may be a problem from an accessibility point of view. This can be solved by writing the <input type='button'/> with javascript, and then put an <input type='submit' /> within a <noscript> tag. The drawback of this approach is that for javascript-disabled browsers you will then have form submissions on ENTER. It is up to the OP to decide what is the desired behaviour in this case.

I know of no way of doing this without invoking javascript at all.

DanSingerman
  • 36,066
  • 13
  • 81
  • 92
  • Weirdly this does not work in Firefox if there is only one field. – DanSingerman Feb 25 '09 at 10:38
  • 6
    Terrible for accessibility? Maybe. However it *does* answer they guy's question, which is what SO is for... Maybe an edit to the answer to point out the accessibility issue is a good compromise? – Neil Barnwell Feb 25 '09 at 12:03
  • 1
    @bobince - maybe the question deserves -1 due to accessibility, but this accurate answer to the question? Don't think so. Also, there are valid uses cases where you want to do this. – DanSingerman Feb 25 '09 at 12:12
  • You don't need to make form impossible to submit without JavaScript, though, eh. That's if it worked though, which it doesn't because browsers will happily submit a form that contains no submit-button. – bobince Feb 25 '09 at 12:19
  • @bobince - Have tested in Safari, Chrome, FF and IE - it works as I describe in all of them. How else can you solve the problem without javascript? – DanSingerman Feb 25 '09 at 12:31
  • 2
    Tested in all of those plus Opera with one text input and one input-button: all still submitted the form on Enter. You obviously need JavaScript to ‘solve’ the Enter issue, but the trick is to do that whilst not making the page completely inoperable where JS is unavailable. – bobince Feb 25 '09 at 13:16
  • @bobince - See my first comment. It works when there is more than one text field. You could put a submit button in a – DanSingerman Feb 25 '09 at 13:28
16

In short answer in pure Javascript is:

<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 only disables the "Enter" keypress action for input type='text'. Visitors can still use "Enter" key all over the website.

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

See my detailed answer for a similar question here

Community
  • 1
  • 1
Tarik
  • 4,270
  • 38
  • 35
  • 4
    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
  • 1
    This is the the most effective and resource-friendly solution. Thank you to @AlexandrePires to! Here is my full working script: http://stackoverflow.com/a/40686327/1589669 – eapo Nov 18 '16 at 21:40
  • 1
    The only working solution; at least in my situation. – hex494D49 Feb 22 '19 at 13:32
16

I've always done it with a keypress handler like the above in the past, but today hit on a simpler solution. The enter key just triggers the first non-disabled submit button on the form, so actually all that's required is to intercept that button trying to submit:

<form>
  <div style="display: none;">
    <input type="submit" name="prevent-enter-submit" onclick="return false;">
  </div>
  <!-- rest of your form markup -->
</form>

That's it. Keypresses will be handled as usual by the browser / fields / etc. If the enter-submit logic is triggered, then the browser will find that hidden submit button and trigger it. And the javascript handler will then prevent the submision.

Halo
  • 1,730
  • 1
  • 8
  • 31
acoulton
  • 538
  • 4
  • 8
9

All the answers I found on this subject, here or in other posts has one drawback and that is it prevents the actual change trigger on the form element as well. So if you run these solutions onchange event is not triggered as well. To overcome this problem I modified these codes and developed the following code for myself. I hope this becomes useful for others. I gave a class to my form "prevent_auto_submit" and added the following JavaScript:

$(document).ready(function() 
{
    $('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event) 
    { 
        if (event.keyCode == 13)
        {
            event.preventDefault();
            $(this).trigger("change");
        }
    });
});
Mahdi Mehrizi
  • 219
  • 3
  • 8
5

I've spent some time making this cross browser for IE8,9,10, Opera 9+, Firefox 23, Safari (PC) and Safari(MAC)

JSFiddle Example: http://jsfiddle.net/greatbigmassive/ZyeHe/

Base code - Call this function via "onkeypress" attached to your form and pass "window.event" into it.

function stopEnterSubmitting(e) {
    if (e.keyCode == 13) {
        var src = e.srcElement || e.target;
        if (src.tagName.toLowerCase() != "textarea") {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        }
    }
}
Adam
  • 359
  • 3
  • 5
4

Preventing "ENTER" to submit form may inconvenience some of your users. So it would be better if you follow the procedure below:

Write the 'onSubmit' event in your form tag:

<form name="formname" id="formId" onSubmit="return testSubmit()" ...>
 ....
 ....
 ....
</form>

write Javascript function as follows:

function testSubmit(){
  if(jQuery("#formId").valid())
      {
        return true;
      }
       return false;

     } 

     (OR)

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.keyCode == 13) {
               event.preventDefault();
               return false;
              }
           });
         });

thanks.

venky
  • 400
  • 1
  • 6
  • 19
4
stopSubmitOnEnter (e) {
  var eve = e || window.event;
  var keycode = eve.keyCode || eve.which || eve.charCode;

  if (keycode == 13) {
    eve.cancelBubble = true;
    eve.returnValue = false;

    if (eve.stopPropagation) {   
      eve.stopPropagation();
      eve.preventDefault();
    }

    return false;
  }
}

Then on your form:

<form id="foo" onkeypress="stopSubmitOnEnter(e);">

Though, it would be better if you didn't use obtrusive JavaScript.

ntownsend
  • 7,462
  • 9
  • 38
  • 35
  • I like this version because it's more readable than the one by @hash. One problem though, you should return false within the "if(keycode == 13)" block. As you have it, this function prevents any keyboard input in the field. Also @hash's version includes e.keyCode, e.which, and e.charCode... not sure if e.charCode is important but I put it in there anyway: "var keycode = eve.keyCode || eve.which || eve.charCode;". – Jack Senechal Feb 17 '11 at 18:00
  • Thanks, Jack. I edited the answer to check for `charCode`. I also moved the `return false` inside the if-block. Good catch. – ntownsend Feb 17 '11 at 18:36
4

To prevent form submit when pressing enter in a textarea or input field, check the submit event to find what type of element sent the event.

Example 1

HTML

<button type="submit" form="my-form">Submit</button>
<form id="my-form">
...
</form>

jQuery

$(document).on('submit', 'form', function(e) {
    if (e.delegateTarget.activeElement.type!=="submit") {
        e.preventDefault();
    }
});

A better solution is if you don't have a submit button and you fire the event with a normal button. It is better because in the first examlple 2 submit events are fired, but in the second example only 1 submit event is fired.

Example 2

HTML

<button type="button" onclick="$('#my-form').submit();">Submit</button>
<form id="my-form">
...
</form>

jQuery

$(document).on('submit', 'form', function(e) {
    if (e.delegateTarget.activeElement.localName!=="button") {
        e.preventDefault();
    }
});
  • This solution does not work in Safari (at least the versions I tested) because for some reason Safari does not consider the `activeElement` to be submit, even if you click on it. Thus, on Safari, it would prevent the form from being submitted at all. – cazort Nov 21 '21 at 18:40
3

You will find this more simple and useful :D

$(document).on('submit', 'form', function(e){
    /* on form submit find the trigger */
    if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
        /* if the trigger is not between selectors list, return super false */
        e.preventDefault();
        return false;
    } 
});
Mike O.O.
  • 119
  • 1
  • 4
3

In my case, this jQuery JavaScript solved the problem

jQuery(function() {
            jQuery("form.myform").submit(function(event) {
               event.preventDefault();
               return false;
            });
}
Kirby
  • 15,127
  • 10
  • 89
  • 104
  • Awesome, thanks @Kirby! Being that the enter key is now disabled in the form, how might you then enable the enter key for all `` fields within the form? – Ian Campbell Aug 09 '13 at 19:40
2

Add this tag to your form - onsubmit="return false;" Then you can only submit your form with some JavaScript function.

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
Rajveer
  • 37
  • 1
  • The OP (like most of who've been bitten by this browser feature) probably wanted to still allow submitting with a mouse click, which this (unfortunately often recommended) method would also disable. There is no nice way to solve this, but e.g. the answer above (at this moment), from Adam, does a better job at it. – Sz. Dec 22 '13 at 23:00
2

Please check this article How to prevent ENTER keypress to submit a web form?

$(“.pc_prevent_submit”).ready(function() {
  $(window).keydown(function(event) {
    if (event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class=”pc_prevent_submit” action=”” method=”post”>
  <input type=”text” name=”username”>
  <input type=”password” name=”userpassword”>
  <input type=”submit” value=”submit”>
</form>
halfzebra
  • 6,771
  • 4
  • 32
  • 47
2

How about:

<asp:Button ID="button" UseSubmitBehavior="false"/>
pdiddy
  • 45
  • 1
1

This link provides a solution that has worked for me in Chrome, FF, and IE9 plus the emulator for IE7 and 8 that comes with IE9's developer tool (F12).

http://webcheatsheet.com/javascript/disable_enter_key.php

Miaka
  • 63
  • 5
  • In case the link is broken, add this code to the header area of your page. `` – Miaka Apr 25 '12 at 04:04
1

Another approach is to append the submit input button to the form only when it is supposed to be submited and replace it by a simple div during the form filling

Nicolas Manzini
  • 8,379
  • 6
  • 63
  • 81
1

Simply add this attribute to your FORM tag:

onsubmit="return gbCanSubmit;"

Then, in your SCRIPT tag, add this:

var gbCanSubmit = false;

Then, when you make a button or for any other reason (like in a function) you finally permit a submit, simply flip the global boolean and do a .submit() call, similar to this example:

function submitClick(){

  // error handler code goes here and return false if bad data

  // okay, proceed...
  gbCanSubmit = true;
  $('#myform').submit(); // jQuery example

}
Volomike
  • 23,743
  • 21
  • 113
  • 209
1

I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.

gavin stanley
  • 1,082
  • 2
  • 13
  • 28
1

How about:

<script>
function isok(e) {
  var name = e.explicitOriginalTarget.name;
  if (name == "button") {
    return true
  }
  return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>

And just name your button right and it will still submit, but text fields i.e. the explicitOriginalTarget when you hit return in one, will not have the right name.

Andrew Arrow
  • 4,248
  • 9
  • 53
  • 80
1

You can trap the keydown on a form in javascript and prevent the even bubbling, I think. ENTER on a webpage basically just submits the form that the currently selected control is placed in.

Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220
  • depends on a control tho ;) in a textarea it just moves to next line. So, catching all 'enter' keypress events is not a good idea. – kender Feb 25 '09 at 10:13
  • Possibly, but in that case would the form have a keydown event anyway? – Neil Barnwell Feb 25 '09 at 12:01
  • You would do it directly on all input-type-text and other similar controls. It's a bit of a pain and not really worth bothering with in most cases, but if you have to... – bobince Feb 25 '09 at 13:18
1

Here's how I'd do it:

window.addEventListener('keydown', function(event)
{
    if (event.key === "Enter" && event.target.tagName !== 'TEXTAREA')
    {
        if(event.target.type !== 'submit')
        {
            event.preventDefault();
            return false;
        }
    }
});
Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
  • this will break textarea -> you won't be able to enter new lines – Liero Jun 17 '21 at 12:35
  • @Liero I've modified my answer to make exception for ` – Lonnie Best Jun 17 '21 at 15:07
  • What if there is a button, e.g. in a bootstrap's input group, or a third party control? It should work with enter. What I want to say is that cancelling KeyPress event is not a good idea – Liero Jun 17 '21 at 15:24
  • @Liero Well, the question didn't mention any need to accommodate 3rd party controls. The essence was just preventing `enter` from submitting the form. What do you think the most proper way to accomplish that is? If available, I think the best way would be if the `
    ` element had an attribute for preventing this default behavior on all sub-elements, while also having the granularity to set an attribute on each sub-element to override the form-level attribute if desired. I'm not aware of such attributes if they exist. What do you think is best?
    – Lonnie Best Jun 17 '21 at 16:02
  • 1
    It's the submit button that causes the submit on enter. Browser triggers click event on the button when user pressed enter key. So rather than cancelling the keypress you can capture the click event and cancel it. – Liero Jun 17 '21 at 17:51
  • @Liero I didn't know a click event was involved. If that's the way it works, then I agree. – Lonnie Best Jun 18 '21 at 16:08
1

If none of those answers are working for you, try this. Add a submit button before the one that actually submits the form and just do nothing with the event.

HTML

<!-- The following button is meant to do nothing. This button will catch the "enter" key press and stop it's propagation. -->
<button type="submit" id="EnterKeyIntercepter" style="cursor: auto; outline: transparent;"></button>

JavaScript

$('#EnterKeyIntercepter').click((event) => {
    event.preventDefault(); //The buck stops here.
    /*If you don't know what this if statement does, just delete it.*/
    if (process.env.NODE_ENV !== 'production') {
        console.log("The enter key was pressed and captured by the mighty Enter Key Inceptor (⌐■_■)");
    }
});
Onosa
  • 1,275
  • 1
  • 12
  • 28
0

This worked for me.
onkeydown="return !(event.keyCode==13)"

    <form id="form1" runat="server" onkeydown="return !(event.keyCode==13)">

   </form>
garish
  • 637
  • 12
  • 14
0

<input onkeydown="onInputKeyDown(event)" />

or in Angular

<input (keydown)="onInputKeyDown($event)" />

  /**
   * Closes the on-screen keyboard on "enter".
   * Cursor leaves the input element.
   */
  onInputKeyDown(e: KeyboardEvent|any) {
    if (e.key === 'Enter') {
      // Leave the input element
      e.target.blur();
      // Prevent to submit form (it was default action on Enter)
      e.preventDefault();
    }
  }
Martin
  • 696
  • 6
  • 7
-1

put into javascript external file

   (function ($) {
 $(window).keydown(function (event) {  

    if (event.keyCode == 13) {

        return false;
    }
});

 })(jQuery);

or somewhere inside body tag

<script>


$(document).ready(function() {
    $(window).keydown(function(event) {
        alert(1);

        if(event.keyCode == 13) {

            return false;
        }
    });
});

</script>
topC
  • 7
  • 2
-1

I had the same problem (forms with tons of text fields and unskilled users).

I solved it in this way:

function chkSubmit() {
    if (window.confirm('Do you want to store the data?')) {
        return true;
    } else {
        // some code to focus on a specific field
        return false;
    }
}

using this in the HTML code:

<form
    action="go.php" 
    method="post"
    accept-charset="utf-8"  
    enctype="multipart/form-data"
    onsubmit="return chkSubmit()"
>

In this way the ENTER key works as planned, but a confirmation (a second ENTER tap, usually) is required.

I leave to the readers the quest for a script sending the user in the field where he pressed ENTER if he decide to stay on the form.

Marco Bernardini
  • 695
  • 6
  • 17