Monday, October 13, 2008

Disable form submit on enter key press in (almost) one line of javascript

How to prevent auto-submission of forms with (almost) one line of javascript...

You make your web form and you test filling it out, and you find out hitting enter causes the form to automatically submit, when in fact you want a different behavior. Here's the simplest, cleanest, most compatible way to do this in browser-agnostic javascript without any dependencies of any kind:

<body onkeypress="var e = (event ? event : window.event); return (e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which) != 13;" >

Essentially that is saying grab the event, determine which key was pressed, and return false if it was the enter key. Returning false suppresses the form from auto-submitting.

Suppose you have a really super useful event handler like the following:

<input type='text' onkeypress='alert("Wow this sure is annoying");' />

The alert would still be shown even though you have the enter key-eating code at the body level thanks to the bubbling precedence of event handling. In essence, the onkeypress event handler is called for the textbox before the event handler code for the body is called. (If you return false from the textbox, it would never bubble up to the body's event handler)

This has been tested on the various current versions of IE (6,7,8), Firefox (2,3), and Safari (3).