HTML and CSS Reference
In-Depth Information
Testing For Required Fields
The form has three required fields: Name, Gender,
and Operating System. The validation function is responsible for checking that they each
contain a value. The
name
field is a text input field. Here's the markup for the field:
<input name=”name” type=”text” />
You use this name to reference the field as a child of
thisform
. The field
name
can be referenced as
thisform.name
, and its contents can be referenced as
thisform.name.value
.
Using this information and an
if
statement, you can test the contents of
name
to see
whether a name has been entered:
if (!thisform.name.value) {
alert(“You must enter a name.”);
return false;
}
The expression in the
if
statement evaluates the value of the form field in a Boolean
context. So if the field's value is null or an empty string, the expression will be false. In
that case, the function displays an error message and prevents the form from being sub-
mitted.
If the name is valid, the next step is to validate the gender radio button group. Validation
of these fields differs slightly because radio button groups consist of multiple fields with
the same name. So in this case,
thisform.gender
will return an array, and we'll use a
loop to iterate over each element in the array and make sure one of the buttons is
selected. For radio buttons, the
value
property is the same as the
value
attribute of the
form field. The
checked
property, a Boolean value, indicates whether the button is
selected.
To test whether one of the
gender
radio buttons has been selected, declare a new variable
called
selected
and give it a value of
false
. Then loop through all the radio buttons
using a
for
loop; if the
checked
property of any radio button is
true
, set
selected =
true
. Finally, if
selected
is still
false
after you've tested each of the radio buttons, dis-
play an
alert()
message and exit the function by calling
return false
. The code
required to perform these tests is shown here:
var selected = false;
for (var i = 0; i < thisform.gender.length; i++) {
if (thisform.gender[i].checked) {
selected = true;
}
}