3.2. Using the Enter Key to Submit a Form After Validation
Problem
You want to use the Enter key to submit the information entered by a user to the server, but your form uses client-side validation that must be performed before the form is submitted.
Solution
Write code that generates some JavaScript that captures the
keypress
event in the browser, checks to see if
the key pressed is the Enter key, performs the client-side
validation, and then submits the form.
In the .aspx
file, add id
and
runat
attributes to the body
element so that all 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:
Call the
Add
method of thepageBody
object’s Attributes collection to add theonload
attribute to thepageBody
control, which causes thecaptureKeyPress
(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( );">
Build a string containing the client-side JavaScript that is to be executed when the page is loaded and 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, perform the client-side ...
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.