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?
an ASP button renders as a submit button by default. The default action for Enter keypress (happens after keydown, before keyup) when a form element is in focus is to submit the form. If an HTML form contains multiple submit buttons, the first one is the default submit button.
Putting all this together, when you keypress (remember, happens after keydown, before keyup) with the Enter key, the form is submitted via the default submit button (Button1).
You have many options to fix the problem. I would recommend using an input type="button" instead of an ASP button with runat=server and handle the click events from there.
Related: Asp button with different button type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With