user2965875
user2965875

Reputation: 701

How to set the start year in date of birth dropdown

I have some code the show the date of birth values. I would like to add one more function to this java script but unsure the best way.

The age is set on the year 2000 as default and the user can't go any lower as you have to be 13 or above to join the site.

Can I adjust this code to make the default change automatically each year?

For example next year the person can be born in 2001 to be 13, so the default would be "2001" the year after 2002 etc.

can anyone help me to automate this code instead of having to manually change it?

Please see Fiddle

var ysel = document.getElementsByName("year")[0],
    msel = document.getElementsByName("month")[0],
    dsel = document.getElementsByName("day")[0];
for (var i = 2000; i >= 1950; i--) {
    var opt = new Option();
    opt.value = opt.text = i;
    ysel.add(opt);
}
ysel.addEventListener("change", validate_date);
msel.addEventListener("change", validate_date);

function validate_date() {
    var y = +ysel.value, m = msel.value, d = dsel.value;
    if (m === "2")
        var mlength = 28 + (!(y & 3) && ((y % 100) !== 0 || !(y & 15)));
    else var mlength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
    dsel.length = 0;
    for (var i = 1; i <= mlength; i++) {
        var opt = new Option();
        opt.value = opt.text = i;
        if (i == d) opt.selected = true;
        dsel.add(opt);
    }
}
validate_date();

Upvotes: 0

Views: 613

Answers (1)

Kishan Reddy
Kishan Reddy

Reputation: 137

Use Date obj to find current year and subtract your preferred age

var currentYear = new Date().getFullYear();
for (var i = currentYear-13; i >= 1950; i--) {
    var opt = new Option();
    opt.value = opt.text = i;
    ysel.add(opt);
}

Upvotes: 3

Related Questions