3.1. Using the Enter Key to Submit a Form

Problem

Ordinarily, a user must click on the Submit button of a form in order to send information entered by a user to a server. You want to use the Enter key for this purpose as well.

Solution

Write some code that generates a client script that captures the keypress event of the browser document object and then checks each keystroke for the Enter key.

In the .aspx file, add id and runat attributes to the body element so that the tag’s contents can be accessed (and modified) in the code-behind:

<body id="pageBody" runat="server"

      leftmargin="0" marginheight="0" marginwidth="0" topmargin="0">

In the code-behind class for the page, use the .NET language of your choice to:

  1. Call the Add method of the pageBody object’s Attributes collection to add the onload attribute to the pageBody control, which causes the captureKeyPress (or equivalently named) client-side script function to be called when the page is first loaded. Your goal is to have HTML like this sent to the browser:

    <body id="pageBody" leftmargin="0" marginheight="0" marginwidth="0" 
          topmargin="0"
    onload="captureKeyPress( );">
  2. Build a string containing the client-side JavaScript that is to be executed when the page is loaded and that causes it to be output as part of the rendered page. The client-side script must capture the keypress event in the browser, check to see if the key pressed is the Enter key, and perform the form submittal, as the following JavaScript does:

    <script language='javascript'> ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.