HTML and CSS Reference
In-Depth Information
The script starts with the declaration of two variables that will be used in the validation
process. The first is an empty array named errors that will be used to store any error
messages associated with invalid fields. The second is called errorMessage , it will store
the error message that will be displayed if the user fails to fill out the form correctly. The
beginning of the error message is in the declaration and before it is displayed, the spe-
cific error messages will be tacked onto it.
If you look at the message, you'll see \n\n at the end. Alert messages are not formatted
using HTML and do include any whitespace that is inside the string. Each \n adds a line
feed in the dialog box. Including the line breaks skips a line between that message and
the individual error messages.
When my variables are all set up, I start validating the contents of the form. First, I vali-
date the name. If it's empty, I add an error message to the errors array using the push()
method, which adds its argument onto the end of the array. Next, I check the gender
field, which also uses the push() method to add a message to errors if no value has
been selected.
After the fields have been validated, it's time to decide whether to display the error mes-
sage. I test the length property of errors . If the array contains any elements, it indicates
that errors were found. In that case, the error message is displayed and the function
returns false so that the form is not submitted. If the array is empty, the form is valid
and submission can proceed. Figure 15.3 shows the full error message.
An alert message
for multiple fields.
Hiding and Showing Elements
One way to help users deal with a lot of information presented on a single page is to hide
some of it when the page loads and to provide controls to let them view the information
that interests them. In this example, I create a frequently asked questions page that dis-
plays all the questions by default but hides the answers to the questions. Users can display
the answers by clicking the corresponding questions.
Search WWH ::

Custom Search