Hit Enter Key in ASP.NET page
Scenario:It's very common for the user to hit the Enter key after they have entered the required data in the text box.
For example, when you want to Login.
After keying in your user name and password, instead of clicking on the "Login" button, you may also hit the Enter key to login.
Solution 1:
In order to do this, ASP.NET 2.0 has provided a property in Form and Panel controls, which is "DefaultButton".
You can set the DefaultButton property to the button name, so that whenever user hits the Enter key in the form or panel, the button clicked event will be triggered.
Solution 2:
Well, I was having an issue with the DefaultButton.
I'm not using panel to group my controls, as panel is having some problem with IE7.
I've found a solution with using javascript, it's simple and nice to use. (You do not need to edit your current UI for this.)
Create this function:
public static void AddEnterKeyAttribute(TextBox txt, ImageButton iBtn)
{
txt.Attributes.Add("onkeydown",
"if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + iBtn.UniqueID + "').click();return false;}} else {return true}; ");
}
The keycode for enter key is 13.
When a key is pressed in textbox it will check the keycode is 13. If it is 13 the relevant button will be clicked.
event.keycode will not work with firefox, so we are using event.which.
You can create multiple similar functions for different web controls.
Perhaps you can also create a general function which accept any kind of web controls. I haven't try this yet.
You just need to add this in Page_Load event, for all the web controls that you want to trigger the button clicked event when user hits the Enter key:
AddEnterKeyAttribute(txtPassword, ibtnLogin);
1 comment:
your site is very nice ...
this is very helpful and attractive.
visit for asp.net help asp.net help
Post a Comment