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

Posted by Ranjeet_8 under ASP.NET category on | Points: 40 | Views : 2061
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="">
<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) {;
return false;
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Write Text And Press Enter Key" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br /><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Write Text And Press Enter Key" OnClick="Button2_Click" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

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