Fire Default button on enter on an Asp.NET page

I found two ways to get this to work. By Default the first button in the form is the default button. When you push Enter an fire event of this button occur. Current solution is enough to get Login control on asp.net form to work. Here is the code:


Dim ctl As Control = Login1.FindControl("LoginLinkButton")
If Not (ctl Is Nothing) Then
Login1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) {__doPostBack('" + ctl.UniqueID + "',''); return false;}")
End If

Fix: return false will break the firing of other buttons. Just to ensure right behaviour.

It works fine for all browsers.
There is one more way to do this but unfortinately it doesn't work with firefox.

Login1.Attributes.Add("onkeypress", String.Format("javascript:return WebForm_FireDefaultButton(event, '{0}')", ctl.ClientID))

2 comments:

  1. After a lot of google, this is the clearest and straightforward solution I have found for this issue, congratulations!

    ReplyDelete
  2. Thank you so much! Very simple. It worked perfectly for me after hours of googling complicated fixes that didn't work.

    ReplyDelete