Monday, November 08, 2004

Using the enter key to submit a form

resource web page from:
http://www.allasp.net/enterkey.aspx

experience and example:

(1). add onkey down in the html part of an aspx page
onkeydown="if ((event.which && event.which == 13) (event.keyCode && event.keyCode == 13)) {document.forms[0].elements['Button'].click();return false;} else return true;" Runat="server" CssClass="FormText">

'Button' is the ID of the button control I want to fire onclick event,

but this won't work if the text box and button are in a usercontrol, cause final clientid will be changed, and user control id will be added in front of each sub control such as textbox and button, so I need to use the second solution,

(2). add onkeydown attribute in the code behide of the aspx page

string keydownAction = "if ((event.which&&event.which == 13)
(event.keyCode&&event.keyCode == 13)){document.forms[0].elements['"
+btnCreateAlias.ClientID+"'].click();return false;} else return true;";
txtAlias.Attributes.Add("onkeydown",keydownAction);

btnCreateAlias is the button I want to fire onclick event on, when key entered in the textbox.
btnCreateAlias.ClientID is clientid defined by the asp.net at run time, so this solution will be working at page level or inside a user control


No comments: