Click here to Skip to main content
6,822,123 members and growing! (18,240 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate License: The Code Project Open License (CPOL)

Capturing the enter key to cause a button click

By kubben

Have you ever wanted to trap the enter key press event in asp.net and have it click a button for you? This article describes two options for capturing the enter key press event and then clicking a button. One solution uses JavaScript, the other uses a panel control.
Windows, .NET, ASP.NET, Visual-Studio, Dev
Posted:19 Jan 2007
Views:111,066
Bookmarked:32 times
Unedited contribution
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
18 votes for this article.
Popularity: 5.23 Rating: 4.17 out of 5
1 vote, 5.6%
1
1 vote, 5.6%
2
1 vote, 5.6%
3

4
15 votes, 83.3%
5

Introduction

Have you ever wanted to trap the enter key press event in asp.net and have it click a button for you?  This article describes two options for capturing the enter key press event and then clicking a button.  One solution uses JavaScript, the other uses a panel control.

Background

Most people like things to work a certain way.  Consider a search engine text box.  After you type in your search text, most people just want to push the enter key and have the search start.  It is a pain when you have to grab the mouse and move the cursor to the search button and click it.  The article describes two solutions to this problem.

The Problem

Web pages have text boxes, text areas etc. where users enter text.  Often after the text is entered the user needs to click a button.  It may be a search button or a submit button or some other sort of button.  The problem is how to trap the enter key press event so that the correct button can be clicked.

The Solution

Let's explore two solutions to this problem.  First let us look at using JavaScript.  With this solution each textbox needs to have some JavaScript attached to the onKeyPress JavaScript event.  I usually do this in the pageload method in the code behind.

//Add the javascript so we know where we want the enter key press to go

if (!IsPostBack)
  {
   txtboxFirstName.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
   txtboxLastName.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
   txtboxAddress1.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
   txtboxAddress2.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
   txtboxCity.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
   txtboxState.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
   txtboxZipcode.Attributes.Add("onKeyPress", "doClick('" + btnSearch.ClientID + "',event)");
  }

NOTE: you pass into the JavaScript method the buttons ClientID so that the JavaScript method can find the button and call its click method.

Next we need a JavaScript method called doClick in the asp.net form.

<SCRIPT type=text/javascript>
    function doClick(buttonName,e)
    {
//the purpose of this function is to allow the enter key to 

//point to the correct button to click.

        var key;

         if(window.event)
              key = window.event.keyCode;     //IE

         else
              key = e.which;     //firefox

    
        if (key == 13)
        {
            //Get the button the user wants to have clicked

            var btn = document.getElementById(buttonName);
            if (btn != null)
            { //If we find the button click it

                btn.click();
                event.keyCode = 0
            }
        }
   }
    </SCRIPT>

The next solution is using a Panel control. In this case the panel is doing all the work.

<asp:Panel ID="panSearch" runat="server" DefaultButton="btnSearch2" Width="100%" >
    <table width="100%">
    
    <tr>
     <td>First Name</td>
     <td ><asp:TextBox ID="txtboxFirstName2" runat="server" ></asp:TextBox></td>
    </tr>
    ...

Notice that the Panel tag has a property called DefaultButton.  You set this property to the button id of the button you want to be clicked on an enter key press event.  So any text box inside of the panel will direct its enter key press to the button set in the DefaultButton property of the Panel.

Which one is better?

I suppose we could spend a lot of time arguing about which method is better.  Some people like JavaScript so that might be the better one.  Others hate JavaScript and prefer writing less code, so they would choose the Panel solution.  One thing I would note is that if you have several buttons and need to have different text boxes click different buttons then you have to go with the JavaScript solution since it gives you that flexibility.  I guess I will let you decide which solution best fits your needs.

Conclusion

Hopefully this article demonstrates two useful techniques to capture the enter key press event and directing it to click the correct button.  Let me know which method you prefer.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

kubben


Member
I started my programmer career over 13 years ago doing COBOL and SAS on a MVS mainframe. It didn't take long for me to move into windows programming. I started my windows programming in Delphi (Pascal) with a Microsoft SQL server back end. I started working with vb.net when the beta 2 came out in 2001. After spending most of my programming life as a windows programmer I started to check out asp.net in 2004. I achieved my MCSD.net in April 2005. I have done a lot of MS SQL database stuff. I have a lot of experience with Window Service and Web services as well. I spent three years as a consultant programing in C#. I really enjoyed it and found the switch between vb.net and C# to be mostly syntax. In my current position I am programming in both vb.net and C# .net 3.5 framework.

On a personal note I am a born again Christian, if anyone has any questions about what it means to have a right relationship with God or if you have questions about who Jesus Christ is, send me an e-mail. ben.kubicek[at]netzero[dot]com You need to replace the [at] with @ and [dot] with . for the email to work. My relationship with God gives purpose and meaning to my life.
Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 77 (Total in Forum: 77) (Refresh)FirstPrevNext
GeneralNew IE and FF caused error Pinmemberlusman11:01 6 Feb '10  
GeneralRe: New IE and FF caused error Pinmemberkubben14:32 6 Feb '10  
GeneralRe: New IE and FF caused error Pinmemberkubben5:10 7 Feb '10  
GeneralCapturing Enter Key -- Worked very well. Pinmembermeeram39522:40 12 Aug '08  
GeneralRe: Capturing Enter Key -- Worked very well. Pinmemberkubben2:17 13 Aug '08  
GeneralDefault Button Click event on Enter Key PinmembernizB1:42 26 Jun '08  
GeneralRe: Default Button Click event on Enter Key Pinmemberkubben2:43 26 Jun '08  
Generaljavascript newbie help [modified] Pinmemberenhesive6:50 13 May '08  
GeneralRe: javascript newbie help Pinmemberkubben9:58 13 May '08  
GeneralRe: javascript newbie help Pinmemberenhesive10:14 13 May '08  
GeneralRe: javascript newbie help Pinmemberkubben10:22 13 May '08  
GeneralRe: javascript newbie help Pinmemberenhesive11:43 13 May '08  
GeneralRe: javascript newbie help Pinmemberkubben15:14 13 May '08  
QuestionHow about Pocket IE Pinmembermymacryan11:20 14 Nov '07  
AnswerRe: How about Pocket IE Pinmemberkubben13:45 14 Nov '07  
GeneralRe: How about Pocket IE Pinmembermymacryan5:14 15 Nov '07  
GeneralRe: How about Pocket IE Pinmemberkubben5:51 15 Nov '07  
GeneralEASIER CODE Pinmemberstixoffire0:21 16 Jun '07  
GeneralRe: EASIER CODE Pinmemberkubben1:43 16 Jun '07  
AnswerRe: EASIER CODE Pinmemberstixoffire0:37 17 Jun '07  
GeneralRe: EASIER CODE Pinmemberkubben4:09 17 Jun '07  
AnswerRe: EASIER CODE Pinmemberstixoffire19:13 17 Jun '07  
GeneralRe: EASIER CODE PinmemberKowDot17:56 29 Jun '07  
GeneralRe: EASIER CODE Pinmemberstixoffire9:31 2 Jul '07  
GeneralCapture Enter Key Press for log out link button PinmemberVani Kulkarni3:52 21 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 19 Jan 2007
Editor:
Copyright 2007 by kubben
Everything else Copyright © CodeProject, 1999-2010
Web09 | Advertise on the Code Project