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!