简体   繁体   English

如何设置出生日期下拉菜单中的开始年份

[英]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. 我想向此Java脚本添加更多功能,但不确定最佳方法。

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. 年龄默认设置为2000年,用户不能再低了,因为您必须年满13岁或更高才能加入该网站。

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. 例如,明年该人可以在2001年出生,年龄为13岁,因此默认值是2002年之后的第二年“ 2001”,等等。

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();

Use Date obj to find current year and subtract your preferred age 使用Date obj查找当前年份并减去您的首选年龄

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM