Creating Validating Date Selection Lists


f.elements["day"].options.length = maxDays; 

The next step for the date selection lists from the previous phrase consists of taking care of users entering a valid date. So, whenever there is a change in the month or in the year, the day selection list must be updated appropriately:

<select name="month"   onchange="updateDay(this.form);"> <select name="year"   onchange="updateDay(this.form);"> 


To do so, a helper function (see Chapter 6) determines whether a year is a leap year:

function isLeapYear(y) {   return (y % 4 == 0 &&     (y % 100 != 0 || y % 400 == 0)); } 


With this information, the day selection list can be updated. If there are too many entries, the list is shortened. If there are too few entries, the list gets additional entries. All this maintains the selectedIndex value, if possible, so that the user's selection is maintained (unless, for instance, day 30 is selected and the month changed to February).

Automatically Updating the List (date.html; excerpt)

<script language="JavaScript"   type="text/javascript"> function updateDay(f) {   var oldDays = f.elements["day"].options.length;   var month = parseInt(f.elements["month"].value);   var year = parseInt(f.elements["year"].value);   var maxDays = 30;   switch (month) {     case 1: case 3: case 5: case 7: case 9: case 11:       maxDays = 31;       break;     case 2:       maxDays = (isLeapYear(year) ? 29 : 28);       break;   }   f.elements["day"].options.length = maxDays;   if (maxDays > oldDays) {     for (var i=oldDays; i<maxDays; i++) {       f.elements["day"].options[i] =         new Option(i+1, i+1);     }   } } </script> 

In Figure 8.10 you can see the result: February of the year 2000 had 29 days.

Figure 8.10. The day list is updated according to month and year.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net