Focus a textbox into a button when user hit enter key in text box

Ranjeet_8
Posted by Ranjeet_8 under ASP.NET category on | Points: 40 | Views : 2118
When u type some thing in textbox then hit the enter key then the textbox focus on
the Default Button Click Event.
ASPX Design Page :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Testing Page</title>
<script type="text/javascript" language="javascript">
function clickEnterButton(e, btnID) {
var evnt = e ? e : window.event;
var btn = document.getElementById(btnID);
if (btn) {
if (evnt.keyCode == 13) {
btn.click();
return false;
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:Button ID="Button1" runat="server" Text="Write Text And Press Enter Key" OnClick="Button1_Click" />
&nbsp;
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br /><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
&nbsp;
<asp:Button ID="Button2" runat="server" Text="Write Text And Press Enter Key" OnClick="Button2_Click" />
&nbsp;
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>

C# Code

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Attributes.Add("onkeypress", "return clickEnterButton(event,'" + Button1.ClientID + "')");
TextBox2.Attributes.Add("onkeypress", "return clickEnterButton(event,'" + Button2.ClientID + "')");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text;
}
protected void Button2_Click(object sender, EventArgs e)
{
Label2.Text = TextBox2.Text;
}

Comments or Responses

Login to post response