![]() |
![]() Code Stuff |
When you need people to fill out a form on your site and you want them to enter a current, recent, or upcoming date, you could give them a menu that by default starts at January 1, 2010. Or you could have the form automatically start at the current date. It's fairly easy with JavaScript. The version I used below puts the scripts inline with the HTML code which was better for my purposes. But you could just as easily turn this into a function.
Here's how it looks:
The first bit of code goes into your HEAD section:
1 |
<SCRIPT type="text/javascript"> var todaysDate=new Date() </SCRIPT> |
This creates a global variable called "todaysDate" and sets it to equal... today's date! The next piece of code is the HTML and JavaScript that creates the form:
1 |
<SELECT name="month" size="1">
<SCRIPT type="text/javascript">
monthText = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
for (optionMonth=0; optionMonth <= 11; optionMonth++)
{
if(optionMonth==todaysDate.getMonth())
{
document.write("<OPTION value=" + monthText[optionMonth] + " SELECTED>"
+ monthText[optionMonth]);
} else {
document.write("<OPTION value=" + monthText[optionMonth] + ">"
+ monthText[optionMonth]);
}
}
</SCRIPT>
</SELECT>
<SELECT name="day" size="1">
<SCRIPT type="text/javascript">
for (optionDay=1; optionDay <= 31; optionDay++)
{
if(optionDay==todaysDate.getDate())
{
document.write("<OPTION value=" + optionDay + " SELECTED>" + optionDay);
} else {
document.write("<OPTION value=" + optionDay + ">" + optionDay);
}
}
</SCRIPT>
</SELECT>
<SELECT name="year" size="1">
<SCRIPT type="text/javascript">var optionYear = todaysDate.getFullYear();
document.write("<OPTION value=" + (optionYear-3) + ">" + (optionYear-3));
document.write("<OPTION value=" + (optionYear-2) + ">" + (optionYear-2));
document.write("<OPTION value=" + (optionYear-1) + ">" + (optionYear-1));
document.write("<OPTION value=" + optionYear + " SELECTED>" + optionYear);
document.write("<OPTION value=" + (optionYear+1) + ">" + (optionYear+1));
document.write("<OPTION value=" + (optionYear+2) + ">" + (optionYear+2));
document.write("<OPTION value=" + (optionYear+3) + ">" + (optionYear+3));
</SCRIPT>
</SELECT>
|
Lines 1-14 create the month code. We create an array with the names of the months with their numbers as keys. Then we print the month form using a loop. When the current month number equals the month we are writing to the page we add the SELECTED attribute to make it the default option. Lines 16-28 create the days form, and it basically works the same as the month code. Lines 30-40 create the year code. Here we just print 3 years before and after the current year.