Ain’t too proud to hack – why won’t my Enter key click my button?

That’s right. With apologies to the “The Temptations”, I ain’t too proud to hack.

I was working on a script to submit a form by programmatically clicking a button using JavaScript when the user pressed the Enter key in a text box. Simple. Apparently, not simple enough for me. Here is the code I had:

<script type=”text/javascript”>
function test() {
if (typeof e == ‘undefined’ && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById(‘btnTest’).click();
}
}
</script>

<asp:TextBox ID=”txtTest” onkeypress=”test(event)” runat=”server” />
<asp:Button ID=”btnTest” Text=”Click” runat=”server” onclick=”btnTest_Click” />

So whenever a key was pressed while the focus was in the txtTest control, a PostBack event would occur. The problem was that whenever I pressed the Enter key, a PostBack would fire (i.e. the Page_Load event would be triggered), but the btnTest_Click event wasn’t firing. The odd part (from my perspective) was that if I disabled the “e.keycode == 13” line and entered a letter key (‘a’, ‘b’, etc…. Wait, there is no “etc” key), the btnTest_Click event would fire.

So, as is my way, I cheated. I made one little change, which was changing the keycode from the enter key to an empty string, and that caused click event to fire properly:

function test() {
if (typeof e == ‘undefined’ && window.event) { e = window.event; }
if (e.keyCode == 13) {
e.keyCode = “”;
document.getElementById(‘btnTest’).click();
}
}

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: