www.webdeveloper.com
Results 1 to 3 of 3

Thread: Auto year select field in descending order

Hybrid View

  1. #1
    Join Date
    Mar 2012
    Posts
    2

    Auto year select field in descending order

    Hello, I am using this script to auto populate a select form field with the current year. Anyone know how to easily make the list show in descending order? I just can't figure it out. Thanks for your time!

    /* This script and many more are available free online at
    The JavaScript Source!! http://www.javascriptsource.com
    Created by: Don Demrow | */
    function autoYear() {
    var time = new Date();
    var year = time.getYear();

    if (year < 1900) {
    year = year + 1900;
    }

    var date = year - 25; /*change the '25' to the number of years in the past you want to show */
    var future = year + 10; /*change the '10' to the number of years in the future you want to show */

    document.writeln ("<form><select><option value=\"\">Select Year");
    do {
    date++;
    document.write ("<option value=\"" +date+"\">" +date+ "");
    }
    while (date < future)
    document.write ("</select></form>");
    }

  2. #2
    Join Date
    Dec 2002
    Location
    St. Louis, MO, USA
    Posts
    1,582
    First, I think getYear() is (or is being) deprecated; use getFullYear(), which will give you the full four digit year.

    Code:
    function autoYear() {
    var time = new Date();
    var year = time.getFullYear();
    
    var date = year + 25; /*change the '25' to the number of years in the past you want to show */
    var future = year - 10; /*change the '10' to the number of years in the future you want to show */ 
    
    document.writeln ("<form><select><option value=\"\">Select Year");
    do {
    date--;
    document.write ("<option value=\"" +date+"\">" +date+ "");
    }
    while (date > future)
    document.write ("</select></form>");
    }
    IMHO, the above is kind of a hokey way of doing it. You're better off hard-coding the SELECT in HTML without options, giving it an ID, and then after the page is loaded use getElementById and new Option. Loop through that and use new Option to add the years.

    Just my $0.02 worth.

  3. #3
    Join Date
    Mar 2012
    Posts
    2

    Hangs the page

    Hi WolfShade - thank you for the heads up on getFullYear() and the order fix. I really appreciate it!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles