Setting the default Button for a TextBox in ASP.NET
We perform a browser detection because IE and Netscape have different event models. The function finally returns false so that the keypress event is cancelled (otherwise a second form submit will be raised). This works with newer versions of IE/Netscape.
function clickButton(e, buttonid){ var evt = e ? e : window.event; var bt = document.getElementById(buttonid); if (bt){ if (evt.keyCode == 13){ bt.click(); return false; } } }
//code behind TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");
The code behind generates the following code:
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')" />
This causes web control Button1 to be clicked when the enter key is hit inside TextBox1.
There are better ways to do this with the newest version of ASP.net!