Java Reference
In-Depth Information
var theMonth;
var monthCounter;
var theDate = new Date();
You use the Date object contained in the theDate variable to get the months as text ( Jan , Feb ... Dec ). You
get these months by setting the month in the theDate variable from 0 up to 11 using the setMonth()
method in a for loop. Although the Date object does not provide a method for returning the date as
anything other than a number, it does have the toString() method, which returns the value, as a
string, of the date stored in the variable. It returns the date in the format of day of the week, month, day
of the month, time, and fi nally year; for example, Wed Jul 15 2009 16:11:10 GMT-0500 . This string
varies from browser to browser, but they all start the month at the fi fth character. With this information,
you can easily use the String object's substr() method to extract the month.
for (monthCounter = 0; monthCounter < 12; monthCounter++)
{
theDate.setMonth(monthCounter);
theMonth = theDate.toString();
theMonth = theMonth.substr(4, 3);
document.write(“<option value=” + theMonth + “>” + theMonth);
}
}
Now that you have your month as a string of three characters, you can create the <option/> element
and populate its text and value with the month.
For user convenience, it would be nice during the loading of the page to set both of the dates in the
select elements to today's date. This is what you do in the window_onload() function , which handles
the window's load event by means of the opening <body> tag.
<body onload=”window_onload()”>
The window_onload() function, defi ned in the head of the page, starts by setting the theForm variable
to reference your Form object, because it shortens the reference needed in your code. Next, you create a
variable to hold a Date object to store today's date.
function window_onload()
{
var theForm = document.form1;
var nowDate = new Date();
Setting each of the <select/> box's initial values is easy; the value returned by the Date object nowDate
can be modifi ed to provide the required index of the options collection. For the day, the correct index
is simply the day of the month minus one — remember that arrays start at 0 , so day 1 is actually at
index 0 . The selected property is set to true to make that day the currently selected option in the list.
theForm.firstDay.options[nowDate.getDate() - 1].selected = true;
theForm.secondDay.options[nowDate.getDate() - 1].selected = true;
The month is even easier because the getMonth() function returns a value from 0 to 11 for the month,
which exactly matches the necessary index value for the options collection.
theForm.firstMonth.options[nowDate.getMonth()].selected = true;
theForm.secondMonth.options[nowDate.getMonth()].selected = true;
Search WWH ::




Custom Search