Setting the default Button for a TextBox in ASP.NET - Raj Kaimal

Setting the default Button for a TextBox in ASP.NET

This entry was posted in 2003. There are better ways to do this with the newest version of ASP.net!

Hitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being “clicked“. The method described below allows you to specify a default Button to submit when the user hits the enter key in a TextBox.

When you press a key on your keyboard, the js OnKeyPress event is fired. This calls a function to which we pass the id of the button associated with the TextBox. The function gets a reference to the button and simuilates a mouse-click on the Button. We perform a browser detection because IE and Netscape have different event models. The function finally returns false so that the keypress event is cancelled (otherwise a second form submit will be raised). This works with newer versions of IE/Netscape.

function clickButton(e, buttonid){

      var evt = e ? e : window.event;

      var bt = document.getElementById(buttonid);

      if (bt){

          if (evt.keyCode == 13){

                bt.click();

                return false;

          }

      }

}


//code behind
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");

The code behind generates the following code:

<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')"  />

This causes web control Button1 to be clicked when the enter key is hit inside TextBox1.

Published Thursday, December 11, 2003 10:41 PM by rajbk
Filed under:

Comments

# re: Setting default Buttons for a textbox.

What is the event you are sending to the script as a parameter?

Thanks

Saturday, May 15, 2004 9:40 AM by David

# re: Setting default Buttons for a textbox.

When an "Event" occurs, as a result of the keyboard keypress(in this case), the browser generates an event object which contains information about the event that occurred. We are passing this event in our event handler "onkeypress".

You might want to do a search on the javascript "event model".

Sunday, May 16, 2004 1:03 AM by rajbk

# re: Setting the default Button for a TextBox in ASP.NET

This code is brilliant. It has saved me a lot of hassle. Many thanks for all your help!!!

Friday, May 28, 2004 9:51 AM by Ricky

# re: Setting the default Button for a TextBox in ASP.NET

Great piece of code!!!
Got exactly what I needed, CHEERS!

Tuesday, June 1, 2004 11:02 PM by Decio Novaes

# re: Setting the default Button for a TextBox in ASP.NET

Gr8. i was seraching for this. Thanks

Wednesday, June 9, 2004 5:33 AM by Murugesan

# re: Setting the default Button for a TextBox in ASP.NET

worked great! Thanks.

Saturday, June 12, 2004 12:32 PM by JPN

# re: Setting the default Button for a TextBox in ASP.NET

nice work man, this was what i needed. i like how you made it so easy to implement into my program

Thursday, June 17, 2004 11:56 AM by J

# re: Setting the default Button for a TextBox in ASP.NET

Cheers bro, sweet code

Thursday, July 1, 2004 4:24 AM by Nikolai

# re: Setting the default Button for a TextBox in ASP.NET

This is great, thank you very much.

Wednesday, July 14, 2004 3:16 AM by Ali Ibrahim

# re: Setting the default Button for a TextBox in ASP.NET

Wonderful piece of code!!! Thanx

Wednesday, July 14, 2004 8:41 PM by mvp

# re: Setting the default Button for a TextBox in ASP.NET

This helped me a lot. I was looking for a similar functionality. Thanks a lot.

Thursday, July 15, 2004 7:11 AM by sudhakar

# re: Setting the default Button for a TextBox in ASP.NET

Just thrilled to find a solution this concise. Thanks a gig

Wednesday, July 21, 2004 5:43 PM by Eric Hackett

# re: Setting the default Button for a TextBox in ASP.NET

SSSSSSSSSSSuperb ! ........... 1Million thanks!

Tuesday, August 3, 2004 1:31 AM by Kelvin

# re: Setting the default Button for a TextBox in ASP.NET

U DA MAN! That was too easy. What am I going to do for the rest of the morning????

Tuesday, August 3, 2004 8:29 AM by Scott Pro

# re: Setting the default Button for a TextBox in ASP.NET

Great solution - thanks for saving me quite a lot of time!

Thursday, August 5, 2004 11:45 AM by rf

# re: Setting the default Button for a TextBox in ASP.NET

hi this works great ! Thanking you

Wednesday, August 16, 2006 6:32 AM by pierce

# re: Setting the default Button for a TextBox in ASP.NET

Superb.. Just For my first serach I Get this Solution. Thanks a Lot..

Friday, September 22, 2006 12:51 AM by Manimaran

# re: Setting the default Button for a TextBox in ASP.NET

Hay man. This was great. Works fine. Saved a lot of my time

Sunday, October 22, 2006 1:31 PM by Kumudu

# re: Setting the default Button for a TextBox in ASP.NET

kudos!made my work easier! tnx

Thursday, November 23, 2006 2:15 AM by Mr.C

# re: Setting the default Button for a TextBox in ASP.NET

your article is very nice,

but i have one doubt,

i am taking one textBox and DataGrid. i want to fill DataGrid while typing the letter (KeyPress-Event).the coding is as follows

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

  Dim con As New SqlConnection("server=localhost;uid=sa;pwd=;DataBase=EMP")

   Dim com As SqlCommand

   Dim Ds As DataSet

   Dim Da As SqlDataAdapter

     com = New SqlCommand("SELECT * FROM EMPLOYEE ", con)

       Ds = New DataSet

       Da = New SqlDataAdapter(com)

       Da.Fill(Ds, "EMPLOYEE")

       DataGrid1.DataSource = Ds

       DataGrid1.DataBind()

       con.Close()

  End Sub

 

Thursday, December 14, 2006 6:05 AM by Ancilla

# re: Setting the default Button for a TextBox in ASP.NET

It works like butter...so cool..

Monday, December 18, 2006 2:32 PM by Rajesh

# re: Setting the default Button for a TextBox in ASP.NET

hi

One doubt ur code

if (typeof bt == 'object')

the above code 'object' mean ?

Venkat

Saturday, March 3, 2007 5:21 AM by Venkatesan

# re: Setting the default Button for a TextBox in ASP.NET

Venkat, the typeof operator is not needed. I have changed the code. typof is used to return the type of the unevaluated operand.

Saturday, March 3, 2007 6:02 PM by rajbk

# re: Setting the default Button for a TextBox in ASP.NET

Thanks. i was seraching for this

Thursday, March 15, 2007 9:38 PM by Anu

# re: Setting the default Button for a TextBox in ASP.NET

Hi,

You saved me a Day. Your code was really helpful.

Raja

Thursday, March 29, 2007 5:14 AM by Raja

# re: Setting the default Button for a TextBox in ASP.NET

It's soooooooo goooooood!

thanks for your helpful code.

Friday, April 6, 2007 1:50 AM by Barnabas Kim

# re: Setting the default Button for a TextBox in ASP.NET

Do you know how to call a server side procedure when user press enter in a textbox?

Thursday, April 12, 2007 1:12 AM by chronos

# re: Setting the default Button for a TextBox in ASP.NET

Very good and thank a lot for this script.

I From Thailand.

Tuesday, May 8, 2007 12:11 AM by joker

# Setting the default Button for a TextBox in ASP.NET

Thanks , This Helped me also

RAJ GUJAR

Thursday, May 10, 2007 3:25 PM by RAJ Gujar

# re: Setting the default Button for a TextBox in ASP.NET

Thank's very very much for sharing ur knowlegde

with us! that's a brilliant 'n easy to pick

code.God bless u !

Wednesday, May 30, 2007 5:05 PM by harsh

# re: Setting the default Button for a TextBox in ASP.NET

Funtastic peace of code, help me a lot!

Thanks man

Friday, June 15, 2007 9:41 AM by Johnny

# re: Setting the default Button for a TextBox in ASP.NET

Thanks. Just what was needed. Nice concise code too.

Wednesday, June 20, 2007 10:33 AM by Brendan

# re: Setting the default Button for a TextBox in ASP.NET

Saved me lots of time. Thanks a bunch!

Monday, June 25, 2007 2:04 PM by Tom Nicholas

# re: Setting the default Button for a TextBox in ASP.NET

Thanks, thanks, thanks. Straight to the point

Tuesday, June 26, 2007 9:44 AM by Charles

# re: Setting the default Button for a TextBox in ASP.NET

Thanks Really Really A Lot!!

This is a much easier solution then the other article's posting!!

Very Clean and easy to understand, A Real Live Saver!

Friday, June 29, 2007 11:34 AM by Lucy

# re: Setting the default Button for a TextBox in ASP.NET

Hi all.  The solution posted by Raj is great and very granular.  Allows for a lot of control for the developer.

An easier solution, however, was provided by the Focus API in ASP.NET 2.0 which for most scenarios works well.

It consists on adding properties to the FORM tag in ASP.NET.  The defaultbutton and the defaultFocus attributes allow you to name the controls that should perform those functions.

As an example : <form id="form1" runat="server"

         defaultbutton="button_name" defaultfocus="control_name">

Saturday, July 7, 2007 4:50 PM by Carlos Guevara

# re: Setting the default Button for a TextBox in ASP.NET

Carlos,

What you have mentioned is useful when you want to set a default button for a given page. This, AFAIK, will not work if you want a different button to be clicked based on the textbox that the focus is on. ie. say you have five buttons and five textboxes; you want a certain button to be clicked based on the textbox currently in focus.

Raj

Monday, July 9, 2007 10:05 AM by rajbk

# re: Setting the default Button for a TextBox in ASP.NET

I am new to Asp.net, it doesnt work for me. I added some code to my button1.click(), but it doesnt go there at all. Any help is appreciated. thanks.

Friday, July 13, 2007 6:11 PM by B

# re: Setting the default Button for a TextBox in ASP.NET

this is cool but needs to add event to all the textboxes...can't we call this function like on PostBack..something like this

Friday, July 20, 2007 3:20 AM by Amit

# re: Setting the default Button for a TextBox in ASP.NET

This is great.  I managed to set up 2 text boxes each with it's own default button.

Excellent, thanks.

Wednesday, July 25, 2007 5:18 AM by Batman

# re: Setting the default Button for a TextBox in ASP.NET

I previously, used a function in aspx file; but that not work in ascx file.

This sample work everywhere!

Thanks, a lot.

Wednesday, August 1, 2007 8:47 AM by birgin

# re: Setting the default Button for a TextBox in ASP.NET

perfect!!! thanks a lot

Friday, August 3, 2007 11:32 AM by maurete

# re: Setting the default Button for a TextBox in ASP.NET

Excellence! Short and sweet and WORKING!

Tuesday, August 21, 2007 2:49 AM by FiRe87

# re: Setting the default Button for a TextBox in ASP.NET

This solution is simple and great. But when I put this in the modalpopupextender, it doesn't work any more. it will still go fire the default button in the main page, not the one I set in the javascript. If I add this line: alter('test'); after the bt.click(), it works as expected.

Can you please help me figure out the reason? Thanks a lot!!!

Wednesday, August 22, 2007 11:19 AM by MiaF

# re: Setting the default Button for a TextBox in ASP.NET

This one works great.

I am using this at my site

Saturday, August 25, 2007 4:52 AM by Handy Chang

# re: Setting the default Button for a TextBox in ASP.NET

You are the Don --- This code is awesome -- An elegant solution that got me out of a fix.

Friday, August 31, 2007 2:51 PM by Andy

# re: Setting the default Button for a TextBox in ASP.NET

OUTSTANDING!  

Thank you!!

Saturday, September 1, 2007 2:47 PM by Robert Fidler

# re: Setting the default Button for a TextBox in ASP.NET

Great piece of code !! Fabulous..Elegant and simply outstanding...AND IT WORKS !!!!

Sunday, September 2, 2007 6:42 PM by Maya Mathew

# re: Setting the default Button for a TextBox in ASP.NET

thanks. very usefull

Thursday, September 6, 2007 3:31 AM by asmvax

# re: Setting the default Button for a TextBox in ASP.NET

thanks alot my friend

Tuesday, September 11, 2007 7:43 AM by doruk türkoğlu

# re: Setting the default Button for a TextBox in ASP.NET

Thanks for sharing!  Great code snippet!

Sunday, September 16, 2007 12:25 AM by Shawn Dorman

# re: Setting the default Button for a TextBox in ASP.NET

Thank you, very much !

Monday, September 17, 2007 10:40 AM by Anonymous

# re: Setting the default Button for a TextBox in ASP.NET

Thanks alot, worked a treat..

Wednesday, September 19, 2007 3:08 AM by Richard

# re: Setting the default Button for a TextBox in ASP.NET

hi,

Nice article :)

Thanks a lot

Wednesday, September 26, 2007 6:09 AM by deepa

# re: Setting the default Button for a TextBox in ASP.NET

Its really good, and working fine, thanks buddy hope in future we will see some more useful article on your blogsite.Thank you.

Thursday, October 11, 2007 5:26 AM by vikas

# re: Setting the default Button for a TextBox in ASP.NET

superb guys, saved a lot of time. for this i wasted half of the day, finally i got this.

Thank You very much

Friday, October 12, 2007 9:24 AM by Rajesh

# re: Setting the default Button for a TextBox in ASP.NET

good a thank you very much

Wednesday, November 7, 2007 1:48 PM by getmore

# re: Setting the default Button for a TextBox in ASP.NET

You made my day. thans a lot for the support.

Wednesday, November 28, 2007 3:31 AM by Magi

# re: Setting the default Button for a TextBox in ASP.NET

Thanks for this page, you are the greatest!

Wednesday, December 5, 2007 9:35 AM by Dragoljub

# re: Setting the default Button for a TextBox in ASP.NET

Working fine in IE6 or 7 but not properly working in Mozilla, for example when i starts with letter 'a' in textbox we will have the related words starts with 'a' but when i selects any of the word starts with 'a' from list showing below than it's not working.

Thursday, January 17, 2008 1:55 AM by Sachin

# re: Setting the default Button for a TextBox in ASP.NET

I have to strongly agreee with the majority here.

This is a simple but brilliant piece of code.

rajbk... you da mann...

Wednesday, February 20, 2008 8:35 PM by nitidomaster

# re: Setting the default Button for a TextBox in ASP.NET

this is called perfection... small and nice...

Saturday, March 1, 2008 6:37 AM by prashant

# re: Setting the default Button for a TextBox in ASP.NET

Neat small piece of code.

You can also achieve the same using the DefaultButton property of the form.

In case of master pages, use a <asp:Panel /> in the child page and set the DefaultButton property

<asp:Panel ID="Panel_Content" runat="server" DefaultButton="Button_Calculate">

.

.

.

.

</asp:Panel>

Sunday, March 2, 2008 1:24 AM by vaionline

# re: Setting the default Button for a TextBox in ASP.NET

Viaonline,

The DefaultButton method allows you to specify only one button per form or panel. The code I posted allows you to specify a button for each textarea. This can be used on forms or panels that have multiple buttons.

Raj

Sunday, March 2, 2008 10:28 AM by rajbk

# re: Setting the default Button for a TextBox in ASP.NET

this is an excellent tutorial and definitely life and time saver.

thnx

Wednesday, March 26, 2008 1:54 AM by Atif Ali Bhatti

# re: Setting the default Button for a TextBox in ASP.NET

It helps me a LOT Buddy.

Tuesday, April 15, 2008 1:24 AM by vivek

# re: Setting the default Button for a TextBox in ASP.NET

Thanks a Million, you have a perfect way of writing things in an easy way.

Monday, May 12, 2008 2:25 AM by Hooman (Iran)

# re: Setting the default Button for a TextBox in ASP.NET

Oh diossss. Por fin una solucion!. GRACIAS GRACIAS THANK YOU. 2h intentando hacer esto!.

Saludos Regards

Wednesday, May 21, 2008 6:16 PM by Sifri Garcia

# re: Setting the default Button for a TextBox in ASP.NET

try this txtABC.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('"+btnSubmit.UniqueID+"').click();return false;}} else {return true}; ");

Tuesday, May 27, 2008 12:24 PM by CreativeMind

# re: Setting the default Button for a TextBox in ASP.NET

This is Superb....

Thank You very much Sir.

Tuesday, June 10, 2008 9:31 AM by Sagar

# re: Setting the default Button for a TextBox in ASP.NET

Great work mate !!!

was searching for almost 2 days too good

thanks well done

Thursday, June 12, 2008 11:17 PM by putta

# re: Setting the default Button for a TextBox in ASP.NET

Hi, This code is not working in mozilla if the controls are inside an update panel

Monday, June 16, 2008 5:22 AM by Nizar

# re: Setting the default Button for a TextBox in ASP.NET

Thanks for this usefull code i have used this,

one question what if user have say 10 to 20 text control and he has to use same code behind code to register the event, why not use the Page level ?,

Friday, August 8, 2008 1:04 AM by Asim Sajjad

# re: Setting the default Button for a TextBox in ASP.NET

WOW bro, you rock !!

Thanks for making it public dude. :-)

Thursday, September 11, 2008 6:12 AM by Fawad

# re: Setting the default Button for a TextBox in ASP.NET

Thanks for your code. It works nice for me.

Thursday, October 2, 2008 2:31 AM by gary

# re: Setting the default Button for a TextBox in ASP.NET

If possible, I would recommend this method:

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

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

   <asp:Button ID="Button1" runat="server" OnClick="Method()" />

</asp:Panel>

Thursday, October 2, 2008 5:24 AM by Emil

# re: Setting the default Button for a TextBox in ASP.NET

nice work it help me alot  

Wednesday, October 22, 2008 3:21 AM by asp .net user

# re: Setting the default Button for a TextBox in ASP.NET

Fantastic piece of code...thanks a lot

Monday, November 3, 2008 2:19 PM by Rajesh

# re: Setting the default Button for a TextBox in ASP.NET

Excellent. In fact is searched in asp.net forums and could only witness the solution that keep the textbox and button in a panel and set the default button. But this one is far better in speed and simplicity also. Thank you again!

Wednesday, December 31, 2008 3:17 AM by sangam

# re: Setting the default Button for a TextBox in ASP.NET

really nice work..

thankss alot sir.

Thursday, January 1, 2009 6:49 AM by Muhammad Tabish

# re: Setting the default Button for a TextBox in ASP.NET

Excelente.

Saludos desde Peru.

Monday, February 16, 2009 10:46 AM by Henry

# re: Setting the default Button for a TextBox in ASP.NET

This is a bunch of incomprehensible garbage! This stuff works only if you're already a very fluent programmer. I'm writing my first website in very clean, plain, basic html and css. None of this stuff makes sense! Why can't you provide a very simple, step by step method that uses an actual example? I don't know whether I'm supposed to replace these little codes such as "buttonid" with the name of my button or leave it as such, etc. It's too complicated for a beginner!

dt263@yahoo.com

Thursday, March 5, 2009 3:19 PM by DT

# re: Setting the default Button for a TextBox in ASP.NET

Simply the best. Thanks a lot......

Tuesday, March 10, 2009 7:47 AM by Renjith.K.C

# re: Setting the default Button for a TextBox in ASP.NET

Thanks a lot, thats helped me lot.

Wednesday, March 25, 2009 6:19 AM by Raj

# re: Setting the default Button for a TextBox in ASP.NET

This is quite an elegant solution.

However, if i recall correctly, not all browsers support calling click() on a button (or was that for hyperlinks only?). Either way, you might want to do something along the lines of

if( bt.click)

   bt.click();

else if(bt.onclick)

   t.onclick();

Also, as an alternative, if the number of "submitting textboxes" is few, you might want to consider setting AutoPostBack=true on the textbox and also setting OnTextChanged handler to the same eventhandler as your button control. That way you can still distinguish between a button click and a textbox enter on the server side (by checking the sender's type).

Thursday, May 21, 2009 8:20 AM by Dimitri

# re: Setting the default Button for a TextBox in ASP.NET

Al fin encontre un ejemplo adecuado a mis necesidades, con este si me funciono, ya que tenia otro evento en esa caja de texto y no me funcionaba.

Gracias.

Wednesday, July 1, 2009 3:52 PM by Jazitron

# re: Setting the default Button for a TextBox in ASP.NET

its too good....straight fit in...

works wonderfully....

Gr8 piece of work...

Sunday, May 16, 2010 2:26 AM by seema

# re: Setting the default Button for a TextBox in ASP.NET

Great post ! It saved my tons of time . Thanks

Sunday, June 6, 2010 2:52 AM by Sachin Kumar

# re: Setting the default Button for a TextBox in ASP.NET

Good its working. Thanks.

Thursday, June 10, 2010 7:26 AM by Ozair Sarwar

# re: Setting the default Button for a TextBox in ASP.NET

so easy, that's what I searched.

-----

Sunday, June 13, 2010 6:35 AM by safi

# re: Setting the default Button for a TextBox in ASP.NET

Code is awesome. It worked perfectly. But focus moves to some other control. Is there any way i can keep the focus on same text box.

Thursday, June 24, 2010 2:50 PM by Nadeem

# re: Setting the default Button for a TextBox in ASP.NET

Guys simplest way (if applicable in your application) is to keep the button, which you want to be default in that page, on left hand side.

Thursday, July 8, 2010 4:38 AM by ANki

# re: Setting the default Button for a TextBox in ASP.NET

Thanks a lottttttttttttttttt

Tuesday, July 13, 2010 8:49 AM by Ganesh

# re: Setting the default Button for a TextBox in ASP.NET

Thanks a lot.

Wednesday, July 21, 2010 3:53 AM by shyam.p.shinde

# re: Setting the default Button for a TextBox in ASP.NET

great work.good coding

Friday, October 8, 2010 9:16 AM by kishore.G

# re: Setting the default Button for a TextBox in ASP.NET

Marvellous piece of code I love it... so elegant too.

Nice one mate!

Wednesday, October 20, 2010 6:43 AM by Etienne