JavaScript to find which button is pressed among multiple buttons
I have multiple TextBoxes and multiple buttons on the page. If I hit Enter key while I'm in one TextBox the corresponding Button click event should be executed.
I have written the code like below, but It is not working. Can anybody please explain me how...
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_开发者_如何学PythonClick" />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:Button ID="Button4" runat="server" Text="Button" OnClick="Button4_Click" />
</div>
Code behind
public partial class JavaScriptEnterKey : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("OnKeyDown", "HitButton('" + Button1.ClientID + "');");
TextBox2.Attributes.Add("OnKeyDown", "HitButton('" + Button2.ClientID + "');");
TextBox3.Attributes.Add("OnKeyDown", "HitButton('" + Button3.ClientID + "');");
TextBox4.Attributes.Add("OnKeyDown", "HitButton('" + Button4.ClientID + "');");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Button1 is clicked");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Write("Button2 is clicked");
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Write("Button3 is clicked");
}
protected void Button4_Click(object sender, EventArgs e)
{
Response.Write("Button4 is clicked");
}
}
**JavaScript**
function HitButton(Button) {
if (event.keyCode == 13) document.getElementById(Button).click();
}
Try using the keypress event rather than keycode. That seemed to work in my code.
精彩评论