在函数内获取值以在函数外使用

时间:2019-04-11 06:35:35

标签: javascript jquery bootstrap-4 datetimepicker

我正在使用两个datetimepicker Bootstrap,第一个是startDate,第二个是enddate,问题是我应该选择开始日期,并且在结束日期中自动选择最小日期(我在startdate中选择的日期)。并且终止日期的datatimepicker中日期的最大值为+7天。你能帮我吗?

我试图在名为datatimepicker6的第一个datatimepicker中获取日期,并且做到了,但我不知道如何在称为datatimepicker7的结束日期datatimepicker中使用。下面是代码:

$emp_in = '7:00 am';
// find the difference between time entered and 8:00 am
$diff = '8:00 am' -$emp_in;

// multiply the diffrence time to 3600 to change to second and then add with time in
$emp_in = strtotime($emp_in) + ($diff*3600);

$emp_out = '5:00 pm';

$emp_out = strtotime($emp_out);

$result_in_out = $emp_in - $emp_out;
$result_hours = abs(floor($result_in_out/3600));
echo $result_hours;

2 个答案:

答案 0 :(得分:2)

将其添加到您的onchange事件中将起作用

            e.date.add(7, 'day'); 
            $('#datetimepicker7').data("DateTimePicker").minDate(e.date);
            $('#datetimepicker7').data("DateTimePicker").date(e.date);

完整代码onchange

 $("#datetimepicker6").on("dp.change", function (e) {
         //var val = $('#datetimepicker6').data('date');     
        e.date.add(7, 'day'); 
    $('#datetimepicker7').data("DateTimePicker").minDate(e.date);     
   $('#datetimepicker7').data("DateTimePicker").date(e.date);

                });                
            });

check the demo here

答案 1 :(得分:2)

无需将变量带到另一个函数中,只需在事件内部声明一个变量即可,Fiddle

$(function () {
                    $('#datetimepicker6').datetimepicker({
                        format: 'DD.MM.YYYY HH:mm:ss',
                        keyBinds: {'delete': null}
                    });


                  $('#datetimepicker7').datetimepicker({
                    format: 'DD.MM.YYYY HH:mm:ss',
                    useCurrent: false,
                    keyBinds: {'delete': null},
                    useCurrent: false //Important! See issue #1075
                  });

                  $("#datetimepicker6").on("dp.change", function(e) {
                        var drr = $('#datetimepicker6').data('date');
                        var endDate = new Date(e.date);
                        endDate.setDate(endDate.getDate()+7);
                        $('#datetimepicker7').data("DateTimePicker").minDate(drr);
                        $('#datetimepicker7').data("DateTimePicker").maxDate(endDate);
                });
         });