Jeff's Junk

The sillynonsense and .NET musings of Jeff Putz

News

My Sites

The default button on enter on an ASP.NET form

I haven't really thought about this in a long time, but after searching a bit and finding some really complex solutions, I figured out a way to fire a "click" based on pressing enter in a text field. It works OK in IE and Firefox, which is good enough for me, and it only requires one line.

EmailTextBox.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + LoginButton.UniqueID + "','')");

"EmailTextBox" is as you might suspect a text box control, while "LoginButton" is a link button. All it does is render an extra attribute in the rendered tag that checks for a key press, and if it's the enter key, it fires ASP.NET's __doPostBack method with the unique ID of the button that you want to virtually press. That in turn fires off whatever server-side event handlers you've wired up. You could pass in the eventargument as the second parameter in that Javascript if you wanted to.

I can't understand why this wasn't included somewhere in v2. They did offer a default button for the entire form, but I think that only works if you have actual buttons (I use LinkButtons almost exclusively). You could actually wire up any control name here if you wanted.
Posted: Jul 26 2005, 03:25 PM by Jeff | with 58 comment(s) |
Filed under:

Comments

Erik Porter said:

We use this in our apps all the time. Very handy! Even with regular buttons, there's still the problem of which one actually gets clicked when you have more than one in your form. By default it just has to do with whichever button is first on the page. It would be nice if a feature in 2.0 allowed you to specify default buttons for both the button and linkbutton. Have you posted anything on Product Feedback about it?
# July 26, 2005 3:40 PM

Jeff said:

I don't remember. Maybe? I haven't thought this out enough to know what other implications there might be, such as those if you plant this thing inside a grid or something.
# July 26, 2005 3:41 PM

scottgu@microsoft.com said:

In ASP.NET V2 you can drive the enter behavior on any focus point on a page. You set this either on the <form> tag or by wrapping regions in an <asp:panel> and then setting the default button property on those container controls (the asp:panel approach is how you can have multiple default buttons all over the page). If the focus is inside that region and enter is hit, the container control will cause the right post-back control to fire.

Hope this helps,

Scott
# July 26, 2005 5:31 PM

Erik Porter said:

That's awesome, Scott...thanks! :)
# July 26, 2005 5:34 PM

Matt Berther said:

Jeff:

I use this technique that I posted about a while back...

http://www.mattberther.com/2003/06/000125.html

Works everytime for me.
# July 26, 2005 6:09 PM

Jeff said:

Matt: That solution isn't going to work if different text fields should activate different buttons.

Scott: Good idea, but that only works with buttons, right? LinkButtons no?
# July 26, 2005 9:28 PM

John Walker said:

I've been using a cool free control from MetaBuilders called DefaultButtons for my 1.1 apps. Here's the URL...

http://www.metabuilders.com/Tools/DefaultButtons.aspx

It makes the page a bit bigger because it injects some javascript to the client, but it has worked flawlessly for me. Works with link buttons too. Highly recommended.




# July 27, 2005 1:01 AM

QWorld said:

Walker, your control is nice, but it seems still a little bit unperfect, for example, when I foucs on the second textbox and hit enter, Smack1 is foucsed and pressed on the page, althrough the label show Smack2 is fired
# July 27, 2005 6:45 AM

Josh said:

Just in case other people come to this page because they have a form that won't submit with the enter key: There is a retarded bug (I think with IE) where if there is only one text box and one button, the submit will NOT be fired when pressing the enter key. The work around is to add another input control somewhere - using another read-only text box of 0 width and 0 height worked for me.
# August 11, 2005 7:44 PM

mario said:

What happens if you have more than one textbox in the form.Then it doesn`t see the desired button but the first one in the form.How can I rounf this problem?
# August 24, 2005 9:33 AM

Jeff said:

Sure it does. You set each TextBox to fire the right postback event as described above.
# August 24, 2005 10:02 AM

Tarek El-Mallah said:

Scott...thanks! :)

the panel solve the problem.

# August 7, 2006 4:04 AM

siva said:

nice

# August 11, 2006 3:09 AM

Jeremy said:

Today I have been researching all of the problems mentioned in the above comments. There really are 2 or 3 scenarios / problems I see people running into. * One input control and one submit button ----IE doesn't send submit button name/value pair in form request *You want to activate different click events (similar to your solution) depending on which input field was active when enter was pressed (this was my specific problem). ----See below * Different solutions may or may not work depending on if you have non-button controls causing postback (which will generate a __doPostBack script, which will NOT BE THERE if only buttons are used on the page to cause post back, i.e., controls that are rendered as HTML elements that cause form submission by default.). ----Check the source of the generated page. Refer to online information to find correct solution for your situation. I think simply using the method at page top may not stop the "default" (first submit button in form) click event from happening. I think it simply triggers another click event for the button you specify. I had trouble with a similar method, but didn't debug to be sure of my theory after I simply found a method that did work. If you want ENTER to trigger different submit button (control) events depending on which textbox (input field) is active, personally, I think this is the best solution I've seen: http://www.newvisionusa.com/Blog/2005/7/23/DefaultButton/Default.aspx It uses the onkeydown event, cancels the default event, and causes the click you specify. If you want more information about the IE issue mentioned above, where there is only one submit button and one input field, see this: http://aspnet.4guysfromrolla.com/articles/060805-1.aspx
# August 21, 2006 7:35 PM

Michael said:

I'm using LinkButton almost exclusively as well. Unfortunately Scott's suggestion only works in IE and not Firefox because there doesn't seem to be a Click() function on HTMLAnchorElement (this is what LinkButton are rendered as). Sadly looking at the W3C docs it looks like it isn't a requirement. Only HTMLInputElement is required to have that function.

# October 2, 2006 9:53 AM

Koob said:

Thanks Scott. But does not work with LinkButton and ImageButton (see http://support.microsoft.com/default.aspx/kb/921277). Maybe provide some standard scripting in the next .Net version?

# October 27, 2006 10:41 AM

SImon said:

Hi

My postback for my button includes some client-side javascript (see below).  The order is:

add some data to database

display an alert box

However, using this code in my pageload event:

txtName.Attributes.Add("onKeyPress", "BLOCKED SCRIPTif (event.keyCode == 13) __doPostBack('" + butAdd.UniqueID + "','')")

when I hit return the button postback event fires ok however, data is added succesfully to the database BUT the alert box does not appear.

DOes anyone have any ideas why not? or a solution?

Thanks,

Simon

strMessage = "Now send a text message!"

                   'finishes server processing, returns to client.

                   Dim strScript As String = "<script language=JavaScript>"

                   strScript += "alert(""" & strMessage & """);"

                   strScript += "</script>"

                   If (Not Page.IsStartupScriptRegistered("clientScript")) Then

                       Page.RegisterStartupScript("clientScript", strScript)

                   End If

# November 24, 2006 7:26 AM

Jeff said:

First off, you don't need to check to see if a script is registered. Second, you're not wiring up anything to an alert box here. You're registering a script fragment that will execute when the page is loaded. You're not calling a function.

# November 24, 2006 10:35 AM

SImon said:

Thanks Jeff.

I took out the alert box and just simply wrote:

response.write("Got Here")

when I click the button the data gets added and Got Here gets written.

when I hit the enter key the data gets added but the "Got Here" doesn't get written.

I'm baffled - any ideas?

thanks,

SImon

# November 24, 2006 11:29 AM

John said:

Thanks Scott, wrapping my second "form" in the panel and setting the default button did the trick.  Thanks for the post, works great!

# December 1, 2006 9:31 PM

Khalid said:

actually I was thinking of this solution but I did not have time to try it.

Then I searched the internet to find some thing fast and this is it.

Don't worry; all the rights are for you :)

# December 4, 2006 10:46 AM

Muhammad Kashif Zia said:

After reading above i have made something like below for me just like window default button. Working fine but need to test more.

<form id="Form1" method="post" runat="server" onkeydown="BLOCKED SCRIPTif (window.event.keyCode == 13 && window.event.srcElement.type != 'submit'){__doPostBack('SearchCriteriaButton');return false;}">

# December 18, 2006 12:45 PM

Muhammad Kashif Zia said:

I have just refined the code above for my use as following, may help someone.

Default control in base class,

Control _DefaultControl = null;

public Control DefaultControl

{

get{ return _DefaultControl;}

set{ _DefaultControl = value;}

}

asp.net base page code in prerender overridden method,

if((this.Page.IsClientScriptBlockRegistered("PM-KeyDownEvent") == false) && (DefaultControl != null) ){Page.RegisterClientScriptBlock("PM-KeyDownEvent", "<script language=javascript event=onkeydown for=document> if (window.event.keyCode == 13 && window.event.srcElement.type != 'submit' && window.event.srcElement.type != 'button'){__doPostBack('" + this.DefaultControl.ClientID + "');return false;}</script>");

}

Add following code in child page

this.DefaultControl = SearchCriteriaButton;

Finally i added a CSS class for look of Default button, thats simply underline text for me.

Thanks. all above posts helped me to learn and find solution for my requirement.

# December 18, 2006 3:53 PM

JD said:

Should this code work for asp.net 1.1 too ?

cheers

-JD

# February 20, 2007 11:46 PM

Jared said:

I've been looking something that does that for ages. Thanks alot!

# February 21, 2007 8:16 PM

Kevin said:

Hi All,

Great solutions overall, however I can't seem to apply the theory to buttons which are not directly accessible in the code behind (such as buttons within templates of FormViews where a FindControl method is needed to access the control).

Here's a short snippet from the code behind:

Button btn = (Button)formView1.FindControl("btnUpdate");

Panel1.DefaultButton = btn.UniqueID;

I get an exception:

The DefaultButton of 'Panel1' must be the ID of a control of type IButtonControl.

I think the problem is Panel1 cannot find the button because it is nested in a template within the formview (i.e. the controls are roughly designed as:

<asp:Panel id="Panel1" ... >

 <asp:FormView ID="formView1" ... >

   <EditItemTemplate>

      ...

      <asp:Button id="btnUpdate" ... />

      ...

   </EditItemTemplate>

 </asp:FormView>

</asp:Panel>

If anyone has a solution for setting buttons within templates as default please post!

TIA

Kevin.

# April 29, 2007 12:02 PM

Mike said:

Kevin: the DefaultButton property is of type string, so you need to set it to the UniqueID property of the control.

# June 11, 2007 6:49 AM

Louis De Grazia said:

I used this in a user control and it worked fine. Thank you so much!

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

       TextBox1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnGo.UniqueID + "','')")

   End Sub

# June 25, 2007 3:50 PM

Nimesh Khatri said:

If there were multiple buttons on the page then the page could end-up reloaded a couple of times (call page_load multiple times). Returning false avoids the extra reload.

The following change fixes this problem.

EmailTextBox.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) {__doPostBack('" + LoginButton.UniqueID + "',''); return false);");

# June 26, 2007 6:12 PM

Mike said:

You know what could solve all this? Having multiple forms on your page. Too bad you usually have the complete page in a form and nested forms are not allowed in HTML.

# July 30, 2007 10:57 AM

alex said:

This doesn't sit well with me but it definitely does the trick for FormViews with templates. Add a panel into each template and set the DefaultButton value there.

<EditItemTemplate>

  <asp:Panel runat="server" ID="pnlEdit" DefaultButton="btnUpdate">

     ...

<InsertItemTemplate>

  <asp:Panel runat="server" ID="pnlEdit" DefaultButton="btnInsert">

     ...

# August 8, 2007 9:42 AM

System.Blog.Martens.Ben said:

In my previous life as an ASP.NET ninja, I had a request from a client to use the enter button to submit

# August 13, 2007 5:08 PM

Noticias externas said:

In my previous life as an ASP.NET ninja, I had a request from a client to use the enter button to submit

# August 13, 2007 5:45 PM

MSDN Blog Postings » Default ASP.NET Button said:

Pingback from  MSDN Blog Postings  &raquo; Default ASP.NET Button

# August 13, 2007 6:16 PM

mepis said:

I would use:

this.Form.DefaultButton = LoginButton.UniqueID;

# August 14, 2007 3:52 PM

Richard said:

Note that if you are using this method in a user control you must use ClientID instead of UniqueID.

# September 3, 2007 7:09 PM

Dave said:

I was looking for similar problem but the stated solution did not work.

My scenario:

2 textboxes

3 buttons

My solution:

Page.Form.DefaultButton = btnSubmit.UniqueID

# September 19, 2007 12:58 PM

Sheetal DJ. said:

//Fires button click event on Enter key press

function fnTrapKD(Button1, event){

    if (document.all){

     if (event.keyCode == 13){

      event.returnValue=false;

      event.cancel = true;

      Button1.click();

     }

    }

    else if (document.getElementById){

     if (event.which == 13){

      event.returnValue=false;

      event.cancel = true;

      Button1.click();

     }

    }

    else if(document.layers){

     if(event.which == 13){

      event.returnValue=false;

      event.cancel = true;

      Button1.click();

     }

   }

   }

# September 21, 2007 2:49 AM

Tyler Thompson said:

Making a custom linkbutton server control from this website worked great for me in both IE and Firefox:

kpumuk.info/.../using-panel-defaultbutton-property-with-linkbutton-control-in-asp-net

# September 27, 2007 12:54 PM

Set default button for Enter key (ASP.Net 1.1) « CJ said:

Pingback from  Set default button for Enter key (ASP.Net 1.1) &laquo; CJ

# October 23, 2007 12:39 AM

Dave Newman said:

If you want to fix this problem without having a lot of extra markup, try this:

sentia.com.au/.../fixing-the-enter-key-in-asp-net-with-jquery

# October 24, 2007 8:49 PM

devmet said:

Thanks. This is great !

# January 21, 2008 11:09 AM

UTTAM said:

Hi guys i found solution finally.

Setting link button as Default button for FIREFOX as well as IE:

use this fallowing code-->

in .aspx file---------------------------

<asp:TextBox ID="txtUserName" runat="server" Width="230" ToolTip="Enter a username" MaxLength="50">

<asp:LinkButton ID="btnSearch" runat="server" OnClick="btnSearch_Click"></asp:LinkButton>

<script type="text/javascript">

function clickButton(e,buttonid)

{ debugger;

var bt=document.getElementById(buttonid);

if(typeof bt=='object')

{

if(navigator.appName.indexOf("Netscape")>(-1))

{

if(e.keyCode == 13)

{

if (bt && typeof(bt.click) == 'undefined')

{

bt.click = addClickFunction1(bt)

}

}

}

if(navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))

{

if(event.keyCode == 13)

{

bt.click();

return false;

}

}

}

}

function addClickFunction1(bt)

{debugger;

var result = true;

if (bt.onclick) result = bt.onclick();

if (typeof(result) == 'undefined' || result)

{

eval(bt.href);

}

}

</script>

-------------------------

in aspx.cs file (write code for the text boxes u required)

aspx.cs file(C#.net code)--->

in Page_Load Event

txtUserName.Attributes.Add("onkeypress", "javascript:return clickButton(event,'" + btnSearch.ClientID + "');");

# March 10, 2008 9:53 AM

Ian said:

Josh, thanks for that 1 textbox bug find.  I was having trouble with a button not doing anything on return.  I added a second textbox, as you suggested, and it works now.

# March 11, 2008 5:15 PM

droyad said:

Thanks for the info, it helped my come up with a slightly different solution:

droyad.blogspot.com/.../enter-key-on-linkbuttons.html

# March 31, 2008 8:04 PM

DugFmJamul said:

Thanks Jeff,

I have beed searching for days and your method seems to work just fine for me.

Thanks again.

# April 4, 2008 5:46 PM

Ian Bowyer said:

Another option is to put the controls in a panel and set the DefaultButton property to the button.

<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">

  <asp:TextBox ID="TextBox1" runat="server" />

  <asp:Button ID="Button1" runat="server" Text="Button" />

</asp:Panel>

# June 5, 2008 4:06 AM

Slappy said:

I have a slightly different but related problem.

I want to suppress the default submit behavior when the enter key is hit. Limiting this to an element would be a bonus. Any ideas or pointers?

# July 4, 2008 2:23 AM

jonsch said:

holy crap Scott, you're like the asp.net supreme guru.  Actually, my opinion is bias dude, I've read tons of your books and watched a good number of your videos.

Keep kickin' arse and takin' names, as I'm sure the internet community truly appreciates it, I know I do!

Thanks.

Jon

# July 21, 2008 4:55 PM

Dawiid said:

Damn Scott, you just lifted a stone of my chest thank you for sharing your knowlege! You da' man! :o)

# August 8, 2008 9:07 AM

Jake H. said:

Thanks for the simple, effective, cross-browser solution Jeff!  It works great in IE, Firefox, and Chrome.  You just saved millions of our users (and more importantly us developers that test the site constantly) much hassle.  Thanks again!

# September 11, 2008 12:08 PM

Barry said:

I have been trying to make this work for a couple of hours and cannot get it working - Am I missing something (Using BN Net Framework 1.1)

Using two buttons and trying to get textbox1 to initiate a button2 response. Keeps going to button1 response. See Code Below:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

TextBox1.Attributes.Add(”onKeyPress”, “javascript:if (event.keyCode == 13) __doPostBack(’” + Button2.UniqueID + “‘,”)”)

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Label1.Text = “button 1 clicked”

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Label1.Text = “Button 2 clicked”

End Sub

Thanks Barry

# October 9, 2008 7:36 PM

Greyman said:

Sweet!  Such elegant solution.  So simple to implement and very efficient, yet not obvious.  This tweak to my forms has really been appreciated.

# October 14, 2008 11:43 PM

jcargilo said:

Hey Jeff, I've been using your method since I discovered it a while ago.  I recently ran into an issue (surprised I hadn't earlier) in that the __doPostBack method is bypassing client validation (using ASP.NET validation controls).  While looking around for a more elegant solution, I figure it simply had to do with adding some code to your method to check for client validation before posting back.  Following PLBlum's advice at:

forums.asp.net/.../2751480.aspx

Using your example above, I modifed your method as follows:

EmailTextBox.Attributes.Add("onKeyPress", "javascript:if(event.keyCode == 13){ if(Page_ClientValidate('" + LoginButton.ValidationGroup + "')){__doPostBack('" + LoginButton.UniqueID + "','')}}");

This little snippet will now check client validation (and the validation group if you're doing multiple forms on one page) before processing the Default Button Enter Key press.

Hope that helps anyone else who might have discovered this.  Thanks for the starting code, however, it's been excellent!

# February 2, 2009 4:12 PM

Jeepie said:

Thanks for the tip on setting the Default button on a panel, saves a lot of time :-)

# February 11, 2009 8:23 AM

Kris Haney said:

You can just use this control as you would a normal panel and it works with LinkButtons as well.

public class DefaultButtonPanel : Panel

{

  protected override void OnLoad(EventArgs e)

  {

     if (DefaultButton != "")

     {

        LinkButton btn = FindControl(DefaultButton) as LinkButton;

        if (btn != null)

        {

           Button defaultButton = new Button();

           defaultButton.ID = btn.ID + "_Default";

           defaultButton.Text = " ";

           defaultButton.Style.Add("display", "none");

           PostBackOptions p = new PostBackOptions(btn, "", null, false, true, true, true, true, btn.ValidationGroup);

           defaultButton.OnClientClick = Page.ClientScript.GetPostBackEventReference(p) + "; return false;";

           Controls.Add(defaultButton);

           DefaultButton = defaultButton.ID;

        }

     }

     base.OnLoad(e);

  }

}

# May 6, 2009 3:17 PM

Kris Haney said:

Oh and it works with validation groups.  You could tweak that PostBackOptions object to include postback url, etc, but I didn't need it.

# May 6, 2009 3:21 PM

SNRaj said:

protected void Page_Load(object sender, EventArgs e)

{  

Page.Form.DefaultButton = <Control>.UniqueID;

}

Note: <Control> may be button, imagebutton

# June 22, 2009 9:53 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)