Monday, February 4, 2008

Submitting a Form upon Pressing the Enter Key


It is very common on web forms that a page is desired to submit its form when a user presses the Enter key while the focus in a certain or any text box. This is typically done using JavaScript. I want to share how it's done as it can be very useful. In essence all that is done is that every time a user presses a key, a JavaScript code checks if the key pressed is the Enter key. If so it submits the form to the server, otherwise it does nothing. The following is a snippet of the code would look like:




On the JavaScript side


function enter_submit(pevent)
{
if(window.event) //Internet Explorer
{
if(myEvent.keyCode == 13) //check enter was pressed
{
document.formname.submit();
//or __doPostBack("",'');
return;
}
}
else if(pevent.which) // Netscape/Firefox/Opera
{
var pressed = pevent.which;
if(pressed == 13)
document.formname.submit();
//or __doPostBack('','');
}
}



On the HTML or ASP .NET side



<asp:Textbox ID="txtPassword" runat="server" onkeypress="javascript:enter_submit(event);/>

<input id="inPassword" type="password" onkeypress="enter_submit(event);"/>

No comments: