How to Stop a Form From Submitting on Enter

Posted by: twmeier

Tagged in: Javascript , HTML

I came across a problem this week, with a form that submitted when a user hit the "enter" or "return" button even though the submit button had an onclick function that should have kept the form from submitting. The problem only manifested itself on Google's Chrome browser.

I found the following JavaScript code to keep this from happening:

// Disables enter button from submitting the form
    var nav = window.Event ? true : false;
    if (nav) {
       window.captureEvents(Event.KEYDOWN);
       window.onkeydown = NetscapeEventHandler_KeyDown;
    } else {
       document.onkeydown = MicrosoftEventHandler_KeyDown;
    }
    function NetscapeEventHandler_KeyDown(e) {
      if (e.which == 13 && e.target.type != 'textarea' && e.target.type != 'submit') { return false; }
      return true;
    }
    function MicrosoftEventHandler_KeyDown() {
      if (event.keyCode == 13 && event.srcElement.type != 'textarea' && event.srcElement.type != 'submit')
        return false;
      return true;
    }

 
This worked great and fixed my problem (and hopefully your too).

Comments (2)add comment

Ceezey said:

0
Fantastic!
Worked like a charm!
 
May 06, 2009 | url
Votes: +0

Karl said:

0
Cool but...
doesn't work with Opera.
 
June 12, 2009
Votes: +0

Leave a Comment

busy