Click here to Skip to main content
Click here to Skip to main content

Capturing the Enter key to cause a button click

By , 19 Jan 2007
 

Sample screenshot

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 button's 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
Web Developer
United States United States
Member
I started my programmer career over 16 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#. Lately I have been using VS2012 and writing a Windows 8 app. You can search for the app it is called ConvertIT.
 
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberogcalyps9 May '13 - 4:36 
Exactly what I wanted
GeneralRe: My vote of 5memberkubben9 May '13 - 7:24 
I am glad you liked the article.
 
Ben
AnswerThanksmemberBartho Bernsmann26 Feb '13 - 19:32 
Thanks a lot man! 10/10
GeneralRe: Thanksmemberkubben27 Feb '13 - 1:56 
Glad you liked the article.
 
Ben
QuestionAbout the postmembertahri jouti2 Jan '13 - 23:14 
Thank you, that was very helpful to me, thanks again Smile | :) !
Questionhimembersravanthigogineni26 Dec '12 - 19:03 
This code is not working in IE and Chrome
AnswerRe: himemberkubben27 Dec '12 - 3:57 
I have this code working in both IE and Chrome.   What part of this code isn't working for you?   The javascript or using the panel default button?
 
Ben
GeneralRe: himembersravanthigogineni27 Dec '12 - 17:31 
Using Java Script was not working
 
<script type="text/javascript">
function doClick(btnLogin, 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(btnLogin);
if (btn != null) { //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</script>
GeneralRe: himemberkubben28 Dec '12 - 3:53 
Ok, so how did you attach that javascript function to a textbox?   I am guessing that is perhaps where your problem is.   You need to add it to the onclick event of the text box that you want.   You also have to make sure the button is named correctly.
 
Are you using visual studio?   If you are, you can put
debugger;
 
In the javascript and visual studio will cause a break point when that gets hit.   This will help you debug your problem.
 
Ben
GeneralMy vote of 5memberBBBwex24 Aug '12 - 7:34 
perfect explanation of the default button setting, in my case I needed it in a webform, but same difference with a panel

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 19 Jan 2007
Article Copyright 2007 by kubben
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid