HTML and CSS Reference
In-Depth Information
14.9 Form Handling
As you discovered in Chapter 9, the data from a Web form can be submitted to a CGI
or a server-side script. This data can be added to a database or used for some other
purpose; therefore, it is important that the data submitted by a user is as accurate as
possible. When the user enters information in a form, there is always a chance that the
information will be incorrect or inaccurate. This is particularly true when text input
boxes are used, since the user can easily mistype data. Often, the form data is checked
for invalid data before it is submitted. Form data validation can be done by the server-
side script, but it can also be done client-side, using JavaScript. Again, this topic is sim-
plified here, but we can get a sense of how this might be done.
When the user clicks the form's submit button, the submit event occurs. We can make
use of the onsubmit event handler to call a function that tests form data for validation.
This technique is referred to as form handling . The Web developer can validate all form
inputs, some inputs, or just one form input. The following list is a selection of some
types of things that might be validated:
Required fields such as name and e-mail addresses
A required check box to acknowledge a license agreement
A radio button indicating method of payment or delivery option
A quantity entered that is numeric and within a particular range
When the user clicks the submit button, the onsubmit event handler calls a function
that tests all of the appropriate form elements for valid data. Then the validation func-
tion confirms that the data is valid ( true ) or not valid ( false ). The form is submitted
to the URL indicated in the <form> action if the data is valid ( true ). The form would
not be submitted if the data is not valid ( false ) and some indication to the user regard-
ing errors would be displayed. The overall structure of the Web page code related to
declaring the function and handling the onsubmit event follows:
... XHTML begins the Web page
function validateForm()
{
... JavaScript commands to test form data go here
if form data is valid
return true
else
return false
}
... XHTML continues
<form method="post" action="URL" onsubmit="return validateForm( );">
... form elements go here
<input type="submit" value="submit form" />
</form>
... XHTML continues
There is a new concept with regard to functions indicated here. A function can encapsu-
late a group of statements, but it can also send a value back to where it was called. This
is referred to as “returning a value” and the JavaScript keyword return is used in the
 
Search WWH ::




Custom Search