Friday, August 18, 2006

Textbox submit on enter

In .net 1.1, getting a textbox to submit on enter pressed is easy,

Put in the textbox (we'll call it UserPassword here) on the form (runat="server") and declare it in the codebehind with the same ID)

Have a submit button, either of type <asp:Button id="BtnSubmit" runat="server"../> or <input id="BtnSubmit" runat="server"...> on the form,
declare a variable in the codebehind with the same ID as the button or input and of the same type (Button or HtmlInputButton)

Wire the submit button up to do the actual submitting and then in Page_Init or Page_Load write this line of code (13 is the magical number for the enter key)

UserPassword.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('"+BtnSubmit.UniqueID+"').click();return false;}} else {return true}; ");

and there you have it


Casper Stendal said...

Thanks, for at very simple and easy to use solution!

Santanu said...

The solution is really helpful. Web GUI Forge