Submitting forms with JavaScript

From time to time some of our users file a bug report concerning an accidental form submit. We weren’t able to track it down until today and there seems to be a nasty bug in some browsers (appeared in Firefox 3.6 on Mac OS X).

We used to attach an event to a textarea element (we’re using Prototype, this is not the exact code but the general idea of it):

$("input-textarea").observe("keyup", function() {
  if (event.keyCode == Event.KEY_RETURN) {
    return formSubmit();
  }
});

This worked in most scenarios except for this one:

  • User enters some text into textarea,
  • User clicks on the browser’s address bar and enters an URL,
  • User presses Enter,
  • The form was submitted, then location was changed.

Avoiding this kind of behavior can be achieved by switching from onkeyup to onkeydown event.

$("input-textarea").observe("keydown", function() {
  if (event.keyCode == Event.KEY_RETURN) {
    return formSubmit();
  }
});

This snippet works for us as expected.