如何从另一个文本框当前文本框填充+一年的日期

时间:2009-08-26 07:47:07

标签: javascript jquery vb.net

我的vb.net代码中有两个文本框

    <tr>
    <td align="right">
        <b>ActivationReqDT:</b>
    </td>
    <td>
        <asp:TextBox ID="ActivationReqDTTextBox" runat="server" Text='<%# Bind("ActivationReqDT","{0:dd/MM/yyyy}") %>' />                       
    </td>
</tr>

<tr>
    <td align="right">
        <b>DeactivationReqDT:</b>
    </td>
    <td>
        <asp:TextBox ID="DeactivationReqDTTextBox" runat="server" Text='<%# Bind("DeactivationReqDT","{0:dd/MM/yyyy}") %>' />
    </td>
</tr>

我希望当我在第一个文本框( ActivationReqDTTextBox )中输入dd / mm / yyyy中的日期时,它会自动填充第二个文本框( DeactivationReqDTTextBox )在上面输入的日期添加加一年

请使用javascript,jquery或vb.net提供您的解决方案

感谢。

最诚挚的问候, MS

1 个答案:

答案 0 :(得分:2)

我不确定甚至你想要什么,所以我假设你可能想要在第一个失去焦点后填写下一个盒子。您可以通过将活动更改为keyupchange或其他任何内容来根据需要进行调整。

$('#ActivationReqDTTextBox').blur(function () {
    var myDate = new Date(Date.parse($(this).val()));
    myDate.setYear(myDate.getYear() + 1);
    $('#DeactivationReqDTTextBox').val(myDate);
});

要注意的事情:

  • 您必须确保您的日期格式与Date.parse兼容,如果不是,则需要在使用前重新格式化
  • 您可能还希望格式化结果日期

Date.parse预计MM / DD / YYYY,在您的情况下,它是DD / MM / YYYY,因此您需要与当天交换月份。这样就可以了:

function reformat(a) {
    return a.substring(3,5) + '/' + a.substring(0,2) + a.substring(5, 10);
}

鉴于上面的修改后的代码应该是这样的。

$('#ActivationReqDTTextBox').blur(function () {
        var myDate = new Date(Date.parse(reformat($(this).val())));
        $('#DeactivationReqDTTextBox').val(myDate.getDate() + '/' + 
            (myDate.getMonth() + 1) + '/' + (myDate.getYear() + 1));
});

编辑:

要确保在第一个字段中输入错误日期时脚本不会启动,您可以这样做:

$('#ActivationReqDTTextBox').blur(function () {
    var value = $(this).val();
    var regex = /^\d{2}\/\d{2}\/\d{4}$/;
    if (regex.test(value)) {
        var myDate = new Date(Date.parse(reformat(value)));
        $('#DeactivationReqDTTextBox').val(myDate.getDate() + '/' + 
            (myDate.getMonth() + 1) + '/' + (myDate.getYear() + 1));
    } else {
        alert('invalid date');
        // this will prevent from leaving the input until the date is correct
        $(this).focus();
    }
});

编辑#2:

对代码的再次更新。这将在数​​月和数天内防止前导零。

$('#ActivationReqDTTextBox').blur(function () {
    var value = $(this).val();
    var regex = /^\d{2}\/\d{2}\/\d{4}$/;
    if (regex.test(value)) {
        var myDate = new Date(Date.parse(reformat(value)));
        var year = myDate.getYear() + 1;
        var month = myDate.getYear() + 1;
        if (month < 10) {
            month = '0' + month;
        }
        var day = myDate.getDate();
        if (day < 10) {
            day = '0' + day;
        }
        $('#DeactivationReqDTTextBox').val(day + '/' + month + '/' + year);
    } else {
        alert('invalid date');
        // this will prevent from leaving the input until the date is correct
        $(this).focus();
    }
});
相关问题