I have two TextBoxes with corresponding two Buttons. I want that when a TextBox has the focus and the user hits Enter then the corresponding Button's code behind event handler is executed as if it was clicked. This is a sample code:
Aspx:
<asp:TextBox ID="TextBox1" runat="server" onkeyup="myfunction1(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button 1" usesubmitbehavior="false" />
<asp:TextBox ID="TextBox2" runat="server" onkeyup="myfunction2(event)"></asp:TextBox>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button 2" usesubmitbehavior="false" />
<asp:Label ID="Label1" runat="server"></asp:Label>
<script type="text/javascript">
function myfunction1(e) {
if (e.keyCode == 13)
document.getElementById('<%= Button1.ClientID %>').click();
}
function myfunction2(e) {
if (e.keyCode == 13)
document.getElementById('<%= Button2.ClientID %>').click();
}
</script>
Code Behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Button 1 was clicked";
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "Button 2 was clicked";
}
But when I press Enter in any of the TextBoxes it always executes the Button1
code behind event handler. If I click on the buttons it obviously works as expected.
What am I missing?