In this article I will explained how to prevent users from submitting form by hitting enter using JavaScript in ASP.Net.

This is a default property that when one presses Enter key in the textbox the form gets submitted in other words there is a postback. So many people asked on forums

1. How to disable enter key in textbox?

2. How to prevent postback or form submission when enter key is pressed in textbox in ASP.Net?

 

So here is the neat and simple trick that does it. And the textbox below is the one that does not do a postback when enter key is pressed inside it

<asp:TextBox ID="TextBox1" runat="server"

   onkeydown = "return (event.keyCode!=13);" >

</asp:TextBox>

 

As you will notice above I wrote a simple condition on onkeydown event.

(event.keyCode!=13);

When enter key is pressed the above condition is false hence false is returned this the postback is disabled.

Note that Visual Studio will give a warning when you add onkeydown event and underline it with green.

It is just a warning and one can ignore that since Visual Studio searched for Server Side events and onkeydown is not in the list. Hence still it will work

But for those who do not want that warning can add this event from code behind

 

C#

TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);");

 

VB.Net

TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")

 

The above line will add the onkeydown event to the textbox. Make sure you add these lines to page load.


In order to disable the enter key form submission on all controls simply add it to the body tag in the following way

<body onkeydown = "return (event.keyCode!=13)">


In this way there is no need to add this event to all controls in the page.


The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari 

* All browser logos displayed above are property of their respective owners.