想要将预选的日期值添加到日期字段中

时间:2014-02-22 06:39:03

标签: javascript html

我想在日期框中添加预选的日期值。我无能为力。此外,只能验证年份字段。

我已经尝试了很多;有人可以帮忙吗?

<script type="text/javascript">
var ysel = document.getElementsByName("year")[0];
var msel = document.getElementsByName("month")[0];
var dsel = document.getElementsByName("day")[0];
var opt = new Option("Date", "");
dsel.appendChild(opt);
var curr_date = new Date().getFullYear();
for (var i = curr_date; 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();
</script>

<select name="year" class="mandatory" id="year" data-mini="true" data-theme="c">
    <option value="">Year</option>
</select>
<select name="month" class="mandatory" id="month" data-mini="true" data-theme="c">
    <option value="1">Month</option>
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>
    <option value="4">Apr</option>
    <option value="5">May</option>
    <option value="6">Jun</option>
    <option value="7">Jul</option>
    <option value="8">Aug</option>
    <option value="9">Sep</option>
    <option value="10">oct</option>
    <option value="11">Nov</option>
    <option value="12">Dec</option>
</select>
<select name="day" class="mandatory" id="day" data-mini="true" data-theme="c">
    <option value="Date" selected>Date</option>
</select>

1 个答案:

答案 0 :(得分:0)

由于您删除了当天的所有值,因此您需要每次都添加“日期”:

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];

    // here you delete all day's
    dsel.length = 0;

    // so we add "Day" back here
    var opt = new Option();
    opt.text = "Day";
    opt.value = '';
    dsel.add(opt);

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

http://jsfiddle.net/47k76/1/