Submitting a Form by Enter key

Post on March 16th, 2007

Depending on the browser type and configuration, pressing the Enter key while in a form does not always submit the form. Sometimes, for instance, the button that submits the form resides in another frame. In that case, adding a bit of JavaScript to ensure that the Enter key sends the form data, as well, comes in handy.

All that is necessary to implement for that function is a standard key listener: Keyboard events are not part of DOM Level 1 or Level 2, but are still implemented in recent browsers.

Accessing the event differs from the usual approach (window.event in Internet Explorer; the event as the automatic parameter of the function in all other browsers). But then, the keyCode property returns the ASCII code of the key, which can then be processed, as in the following example:

The key code for the Enter key is 13, so when this code is found, the form is submitted:

function checkKey(e) {
 
     var key;
 
     if (window.event) {
 
          key = window.event.keyCode;
 
     } else {
 
          key = e.keyCode;
 
     }
 
     if (key == 13) {
 
          document.forms[0].submit();
     }
 
}
 
window.onload = function () {
 
     document.forms[0].elements["field"].onkeydown = checkKey;
}

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.