Jawad Khan

Jawad's Lodge - The willingness to torture yourself before others is what makes a developer truly a unique breed.
posts - 45, comments - 149, trackbacks - 155

My Links

News

Archives

Post Categories

Image Galleries

Enabling Enter Key on a Text Box to auto click a Button ....

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

 }
}

Print | posted on Sunday, May 15, 2005 2:32 AM | Filed Under [ ASP.NET ]

Feedback

Gravatar

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

Jawad, this works beautifully. Thanks!
7/27/2005 12:56 PM | Danny Crowell
Gravatar

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

Have you tested this with Firefox? I tried it and it failed. Thanks.
7/27/2005 1:42 PM | Danny Crowell
Gravatar

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

Isn't this the same as simply entering OnTextChanged="btnFindPtr_Click" on your ASP.NET textbox control?
7/31/2005 12:32 PM | Travis
Gravatar

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

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
7/31/2005 10:55 PM | donna k stokes
Gravatar

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

This seems best and easiest

<form id="Form1" method="post" runat="server" onKeyPress="if(event.keyCode==13) {document.getElementById('btnSearch').click(); return false;}">
8/8/2005 9:59 AM | Wilson
Gravatar

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

Jawade sahab ur code is nice for ASP.Net but i wnat this thing in ASP.Will u help me.
shaileshraj2005@rediffmail.com
12/28/2005 4:31 AM | Shailesh
Gravatar

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

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">
1/6/2006 9:31 AM | Danny Crowell
Gravatar

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

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.
2/1/2006 3:57 PM | Mr_CPP
Gravatar

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

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.
2/1/2006 4:25 PM | Mr_CPP
Gravatar

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

How do I prevent post back when an enter key is pressed without using javascript
Thanks!
3/3/2006 11:55 PM | Arun
Gravatar

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

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
3/5/2006 7:02 AM | Jawad Khan
Gravatar

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

Is there another easy way to do this?
4/26/2006 4:37 AM | Ted
Gravatar

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

Is there another easy way to do this?
4/26/2006 4:37 AM | Ted
Gravatar

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

How to track Enter key pressed from FireFox and opera ?
5/11/2006 10:19 PM | Surjit
Gravatar

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

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 ?
6/26/2006 6:17 AM | Rico
Gravatar

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

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.
6/26/2006 6:19 AM | Rico
Gravatar

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

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.
6/26/2006 8:15 AM | Rico
Gravatar

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



jkl

5/2/2007 11:02 AM | j
Gravatar

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

wonderful! works so great! thanks!
7/27/2007 7:38 PM | Jim
Gravatar

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

Very Informative.........
ThanX
2/22/2008 1:36 AM | Anil Veeraghattapu
Gravatar

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

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...
3/17/2008 8:38 PM | nsimeonov
Gravatar

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

Thank you, with document.getElementById(...) it works in FireFox.
5/2/2008 3:40 AM | Lord Irvigon
Gravatar

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

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
5/2/2008 4:10 PM | Garen Parham
Gravatar

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

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>
6/3/2008 12:32 AM | Jeevan K Augustin
Gravatar

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

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.
7/21/2008 4:51 AM | sourabh mane
Gravatar

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

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
7/29/2008 9:11 AM | Umar Saeed
Gravatar

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

Just add

this.form.defaultbutton = button.clientid

to the form_load event. This is a simple solution for it
8/1/2008 2:42 AM | Jeen
Gravatar

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

Thanks you da man. Worked as is the first time without any modifications!!
1/8/2009 1:27 PM | ObamaIsAMarxist
Gravatar

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

put the textbox in a asp:panel and set its defaultbutton property
8/3/2009 9:39 AM | wendel
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: