Web Development Blog

ASP.NET submit form when pressing enter key

Often on the web I need to register on a website or fill out some sort of form. After I fill out all the details I press enter expecting the form to submit and save my details or take some action, but the page submits and nothing happens, then I grab my mouse and click on the submit button.

It is commonly known that with ASP.NET, when pressing the enter key the page will submit but not fire the event attached to the submit button.

So what can you do about this?

The solution depends on the version of ASP.NET you use

One approach suggested is to create a javascript function and attach it to the textbox's onkeypress event. You need to use this approach if you are still working on ASP.NET 1.1 or 1.0 code.

Below is some code that will do this for you.

function trapSubmit(id,event){
    if (document.all){
         if (event.keyCode == 13){
             event.returnValue=false;
             event.cancel = true;
              if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate())
              {
                   __doPostBack(id,'');
              }
         }
    }
    else if (document.getElementById){
         if (event.which == 13){
              event.returnValue=false;
             event.cancel = true;
              if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate())
              {
                   __doPostBack(id,'');
              }
         }
    }
    else if(document.layers){
         if(event.which == 13){
              event.returnValue=false;
              event.cancel = true;
              if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate())
              {
                   __doPostBack(id,'');
              }
         }
    }
}

I only recently discovered a much better to do this using the Panel property DefaultButton. This is feature was new in ASP.NET 2.0. Using the Panel's DefaultButton property you can nest all your form controls in a Panel and set the default button action. This works great and is results in much less html.

ASP.NET creates the following javascript on the rendered div.

onkeypress="javascript:return WebForm_FireDefaultButton(event, 'Button')"

If you have a single textbox and want to avoid adding a Panel control you can simply attach this javascript your textbox's onkeypress event.

The javascript function fires the buttons onclick event, one problem here is if your default button is a LinkButton rather than a Button control in firefox the buttons submit javascript is rendered in the links href and because of this the default action is not fired.