How to prevent “Enter” from Submitting a form using JavaScript

Posted: 2011/10/31 in Development, HTML / HTML5, JavaScript

I created a really fun form at work that has all kinds of AJAX and HTML5 goodness… but as soon as the user hits ‘enter’, the form is submitted.  Arg.  I want them to click the Submit button ’cause I got more JavaScript fun happening there.  Problem: How to make the Enter button not submit a form?

Good ole StackOverflow.  Posted here, in the comments/answers/whatever, is the following code, redacted:

// Prevent 'enter' button from submitting the form
document.onkeydown = function(evt) {
     var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
     if (keyCode == 13) {
          return false;
     }
}

YAY!  At the time of this post, this works in Firefox 7.0.1, Chrome 15.0.874.102 m, and IE 8 (and IE8 in IE7 mode).

Huge thanks to Stack Overflow user “Varun” of http://www.bmserverhosting.com

Advertisements
Comments
  1. Great, thanks for this. But now I’ve solved the problem, I’m wondering if this is counter-intuitive for the user? What would a UX Designer say about overriding “enter” in this instance? #ux

    • It depends on what makes sense for Enter in the context of the page. In my particular situation, I am preventing form-submission on Enter because I am using AJAX functionality to build the form-itself… Hitting Enter/form-submit when only part of the form is created is, of course, no good. So in this case, when the user hits Enter, I prevent form-submit but also fire an AJAX call that uses the current user-entered data to build-out the rest of the form in a meaningful way.
      For example, if someone fills out a field called “U.S. State” and hits Enter, instead of submitting the form, an AJAX call is made to retrieve an unordered list of cities which are then presented to the user (as another form field). This would NOT be contrary to what the user is expecting.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s