Thursday, February 18, 2010

Enter Key in Asp.net

One of the common requests in ASP.NET is to submit a form when visitor hits an Enter key. That could be a case if, for example you want to make Login Screen. It is expected that user just hit enter when he insert a user name and password instead to of forcing him to use a mouse to click login button. If you want to make search function on your web site, it is frequently required to give a possibility to hit enter after you insert a search terms instead of mouse click on a Search button.

When you don’t want to submit a form with Enter key?

Rarely, you will need to disable an Enter key and avoid submitting form. If you want to prevent it completely, you need to use OnKeyDown handler on <body> tag of your page. The JavaScript code should be:


if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}



How to make a default button in ASP.NET
Method1:

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

Method2:

<form defaultbutton="button1" runat="server">
<asp:textbox id="textbox1" runat="server"/>
<asp:textbox id="textbox2" runat="server"/>
<asp:button id="button1" text="Button1" runat="server"/>

<asp:panel defaultbutton="button2" runat="server">
<asp:textbox id="textbox3" runat="server"/>
<asp:button id="button2" runat="server"/>
</asp:panel>
</form>

No comments:

Post a Comment