65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.93/5 (12 votes)

Oct 17, 2011

CPOL
viewsIcon

91353

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.