Home > AJAX, JavaScript, Visual Studio 2005, Visual Studio 2008 > Catching Enter on Web Pages with JavaScript

Catching Enter on Web Pages with JavaScript

September 25, 2007

A common question in the .aspnet forums has been how to prevent the use of the Enter key when submitting forms online.  By default, a form submits when Enter or Return is pressed on the keyboard.

The “best” way to deal with this would be form validation—if something isn’t filled out, the validators stop and pick it up.  That resolves most issues.  However, several still would like to disable the Enter key.  So here’s how using JavaScript.

function catchEnter(e)

{

// Catch IE’s window.event if the
// ‘e’ variable is null.

      // FireFox and others populate the

// e variable automagically.

      if (!e) e = window.event; 

       

      // Catch the keyCode into a variable. 

      // IE = keyCode, DOM = which.

      var code = (e.keyCode) ? e.keyCode : e.which;

       

       // If code = 13 (enter) or 3 (return),

// cancel it out; else keep going and

// process the key.

if (code == 13 || code == 3) return false;
else return true;

}

   

// Anonymous method to push the onkeypress

// onto the document.

// You could finegrain this by

// document.formName.onkeypress or even on a control.

window.onload = function() { document.onkeypress = catchEnter; };

This example is cross-browser compatible (I’ve tried it in IE6, IE7, and FF2.  The one variable I don’t have to try is Mac.  From what I’ve read, Mac “enter” keys return a different KeyCode.  If anyone has that, post it up and I’ll add it to the code.

The code is pretty simple and could be, in the latest craze, be pushed into a Custom Control and accept an array of “keyCodes” to block or placed as a string and added to a Page object using the ClientScript in C#. Hmm, ideas. 

 

%d bloggers like this: