Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

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

4.93/5 (12 votes)
17 Oct 2011CPOL 91.4K  
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)