Java Reference
In-Depth Information
This select box renders as a drop-down list box in the browser; by default, a <select/> element's size
attribute is set to 1. The onchange event handler connects to the recalcDateDiff() function that
you'll be looking at shortly.
However, no <option/> elements are defi ned within the <select/> element. The drop-down list boxes
need to be populated with too many options for you to enter them manually. Instead you populate the
options using the functions, which make use of the document.write() method.
The date and year options are populated using the writeOptions() function declared in the head of
the page. The function is passed two values: the start number and the end number of the options that
you want the select element to be populated with. Let's look at the writeOptions() function.
function writeOptions(startNumber, endNumber)
{
var optionCounter;
for (optionCounter = startNumber;
optionCounter <= endNumber; optionCounter++)
{
document.write(“<option value=” + optionCounter + “>” +
optionCounter);
}
}
The function is actually quite simple, consisting of a for loop that loops from the fi rst number
( startNumber ) through to the last ( endNumber ) using the variable optionCounter and writes out the
HTML necessary for each <option/> element. The text for the option and the value attribute of the
<option/> element are specifi ed to be the value of the variable optionCounter . It's certainly a lot
quicker than typing out the 31 <option/> elements necessary for the dates in a month.
For the year select box, the same function can be reused. You just pass 1970 and 2020 as parameters to
the writeOptions() function to populate the year select box.
<select name=”firstYear” onchange=”recalcDateDiff()“>
<script type=”text/javascript”>
writeOptions(1970, 2020);
</script>
</select>
To populate the month select box with the names of each month, you will need a different function.
However, the principle behind populating the <select/> element remains the same: You do it using
document.write() . The function in this case is writeMonthOptions() , as you can see from the fol-
lowing month select element:
<select name=”firstMonth” onchange=”recalcDateDiff()“>
<script type=”text/javascript”>
writeMonthOptions();
</script>
</select>
The new function, writeMonthOptions(), is defi ned in the head of the page. Let's take a look at it now.
You start the function by defi ning three variables and initializing the variable, theDate, to the current date.
function writeMonthOptions()
{
Search WWH ::




Custom Search