Click here to Skip to main content
11,631,906 members (69,429 online)
Click here to Skip to main content

Tagged as

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

, 17 Oct 2011 CPOL 48.4K 11
Rate this:
Please Sign up or sign in to vote.
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:

$(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:

<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)

Share

About the Author

Ram Balak Sharma
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/

You may also be interested in...

Comments and Discussions

 
SuggestionUse this in code behind Pin
Nik663-Mar-13 4:51
memberNik663-Mar-13 4:51 
GeneralMy vote of 5 Pin
phicho29-May-12 0:53
memberphicho29-May-12 0:53 
GeneralReason for my vote of 5 simple solution for a problem we use... Pin
Osvaldo Pontes27-Dec-11 7:27
memberOsvaldo Pontes27-Dec-11 7:27 
GeneralReason for my vote of 5 nice work Pin
Bilal Ahmed Lilla26-Oct-11 19:54
memberBilal 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
memberShyamSunderVashista18-Oct-11 19:33 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150728.1 | Last Updated 17 Oct 2011
Article Copyright 2011 by Ram Balak Sharma
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid