简体   繁体   中英

Set Datetimepicker minDate based on another Datetimepicker date

I am using Datetimepicker with date only format on both classes(It is working fine if I select Date from the ValidFrom Box). My use case was that once ValidFrom is selected, the ValidTo should automatically increase by 1 month(this is happening). Now the problem I am facing is that once, the date from ValidFrom is selected in ValidTo Box the date should not be less than the date in ValidFrom and also, date in ValidTo can only be decreased and should not increase 30 days.

Following is my code for Datetimepicker:

<script>
    $(document).ready(function () {
        $('#ValidFrom').datetimepicker({
            datepicker: true,
            timepicker: false,
            format: 'm/d/Y',
            step: 30,
            minDate: new Date(),
            onChangeDateTime: function (dp, $input) {
                var date = new Date($input.val());
                date.setMonth(date.getMonth() + 1);
                date = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
                $('#ValidTo').val(date);
            },

        });
        $('#ValidTo').datetimepicker({
            datepicker: true,
            timepicker: false,
            format: 'm/d/Y',
            step: 30,
            minDate: new Date(),

        });

    });

</script>

PS I've already tried the ways mentioned in other question, but they were not fruitful.

Try with updating minDate and maxDate as below.

$('#ValidTo').datetimepicker('option', 'minDate', minDate);
$('#ValidTo').datetimepicker('option', 'maxDate', maxDate);

Or if it doesn't work then try like below.

$('#ValidTo').data("DateTimePicker").setMinDate(minDate);
$('#ValidTo').data("DateTimePicker").setMaxDate(maxDate);

Your complete code should be like below.

 $(document).ready(function() { $('#ValidFrom').datetimepicker({ datepicker: true, timepicker: false, format: 'm/d/Y', step: 30, minDate: new Date(), onChangeDateTime: function(dp, $input) { var date = new Date($input.val()); $('#ValidTo').datetimepicker('option', 'minDate', date); date.setMonth(date.getMonth() + 1); $('#ValidTo').datetimepicker('option', 'maxDate', date); date = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); $('#ValidTo').val(date); }, }); $('#ValidTo').datetimepicker({ datepicker: true, timepicker: false, format: 'm/d/Y', step: 30, minDate: new Date(), }); }); 

这是一个方便的工具 ,可以帮助您创建所需的约束。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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