How to get and cancel the enter/return key in Javascript?

There was a problem I was facing with a web form I made, and that was that whenever the user pressed the enter key while typing in a text box, he was taken to the previous page. Obviously it was very irritating so I thought about making up a javascript routine to eat away the Enter key. At first I made up a function using window.event and that was working perfectly fine until I discovered that it wasn’t working in Firefox 3. So I starting googling things out and came up with this function. This baby works fine in both browsers.

function eatenter(e) {
if (window.event) { // IE
if (e.keyCode == 13) {
//override default value so you know it was caused by input

return false;
else if(e.which == 13) { // Netscape/Firefox/Opera

return false;

Since this was an ASP .NET application and I was working with asp:Textbox control so I added this function to the textbox using this statement.

txtBox.Attributes.Add(“onkeydown”, “return eatenter(event);”);

This would look something like that in HTML

<input type=”text” onkeydown=”return eatenter(event);” />

Hope that helps,

Happy Programming Folks!


Author: Imran Akram

A .NET/SharePoint Consultant and a political enthusiast who believes in putting the feet of the elected and/or unelected officials to fire in order to get good governance.

One thought on “How to get and cancel the enter/return key in Javascript?”

  1. This used to work fine but now firefox 3 ignores all of these:
    switch(e.keyCode) {
    case 13: //enter
    e.returnValue = false;
    e.cancel = true;
    e.cancelBubble = true;
    return false;
    return false;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s