Java Reference
In-Depth Information
Here, you also define a
<meter/>
element with an
id
of
speedMeter
. This meter is supposed to visually
represent highway speed in miles per hour. In such cases, 55MPH is slow, 75MPH is optimum/
standard, and 90MPH is high. The maximum value this meter can display is 120.
The last field is another text box for the driver's vehicle:
<p>
<label for="vehicle">Vehicle Type: </label>
<input type="text" id="vehicle" name="vehicle" />
</p>
Then after the form, you define a
<progress/>
element:
<p>
Form Completion Progress:
<progress id="completionProgress" max="3" value="0"></progress>
</p>
This is to track the user's progress in filling out the form. It has an
id
of
completionProgress
and has
a maximum value of
3
because it contains three fields.
Of course, the HTML by itself isn't very interesting; so, let's look at the JavaScript. You first retrieve
three elements from the document: the
<form/>
,
<progress/>
, and
<meter/>
elements.
var myForm = document.form1;
var completionProgress = document.getElementById("completionProgress");
var speedMeter = document.getElementById("speedMeter");
To retrieve the
<progress/>
and
<meter/>
elements, you use
document.getElementById()
because
although these two elements are considered form controls, you cannot access them through the form
hierarchy (which admittedly can be a little confusing).
Once again, the form's
input
event provides the magic for this example; so, you register its listener:
myForm.addEventListener("input", formInputChange);
The
formInputChange()
function is rather simple; it updates the values of both the
<progress/>
and
<meter/>
elements:
function formInputChange() {
completionProgress.value = countFieldData();
speedMeter.value = myForm.speed.value;
}
The value for
speedMeter
comes from the
speed
field in the form, but a little more work is needed to
set the value for
completionProgress
.
You create a helper function called
countFieldData()
. Its job is straightforward: Examine the elements
within the form and determine if they have a value. It's not a foolproof solution for determining if the
user has completed the form, but it works for this example.