html button elemenents and onserverclick attribute in asp.net
- by Adrian Adkison
I have been experiencing some very strange behavior using html buttons with the onserverclick attribute. What I am trying to do is use jQuery to designate the default button on the page. By default button I mean the button that is "clicked" when a user hits enter. In testing, I would hit enter while in an input field and sometimes the intended "default" button was clicked and the server side method defined in the corresponding onserverclick attribute was hit. Other times a post back was made without hitting the server method. In order to isolate the issue I created a minimal test case and found some very interesting results.
client side:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="/scripts/jquery-1.4.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="_response" runat="server"></asp:Label>
<input id="input1" type="text" />
<input id="input2" type="text" />
<button id="first" type="button" class="defaultBtn" runat="server" onserverclick="ServerMethod1">test1</button>
<button id="second" type="button" runat="server" onserverclick="ServerMethod2">test2</button>
</form>
<script type="text/javascript">
jQuery('form input').keyup(
function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button.defaultBtn').click();
return true;
}
}
);
</script>
</body>
</html>
server side:
public partial class admin_spikes_ButtonSubmitTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ServerMethod1(object sender, EventArgs e)
{
_response.Text = "server method1 was hit";
}
protected void ServerMethod2(object sender, EventArgs e)
{
_response.Text = "server method2 was hit";
}
}
What I found was that everything worked as expected with this code except when I removed one of the input elements. In Firefox 3.6 and IE 8 when only one input exists on the page, hitting enter does not trigger the onserverclick, it makes a post back without even being jQuery "clicked" or actually "clicked". You can test this by starting with two inputs and clicking "test2". This will output "server method2 was hit". Then just hit enter and the output will be "server method1 was hit. Now take away an input and run the same test. Click "test2" see the results, then hit enter and you will see that nothing will change because the "test1" method was never hit. Does anyone know what is going on?
Thanks
p.s. Chrome worked as expected