Select Menus and Date Object Validation
Select a month from the 1st menu and the correct number of days in that month will be displayed in the 2nd menu.
First an array containing the months of the year stored as strings is created, and a new Date object used to retrieve the integer representing the current month (0-11) and the current date. Both are used to dynamically write the select menus so that the current month and date are displayed.
var months = new Array()
months[1] = "Jan"
months[2] = "Feb"
months[3] = "Mar"
months[4] = "Apr"
months[5] = "May"
months[6] = "Jun"
months[7] = "Jul"
months[8] = "Augt"
months[9] = "Sep"
months[10] = "Oct"
months[11] = "Nov"
months[12] = "Dec"
var today = new Date()
var month = today.getMonth()+1
var date = today.getDate()
The HTML select menus' options are created dynamically using the months array, and the month and date variables:
<form>
<select onchange="correctDate(this.form,this)">
<script type="text/javascript>
for(i=1; i<=12; i++){
if(i==month){
sel = "selected"
}
else{
sel = ""
}
document.write("<option value="+months[i]+" "+sel+">"+months[i]+"\n")
}
</script>
</select>
<select>
<script language="JavaScript">
var daysInMonth=(month==4 || month==6 || month==9 || month==11) ? 30 : (month==2) ? 28 : 31
for(j=1; j<=daysInMonth; j++){
if(j==date){
sel = "selected"
}
else{
sel = ""
}
document.write("<option value="+j+" "+sel+">"+j+"\n")
}
</script>
</select>
</form>
Because the menus' options are created dynamically, they will conveniently display the current month and date. To make sure the user will not select a non-existing date such as "Feb 31", the 1st menu invokes a function from within its onChange event handler which changes the number of options in the date menu to reflect the actual number of days in the selected month.
function correctDate(form,monthMenu){
for(i = 0; i < form.elements.length; i++){
if(form.elements[i] == monthMenu){
var dateMenu = form.elements[i+1]
break
}
}
var formerlength = dateMenu.options.length
var thelength
if(monthMenu.options[1].selected){
thelength = 28
}
else if(monthMenu.options[3].selected || monthMenu.options[5].selected || monthMenu.options[8].selected || monthMenu.options[10].selected){
thelength = 30
}
else{
thelength = 31
}
dateMenu.options.length = thelength
for(i=formerlength; i<thelength; i++){
dateMenu.options[i].value=i+1
dateMenu.options[i].text=i+1
}
dateMenu.selectedIndex = thelength-1
}
There ya have it. A handy little script that will keep your date menu true to its month menu.