Thursday, January 19, 2012

How prevent Textbox postback when hit enter key in asp.net by using Jquery, Java Script

In Asp.net on TextBox control when you will press enter key then page will post back, this is default nature of Asp.net. to avoid this post back we have to write a java script function as below.

This is a default.aspx page code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Prevent postback on enter key in text box</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/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;
        });
    });

</script>

</head>

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

    </form>

</body>

</html>


This is the default.asps.cs page code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       Response.Write("Psotback");
    }

}


when you will press enter key on text box then page will not pst back.

No comments:

Post a Comment