Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET
Tip/Trick

How to prevent textbox postback when hitting Enter key in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.93/5 (12 votes)
17 Oct 2011CPOL 88.8K   11   6
Stop postback in text box when hitting the Enter key, by using jQuery

In ASP.NET, it is default nature that if you press the Enter key on any text box, the page wil post back. To stop this, I had to write a JavaScript function as below:


JavaScript
$(function () {
       $(':text').bind('keydown', function (e) {
        //on keydown for all textboxes
           if (e.target.className != "searchtextbox") {
               if (e.keyCode == 13) { //if this is enter key
                   e.preventDefault();
                   return false;
               }
               else
                  return true;
           }
           else
               return true;
       });
   });

Below is the HTML for the textbox and buttons:


HTML
<form id="form1"  runat="server">
        <input id="Button1" type="button" value="Button" " />
        <asp:TextBox ID="txtMessage" runat="server"  Width="438px">
</form>

Now if you hit the Enter key in the textbox, then the page will not postback.


For complete code, you can visit: http://stackdotnet.blogspot.com/search/label/JQuery.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Q3 technology
India India
Ram is .Net Architect by profession and passion having 8 year experience. He has extensive experience on Microsoft Development Platform and is also Microsoft Certified Application Developer (MCAD) for Web.
Reach me at rsharma@stackdotnet.com

http://www.stackdotnet.com/
6 Freely avaliable E-Books/

Comments and Discussions

 
Suggestioncompleting event stack Pin
Dan Randolph16-Oct-15 13:22
Dan Randolph16-Oct-15 13:22 
SuggestionUse this in code behind Pin
Nicolò Beltrame3-Mar-13 4:51
professionalNicolò Beltrame3-Mar-13 4:51 
GeneralMy vote of 5 Pin
phicho29-May-12 0:53
phicho29-May-12 0:53 
GeneralReason for my vote of 5 simple solution for a problem we use... Pin
Osvaldo Pontes27-Dec-11 7:27
Osvaldo Pontes27-Dec-11 7:27 
GeneralReason for my vote of 5 nice work Pin
Bilal Ahmed Lilla26-Oct-11 19:54
Bilal Ahmed Lilla26-Oct-11 19:54 
GeneralReason for my vote of 5 GR8 i was facing same issue when doi... Pin
ShyamSunderVashista18-Oct-11 19:33
professionalShyamSunderVashista18-Oct-11 19:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.