【问题标题】:Use php array to disable dates in datepicker and times in timepicker from onSelect in DatePicker使用 php 数组从 DatePicker 中的 onSelect 禁用 datepicker 中的日期和 timepicker 中的时间
【发布时间】:2017-12-09 18:33:28
【问题描述】:

我有一个日期选择器输入和一个时间选择器输入,我想用它们来安排一个人的约会。

当用户单击输入以打开日期选择器菜单时,我想将特定日期时间变灰。我有一个 php 函数,它以 'Y-m-d H:i:s' 字符串格式返回这个日期时间数组。但我不知道如何使用该函数的返回值来为 javascript 函数提供在 datepicker 中禁用一系列日期所需的内容。

在我的日期选择器的 onSelect 事件中,我希望它根据当天预订的时间段启用/禁用我的时间选择器中的时间选项。但我不知道怎么做。

  1. Datepicker 使用 beforeshowDay: 禁用预订日期

  2. 用户从日期选择器中选择日期

  3. 日期选择器在时间选择器中启用/禁用时间

我确实发现了如何在时间选择器 Here 中禁用时间范围。代码示例是这样的:

$('input.timepicker').timepicker({
    'disableTimeRanges': [
        ['1am', '2am'],
        ['3am', '4:01am']
    ]
});

但这就是我在时间选择器范围内禁用时间范围的方式。我不知道如何在 datepicker 的 BeforeShowDay 中禁用它们?

<script type="text/javascript">   
    $(document).ready(function(){
        $( "#datepickerListAppointments" ).datepicker(
        {
            minDate:'0',
            beforeShowDay:
            function(dt)
            {   // need to disable days other than tuesday and wednesday too.
                return [dt.getDay() === 2 || dt.getDay() === 3, ""];
            },
            onSelect : function(){
                should disable/enable timepicker times from here?
            }
        });

        $('input.timepicker').timepicker({
            timeFormat: 'h:mm p',
            interval: 90,
            minTime: '9',
            maxTime: '10:30am',
            defaultTime: '9',
            startTime: '9:00',
            dynamic: false,
            dropdown: true,
            scrollbar: false                
        });

    });

这是提供日期时间的函数,以防有助于了解。

function get_next_open_appointments($numAppointments, $timeSlotToExclude = "")
{
    global $db;
    $whereCondition = "WHERE FirstName = :null ";
    if ($timeSlotToExclude != "")
    {
        $whereCondition .= "AND AppointmentTime != '$timeSlotToExclude' ";
    }

    $query = "SELECT DISTINCT AppointmentTime FROM appointments
              $whereCondition
              ORDER BY AppointmentTime ASC LIMIT $numAppointments";
    $statement = $db->prepare($query);
    $statement->bindValue(':null', "");
    $statement->execute();
    $datesArray = array();
    while ($row = $statement->fetch()) 
    {
        array_push($datesArray, $row['AppointmentTime']);
    }
    $statement->closeCursor();
    return $datesArray;
}

更新:

Hugo De Carmo 为我指明了正确的方向,我得到了适当禁用/启用的日期。但是,我不知道如何使用我在下面的代码中提取的日期时间来禁用/启用时间选择器中的时间。

这是新代码:

<script type="text/javascript">   
    $(document).ready(function(){

        // uses php to get open appointments, and put them in a javascript array
        <?php $datetime_openings = get_next_open_appointments(200);
        $date_openings = array();
        foreach ($datetime_openings as $dt)
        {
            array_push($date_openings, substr($dt,0,10)); // just the date part
        }

        $json_date_openings = json_encode($date_openings);
        echo "var arr_Openings = ". $json_date_openings . ";\n";
        ?>

        $( "#datepickerOpenAppointments" ).datepicker(
        {
            minDate:'0',
            beforeShowDay:
            function(dt)
            {
                var string = jQuery.datepicker.formatDate('yy-mm-dd', dt);
                var bFound = (arr_Openings.indexOf(string) != -1);
                return [ bFound ]; 
            },
            onSelect : function(){
               //    Should disable/enable time ranges here?
        });

        $('input.timepicker').timepicker({
            timeFormat: 'h:mm p',
            interval: 90,
            minTime: '9',
            maxTime: '10:30am',
            defaultTime: '9',
            startTime: '9:00',
            dynamic: false,
            dropdown: true,
            scrollbar: false                
        });

    });

【问题讨论】:

    标签: javascript php jquery datepicker timepicker


    【解决方案1】:

    试试这个,
    抱歉,我没有使用 beforeshowDay
    选择日期 2017-7-14 和 2017-7-17 并查看

    var disabledDateTime = {
      '2017-7-14':[
      	['2:30am','3:00am'],
        ['6:30am','9:00am']
      ],
    	'2017-7-17':[
      	['1:00am','3:00am'],
        ['5:30am','7:00am'],
        ['11:30am','2:00pm']
      ]
    };
    
    $(function() {
      $('#pickTime').timepicker();
      $('#pickDate').datepicker({
        'format': 'yyyy-m-d',
        'autoclose': true
      }).on('changeDate',function(e){
        var ts = new Date(e.date);
        var m = ts.getMonth()+1;
        var dt = ts.getFullYear() + '-' + m + '-' + ts.getDate();
        var opt = {'disableTimeRanges': []}
        if(typeof(disabledDateTime[dt])!='undefined'){
          $('#pickTime').timepicker('setTime', '');
          opt = {'disableTimeRanges': disabledDateTime[dt]}
        }
        $('#pickTime').timepicker('option',opt);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <link href="https://jonthornton.github.io/jquery-timepicker/lib/bootstrap-datepicker.css" rel="stylesheet"/>
    <script src="https://jonthornton.github.io/jquery-timepicker/lib/bootstrap-datepicker.js"></script>
    <link href="https://jonthornton.github.io/jquery-timepicker/jquery.timepicker.css" rel="stylesheet"/>
    <script src="https://jonthornton.github.io/jquery-timepicker/jquery.timepicker.js"></script>
    
    <input id="pickDate" type="text" class="date" />
    <input id="pickTime" type="text" class="time" />

    【讨论】:

    • var disabledDateTime = { '2017-7-14':[ ['2:30am','3:00am'], ['6:30am','9:00am'] ], '2017-7-17':[['1:00am','3:00am'], ['5:30am','7:00am'], ['11:30am','2:00pm'] ] };但我想使用 php 从日期、开始时间、结束时间等 db 值动态显示它。我该怎么做?
    • var disabledDateTime = {'2017-7-14':[['2:30am','3:00am'],['6:30am','9:00am']], '2017-7-17':[['1:00am','3:00am'],['5:30am','2:00pm']]};上面的 javascript 将两个值存储到一个变量(disabledDateTime)中,但我想使用数据库中的 php 将值动态存储到该变量(disabledDateTime)中
    • @hearthacker 您可以随时使用 ajax 检索数据(json)并设置 var disabledDateTime。
    【解决方案2】:

    有人已经回答了这个问题here

    不管怎样,下面的代码应该能让你了解如何解决这个问题。

    // supose your script return a json similar to the following
    {
        "data": [
            // ...
            "17-07-11"
        ]
    }
    
    $(function() {
      $.getJSON("/path/to/script", function(response){
        $('#datepickerListAppointments').datepicker({
          beforeShowDay: function(dt) {
            var config = [];
            config[1] = 'class';
    
            if ((dt.getDay() === 2) || (dt.getDay() === 3)) {
              config[0] = false;
              return config;
            }
    
            var string = jQuery.datepicker.formatDate('yy-mm-dd', dt);
            config[0] = (response.data.indexOf(string) === -1);
            return config;
          }
        });
      });
    });
    

    我假设您正在使用某种 API 与服务器交换数据,因此使用 getJSON,如果您想处理服务器错误,那么我建议您使用 ajax 结合 @987654324 @。

    编辑 1

    您可以使用 DateTime 类从您的日期中提取所有内容,这是一个 sn-p:

    $openings = array();
    
    $date = DateTime::createFromFormat("y/m/d H:i", "17/07/15 08:30");
    
    if (!isset($openings[$date->format("y-m-d")])) {
        $openings[$date->format("y-m-d")] = array();
    }
    
    $openings[$date->format("y-m-d")][] = array(
        "hour" => $date->format("Ha"),
        "minute" => $date->format("i")
    );
    
    /* result
    array(1) {
      ["17-07-15"]=>
      array(1) {
        [0]=>
        array(2) {
          ["hour"]=>
          string(4) "08am"
          ["minute"]=>
          string(2) "30"
        }
      }
    }
    */
    

    然后您可以根据日期禁用时间选择器中的时间,您可能需要在您的日期选择器中注册一个回调函数以根据所选日期更新时间选择器,或者您必须使用新设置覆盖时间选择器。

    【讨论】:

      【解决方案3】:

      是的,您可以使用 timepicker 组件的 option 方法动态更新 onSelect 函数内的 timepicker disableTimeRanges

      我假设:

      • 您正在使用 jQuery UI datepicker(因为您没有使用 twitter-bootstrap 标记您的问题,而 bootstrap-datepicker 没有 minDate 选项)
      • 您正在使用get_next_open_appointments 的第一个版本,它返回一个日期时间数组(如['2017-07-25 09:30:00', ...],参见sn-p 中的fakeDisabledTimes

      我正在使用 momentjs 来简化日期管理。在下面的代码中,我使用了矩解析函数(moment(String)moment(String, String))、isSameaddformat。请注意,时刻令牌与 PHP 令牌不同。

      这是一个完整的工作示例:

      var fakeDisabledTimes = [
        '2017-07-25 09:30:00', '2017-07-26 10:00:00',
        '2017-08-01 09:00:00', '2017-08-02 09:30:00',
        '2017-08-08 10:30:00', '2017-08-09 10:00:00',
        '2017-07-15 09:30:00', '2017-07-16 10:00:00'
      ];
      
      $(document).ready(function(){
        $( "#datepickerListAppointments" ).datepicker({
          minDate:'0',
          beforeShowDay:
          function(dt){
            // need to disable days other than tuesday and wednesday too.
            return [dt.getDay() === 2 || dt.getDay() === 3, ""];
          },
          onSelect : function(dateText){
            //should disable/enable timepicker times from here!
            // parse selected date into moment object
            var selDate = moment(dateText, 'MM/DD/YYYY');
            // init array of disabled times
            var disabledTimes = [];
            // for each appoinment returned by the server
            for(var i=0; i<fakeDisabledTimes.length; i++){
              // parse appoinment datetime into moment object
              var m = moment(fakeDisabledTimes[i]);
              // check if appointment is in the selected day
              if( selDate.isSame(m, 'day') ){
                // create a 30 minutes range of disabled time
                var entry = [
                  m.format('h:mm a'),
                  m.clone().add(30, 'm').format('h:mm a')
                ];
                // add the range to disabled times array
                disabledTimes.push(entry);
              }
            }
            // dinamically update disableTimeRanges option
            $('input.timepicker').timepicker('option', 'disableTimeRanges', disabledTimes);
          }
        });
      
        $('input.timepicker').timepicker({
          timeFormat: 'h:i a',
          interval: 90,
          minTime: '9',
          maxTime: '10:30am',
          defaultTime: '9',
          startTime: '9:00',
          dynamic: false,
          dropdown: true,
          scrollbar: false                
        });
      
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.js"></script>
      
      <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>
      <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.10.0/jquery.timepicker.css" rel="stylesheet"/>
      
      <input id="datepickerListAppointments" type="text">
      <input class="timepicker" type="text">

      【讨论】:

        猜你喜欢
        • 2018-03-03
        • 2020-11-23
        • 1970-01-01
        • 2020-08-23
        • 1970-01-01
        • 2020-05-19
        • 2011-09-09
        • 2019-02-27
        • 1970-01-01
        相关资源
        最近更新 更多