Saturday, September 15, 2007

Enter Key Default Submit Button

Enter Key functionality is handled a little differently when it comes to ASP.NET. 
 
If there is a single button then it is straight forward because that button is the only button and thus the default button; however, if there are two or more buttons then it uses the first button as the default button.
 
ASP.NET 2.0 introduces a work around for this by simply specifying the defaultbutton property to the ID of the <asp:Button> whose event you want to fire.
 
The defaultbutton property can be specified in the <form> tag as well as in the <asp:panel> tag. The form level setting is overridden when specified at the panel level, for those controls that are inside the panel.
 
If for some reason handling this at the form level or panel level doesn't fit with how you have things setup, you can still use some simple JavaScript techniques to accomplish this.
 
Take this JavaScript function for example, which also utilizes another custom FindControl function.
 
function Submit(e, ButtonName)
{
    
var KeyCode = (window.event) ? event.keyCode : e.which;
     var KeyChar = (window.event) ? String.fromCharCode(event.keyCode) : String.fromCharCode(e.which);

    
if (KeyCode == 13)
    
{
         
var btnSubmit = FindControl(ButtonName, "input");
         
          if(btnSubmit != null)
         
{
              
btnSubmit.click();
          
}
 
          if (window.event)
          {
               window.event.returnValue = false;
          }
         
else
         
{
              
e.preventDefault();
          
}
     }
}
 
Now for any control on your page you can specify which button you want "clicked" when the ENTER key is pressed while that control has focus like so:
 
<asp:TextBox ID="txtTest" onkeypress="Submit(event, 'btnSubmit')" runat="server" />
 
This has been tested in IE and Firefox.

0 comments: