Thursday, April 4, 2013

Capturing the Enter key to cause a button click


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.

if (!IsPostBack)
{
   txtboxFirstName.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.

 Collapse | Copy Code
<asp:Panel ID="panSearch" runat="server"
       DefaultButton="btnSearch" Width="100%" >
    <table width="100%">
   
    <tr>
     <td>First Name</td>
     <td ><asp:TextBox ID="txtboxFirstName"
           runat="server" ></asp:TextBox></td>
    </tr>
    ...

0 comments:

Post a Comment