Geeks With Blogs
Jawad Khan Jawad's Lodge - The willingness to torture yourself before others is what makes a developer truly a unique breed.

It is very Common practice to hit an enter key on a text box in order to submit a form. For example if you are designing a Login Screen it is frequently required that user just hit enter after filling in the password rather then to be forced to click on the login butto itself. ASP.Net by default will just post back the form without clicking the the specified button ..... Here is the code that you can call to tie your text box to desired button you want to get clicked .....

For e.g in the PageLoad event

                   Jawad.Web.WebControls.Helpers.TieButton(txtBoxPassword, lnkButtonSubmit);

Here is the code ....  Just add a .cs class named Helpers.cs into your project or class library and copy the whole code there ....

using System;
using System.Web.UI;
namespace Jawad.Web.WebControls
{
 ///


 /// Summary description for Helpers.
 ///

 public class Helpers
 {
  ///
  ///     This ties a textbox to a button.
  ///

  ///
  ///     This is the textbox to tie to. It doesn't have to be a TextBox control, but must be derived from either HtmlControl or WebControl,
  ///     and the html control should accept an 'onkeydown' attribute.
  ///
  ///
  ///     This is the button to tie to. All we need from this is it's ClientID. The Html tag it renders should support click()
  ///
  public static void TieButton(Control TextBoxToTie, Control ButtonToTie)
  {
   string formName;
   try
   {
    int i=0;
    Control c = ButtonToTie.Parent;
    // Step up the control hierarchy until either:
    // 1) We find an HtmlForm control
    // 2) We find a Page control - not what we want, but we should stop searching because we a Page will be higher than the HtmlForm.
    // 3) We complete 500 iterations. Obviously we are in a loop, and should stop.
    while(! (c is System.Web.UI.HtmlControls.HtmlForm) &! (c is System.Web.UI.Page) && i<500)
    {
     c=c.Parent;
     i++;
    }
    // If we have found an HtmlForm, we use it's ClientID for the formName.
    // If not, we use the first form on the page ("forms[0]").
    if (c is System.Web.UI.HtmlControls.HtmlForm)
     formName = c.ClientID;
    else
     formName = "forms[0]";
   }
   catch
   {
    //If we catch an exception, we should use the first form on the page ("forms[0]").
    formName = "forms[0]";
   }
   // Tie the button.
   TieButton(TextBoxToTie, ButtonToTie, formName);
  }
  ///
  ///     This ties a textbox to a button.
  ///

  ///
  ///     This is the textbox to tie to. It doesn't have to be a TextBox control, but must be derived from either HtmlControl or WebControl,
  ///     and the html control should accept an 'onkeydown' attribute.
  ///
  ///
  ///     This is the button to tie to. All we need from this is it's ClientID. The Html tag it renders should support click()
  ///
  ///
  ///     This is the ClientID of the form that the button resides in.
  ///
  public static void TieButton(Control TextBoxToTie, Control ButtonToTie, string formName)
  {
   // This is our javascript - we fire the client-side click event of the button if the enter key is pressed.
   string jsString = "if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {document."+formName+".all['"+ButtonToTie.ClientID+"'].click();return false;} else return true; ";
   // We attach this to the onkeydown attribute - we have to cater for HtmlControl or WebControl.
   if (TextBoxToTie is System.Web.UI.HtmlControls.HtmlControl)
    ((System.Web.UI.HtmlControls.HtmlControl)TextBoxToTie).Attributes.Add("onkeydown",jsString);
   else if (TextBoxToTie is System.Web.UI.WebControls.WebControl)
    ((System.Web.UI.WebControls.WebControl)TextBoxToTie).Attributes.Add("onkeydown",jsString);
   else
   {
    // We throw an exception if TextBoxToTie is not of type HtmlControl or WebControl.
    throw new ArgumentException("Control TextBoxToTie should be derived from either System.Web.UI.HtmlControls.HtmlControl or System.Web.UI.WebControls.WebControl", "TextBoxToTie");
   }
  }

 }
}

Posted on Sunday, May 15, 2005 2:32 AM ASP.NET | Back to top


Comments on this post: Enabling Enter Key on a Text Box to auto click a Button ....

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Jawad, this works beautifully. Thanks!
Left by Danny Crowell on Jul 27, 2005 12:56 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Have you tested this with Firefox? I tried it and it failed. Thanks.
Left by Danny Crowell on Jul 27, 2005 1:42 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Isn't this the same as simply entering OnTextChanged="btnFindPtr_Click" on your ASP.NET textbox control?
Left by Travis on Jul 31, 2005 12:32 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
how do i find key so radio works could i find out what to do.i guess i am just plain dumb. thank you-----donna stokes
Left by donna k stokes on Jul 31, 2005 10:55 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Jawade sahab ur code is nice for ASP.Net but i wnat this thing in ASP.Will u help me.
shaileshraj2005@rediffmail.com
Left by Shailesh on Dec 28, 2005 4:31 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
This problem is much easier to solve using ASP.net 2.0. You can use the "defaultfocus" and "defaultbutton" properties of the form tag. For example:

<form id="Form1" method="post" runat="server" defaultfocus="txtEmailAddress" defaultbutton="btnSubmit">
Left by Danny Crowell on Jan 06, 2006 9:31 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Interesting, but that's a lot of coding to do something so simple. For ASP.NET 1.1 using IE, the click() method doesn't seem to work if you have several buttons on the page. What works is the focus() method. So, if you add the Attributes like this:

txtBox.Attributes.Add("onkeydown", "(event.keyCode==13)?document.getElementById('" + btnSearch.UniqueID + "').focus():return false;");

That should work as the javascript puts the button that you want in focus and then the enter key is pressed upon the focused object on the page.
Left by Mr_CPP on Feb 01, 2006 3:57 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Correction for the above:

the code I posted will give you a javascript error on page load. What you'll need to do is to make the javascript code as a function within the ASPX page and call the function by adding the "onkeydown" attribute from the codebehind. Don't bother with the "return false;" statement.
Left by Mr_CPP on Feb 01, 2006 4:25 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
How do I prevent post back when an enter key is pressed without using javascript
Thanks!
Left by Arun on Mar 03, 2006 11:55 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
The PostBack is actually a form Submit. It is the HTML behaviour that when you press Enter Key on a Input field within a HTML Form it will be submited to the Server. The Submit will treat the Enter key as a Click on the First button that apears after the FORM Tag.
That is the exact behaviour you are experiencing since in ASP.Net page you can only have 1 FORM Tag if you want Web Server Server Control in it.
The only way to stop it is to Use JavaScript. Catch the Key Press event and see if Key Pressed is Enter Key. If it is Enter key then just ignore it. This way page will not be submitted back to Server
Left by Jawad Khan on Mar 05, 2006 7:02 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Is there another easy way to do this?
Left by Ted on Apr 26, 2006 4:37 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Is there another easy way to do this?
Left by Ted on Apr 26, 2006 4:37 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
How to track Enter key pressed from FireFox and opera ?
Left by Surjit on May 11, 2006 10:19 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Hahaha lol.
If you stop Enterclicks, you won't be able to use Enter for anything! It overrides and stops any enterclick. Jeez, think ahead anyone ?
Left by Rico on Jun 26, 2006 6:17 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
My suggestion is use a dummy asp-button with Visible=False, that does nothing on its click event. Attributes Defaultbutton and Focusbutton to this button. Problem solved more or less, there is no other sensible way of stopping postbacks.
Left by Rico on Jun 26, 2006 6:19 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
I translated this helperclass to VB.Net, and i also added support for ALL browsers. Anyone interested may inquire me at: rickard.robin**avancit.se
where ** is @

There is also a workaround regarding DefaultButton and DefaultFocus, where you target an invisible AspButton. Both problems fixed for me at least =)

Btw, this helperclass is not authored by Jawad, it is old and has been around the net for some while.
Left by Rico on Jun 26, 2006 8:15 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...


jkl

Left by j on May 02, 2007 11:02 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
wonderful! works so great! thanks!
Left by Jim on Jul 27, 2007 7:38 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Very Informative.........
ThanX
Left by Anil Veeraghattapu on Feb 22, 2008 1:36 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Oh my God... I see one loser after another asking completely clueless questions. Ok let's don't be so bad - does clueless newbie sound better? Let me explain:

1. Neither document.all[...] nor document.form1.all[...] is supported by FireFox. It should be document.getElementById(...) instead.

2. No it's not as simple as setting a property of the textbox... perhaps it should but knowing a little bit about how web applications work, and what javascript can do in first place is a must before one ever starts developing "applications". Let me clarify: it's not about setting the default button, it's clicking a specific button when you press enter in a specific textbox, in 3 different textboxes you may need to click a different button.

3. No, you cannot use an invisible button (hidden by myButton.Visible = false) because using this approach the no html code will be generated for this button, hence how do you think the browser is supposed to read your mind and figure out what to click. Well, a button with style display="none" is a better guess.

Hope this helps you guys. Excuse my tone, but really before you consider developing something you better know the basics...
Left by nsimeonov on Mar 17, 2008 8:38 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Thank you, with document.getElementById(...) it works in FireFox.
Left by Lord Irvigon on May 02, 2008 3:40 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
As alluded to by Danny, you can use the DefaultButton and DefaultFocus properties of a form. You can also use it for a panel particular panel. Scott Guthrie has a good writeup here:

http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx
Left by Garen Parham on May 02, 2008 4:10 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
We can use this....and it's working.

<script language="javascript">
function checklength()
{
if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) { document.getElementById("btnSubmit").click();
return false;
}
else return true;
}
</script>
Left by Jeevan K Augustin on Jun 03, 2008 12:32 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
suppose if there is any text in textbox on loading of page i want to remove the text on the click of that textbox nad if no text is entered in that text box the orignal text should again be visible.
Left by sourabh mane on Jul 21, 2008 4:51 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
how can we do this is vb.net, can someone guide me please , i need the same functionality but with vb.net , don't we have some kind of textbox properties or button properties by which we can auto click it .
please help me .

Regards
Left by Umar Saeed on Jul 29, 2008 9:11 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Just add

this.form.defaultbutton = button.clientid

to the form_load event. This is a simple solution for it
Left by Jeen on Aug 01, 2008 2:42 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Thanks you da man. Worked as is the first time without any modifications!!
Left by ObamaIsAMarxist on Jan 08, 2009 1:27 PM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
put the textbox in a asp:panel and set its defaultbutton property
Left by wendel on Aug 03, 2009 9:39 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Not working in FF... I ve been searching all over the internet and unable to get this to work, anybody has a good solutions?
Left by Freddy on Feb 10, 2010 11:40 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Thank You "wendel" you made my life so easy, all that utter javascript avoided by your one single suggestion, Thank you!
Left by SoleSupreme on Jun 09, 2010 9:50 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Very good. It works fine! Thank you!
Left by Matheus on Jun 24, 2010 7:39 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
try this:
PS: Html code <div>
<asp:textbox CssClass="textbox" id="txtFirstName" runat="server" MaxLength="100"></asp:textbox>
<asp:LinkButton ForeColor="Blue" runat="server" id="cmdSearch" Text="Search" OnClick="cmdSearch_Click"></asp:LinkButton>
....
<div>
In .cs:
string formName = "form1";
string jsString = "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + cmdSearch.UniqueID + "').focus(); document.getElementById('" + cmdSearch.UniqueID + "').click();return false;}} else {return true}; ";
txtFirstName.Attributes.Add("onkeydown", jsString);

This will work both in firefox and IE but not in safari :-(
Left by radha on Sep 28, 2010 9:30 AM

# re: Enabling Enter Key on a Text Box to auto click a Button ....
Requesting Gravatar...
Awesome! Thank you!
Left by CopyNPaste on Sep 14, 2011 2:36 PM

Your comment:
 (will show your gravatar)
 


Copyright © Jawad Khan | Powered by: GeeksWithBlogs.net | Join free