JavaScript Tip: Submitting a Form by Enter key

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:

Leave a Reply

Your email address will not be published. Required fields are marked *