Creating Prefilled Date Selection Lists


elements["day"].selectedIndex = d.getDate() - 1; 

Most online booking sites have a set of three selection lists allowing users to enter a date: one list for the day, one for the month, and one for the year. Generating these lists, either in static HTML or on the server side, is a rather trivial task; but preselecting them requires server-side means (see the book PHP Phrasebook for a solution in PHP)or a bit of JavaScript. The idea is to set the selectedIndex property of each list to the appropriate date value, as shown in the following listing (the selection lists are of course abridged):

Prefilling a Date List (autodate.html; excerpt)

<script language="JavaScript"   type="text/javascript"> window.onload = function() {   with (document.forms[0]) {     var d = new Date();     elements["day"].selectedIndex = d.getDate() - 1;     elements["month"].selectedIndex = d.getMonth();     elements["year"].selectedIndex = 2006        d.getFullYear();   } } </script> <form>   <select name="day">     <option value="1">1</option>     <! ... >   </select>   <select name="month">     <option value="1">January</option>     <! ... >   </select>   <select name="year">     <option value="2006">2006</option>     <! ... >   </select> </form> 

Warning

In the example, the first year in the list is 2006; this value is also used for calculating the required selectedIndex for that date. If you change that, for instance add the year 2007, you have to change the formula for elements["year"].selectedIndex accordingly.





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