Skip to content
Advertisement

How can I set Date in second TextBox to first TextBox’s day + 1

I have two TextBox in a page. When user pick a date from first TextBox, second TextBox has to be first TextBox’s day +1(previus dates has to be disable). For exemple: User pick 2020-12-29, second minimum date has to be 2020-12-30. Here is the first TextBox with js codes that sets the date to today.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var today = new Date();
        var month = ('0' + (today.getMonth() + 1)).slice(-2);
        var day = ('0' + today.getDate()).slice(-2);
        var year = today.getFullYear();
        var date = year + '-' + month + '-' + day;
        $('[id*=txt1]').attr('min', date);
    });
</script>
<asp:TextBox ID="txt1" runat="server" TextMode="Date"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server" TextMode="Date"></asp:TextBox>

I can’t figure it out how to make second TextBox. But I don’t have to do it with only js. If you suggest I can also try to make it in c#.

Advertisement

Answer

Try this:

    <script type="text/javascript">
        $(function () {
            var today = new Date();
            var month = ('0' + (today.getMonth() + 1)).slice(-2);
            var day = ('0' + today.getDate()).slice(-2);
            var year = today.getFullYear();
            var date = year + '-' + month + '-' + day;
            $('[id*=txt1]').attr('min', date);


            $('[id*=txt1]').change((e) => {
                var day = 60 * 60 * 24 * 1000;

                let date1Arr = $('[id*=txt1]').val().split(/D/);
                let date2min = new Date(date1Arr[0], date1Arr[1], date1Arr[2]);
                date2min = new Date(date2min.getTime() + day);
                let yyyy = date2min.getFullYear();
                let mm = date2min.getMonth() + 1;
                let dd = date2min.getDate();

                if (mm < 10)
                    mm = '0' + mm;
                if (dd < 10)
                    dd = '0' + dd;
                let date2minText = [yyyy, mm,dd].join('-');
                $('[id*=txt2]').attr('min', date2minText);
            });
        });
    </script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement