Disable the Enter Key

The enter key performs different functions depending on whether your visitor is in a textarea in a form on your page, elsewhere in a form, on somewhere not in a form at all. You may want to avoid all of this confusion by just ignoring all enter key presses on your page. Try it out on this page, the following form allows you to enter text into both a text area and text field and when the action button is selected (either by clicking on it with the mouse or tabbing to it and then pressing the space bar) the content of both input fields will be displayed separated by a line feed. All enter key presses on this page will be ignored so the only additional linefeeds in the result will be due to word wrap.

So how do we achieve this result? A few lines of Javascript added to the head section of the page will do it. The following code works on Internet Explorer, Netscape 4+, and Opera 6+.

function kH(e) {
var pK = e ? e.which : window.event.keyCode;
return pK != 13;
document.onkeypress = kH;
if (document.layers) document.captureEvents(Event.KEYPRESS);

What this code basically does is to capture the numerical code corresponding to each key that is pressed and discard it if it is 13 (the code corresponding to the enter key). Much of the supplied code is only required for some browsers (in particular Netscape 4) in order to ensure that all keystrokes are captured including those entered into forms. Most browsers do not require all of the code but the additional statements do not interfere with the functioning on those browsers. The code supplied here is the shortest version of the test that I can put together that works on all of the browsers where keystroke capture is possible.

So how do we call the code to make it take effect on our page? Well the presence of this code in the head section of the web page will disable the enter key for us for the entire page without any need to "call" it from anywhere within the page. The document.onkeypress statement will make sure that all keystrokes are processed by the kH function so no further code in the body section of the page is required.

Note that this code does not disable the enter key for all browsers. Browsers which do not support Javascript, browsers with Javascript disabled, and earlier browsers that do not provide a means of capturing keystrokes (eg. Opera 5) will still process enter keys as if the code were not there.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow