Sunday, June 12, 2005

Scott Mitchell: Enter and the Button Click Event

Of particular interest to ASP.NET developers, though, is that when creating an ASP.NET Web Form hitting Enter to submit the form seemingly sometimes causes the page's Button Web control's Click event to fire, and other times not. In this short article we'll see under what conditions a Button Web control's Click event might not fire when the user submits the page hitting Enter; furthermore, we'll look at a workaround.

A lenyeg:
The issue centers around the way that Internet Explorer posts back the form's controls when hitting enter in a form with only one single-line textbox. Specifically, Internet Explorer does not include the submit button's name/value pair in the post body. Since the submit button's name/value pair is not sent back, the ASP.NET engine cannot determine what induced the postback and therefore can't raise the appropriate Button Web control's Click event.
...
Without the information as to what button caused the postback, the ASP.NET engine cannot raise the corresponding button's Click event. Hence, if you have a Web Form with just one single-line text input (even if there are additional input fields, like CheckBoxLists, RadioButtonLists, DropDownLists, and so on), hitting enter in the text input will not cause the Button Web control's Click event to fire when using Internet Explorer - other browsers, such as FireFox, always send back the button's name/value pair, even if there is only one text input.

For additional information about Enter and form submission, as well as JavaScript techniques for disabling submissions via Enter and ensuring submissions via Enter (for older browsers), be sure to check out the following articles:
FORM submission and the ENTER key?
Using JavaScript to prevent or trigger form submission when ENTER is hit
FAQs relating to 'Pressing Enter Key for Form Submission'