Tuesday, June 12, 2007

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);

It's done. It's just that simple. ^_^

Ref: The Code Project - Solving out ASP.NET enter key problem

6 comments:

  1. well done~~ it seems that u r doing well in asp.net 2 and javascript now... good good..
    ganbateh~~

    ReplyDelete
  2. To ocean:

    haha~~ thanks!
    Well, I'm still stuck in many areas, but yeah, improving my skills now. Have to, otherwise how can we complete the project? haha~~ the next challenge is Ajax. People are complaining about the whole page refresh issue. :p

    ReplyDelete
  3. Wow, this worked awesome, nice easy trick!

    ReplyDelete
  4. Thanks very much i spended my whole Day to find this Function

    ReplyDelete
  5. well done..thx for this sample. It works 100% under IE7 but NOT under Firefox :-( Have you any idea how to deal with it also under Firefox ?

    ReplyDelete
  6. thx for this sample. I've tested it also in FireFox but it doesnt work :-( It works ONLY in IE. Please help

    ReplyDelete