datePicker需要单击两次才能显示不可用的日期

datePicker need to click twice to show the unavailable dates

本文关键字:显示 日期 两次 单击 datePicker      更新时间:2023-09-26

我创建了一个代码,该代码禁用从数据库检索的某些日期。

在getDates脚本中,我只从数据库中检索日期,返回它们并将它们分配给数组unavailableDates。

<script>
var unavailableDates;
function unavailable(date) {
    dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
    if ($.inArray(dmy, unavailableDates) == -1) {
        return [true, ""];
    } else {
        return [false, "", "Unavailable"];
    }
}
$(document).ready(function()
{
    $("#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',  
        beforeShowDay: unavailable, 
        minDate: 0,
        firstDay: 1, // rows starts on Monday
        changeMonth: true,
        changeYear: true,
        showOtherMonths: true,
        selectOtherMonths: true,
        altField: '#date_due',
        altFormat: 'yy-mm-dd'
        });
    $('#datepicker').focus(function(){
        //alert($('#name').html());
         $.ajax({                                      
        url: 'getDates.php',                  
        data: "artist_id="+$('#name').html(),                       
        dataType: 'json',                     
        success: function(data)          
        {
                   unavailableDates = data;
        } 
        });
    })
});
</script>

它工作得很好,但只有当我点击两次日期选择器时。当我第一次点击时,它会显示所有日期(无论是否可用)。当我再次单击时,它会显示不可用的日期。

有人知道为什么吗?感谢

在ajax调用中添加async:false,以便应用程序在继续之前等待响应,就像一样

$('#datepicker').focus(function(){
    //alert($('#name').html());
     $.ajax({                                      
    url: 'getDates.php',                  
    data: "artist_id="+$('#name').html(),                       
    dataType: 'json', 
    async: false,            
    success: function(data)          
    {
               unavailableDates = data;
    } 
    });

另一个想法是,您可以将这个ajax调用直接添加到不可用的函数中,而不是先运行两个东西,onFocus和beforeShowDay(尽管我对beforeShowDay函数不是很熟悉)

不过,这可能会减慢日期选择器的打开速度,因为它必须等待服务,因此这取决于您的服务速度和性能要求。如果速度太慢,其他选择是弹出一条"获取日期"消息,或者在页面打开时每隔X秒拉一次服务器(尽管这可能会增加很多额外的服务呼叫…)

编辑:在这个评论之后。。。

"basically when user selects an option (here they want to book artists so '
when user selects an artist), the unavailable dates of datepicker are 
updated   automatically." 

当选择艺术家时加载列表似乎更有意义,除非你担心页面打开时会发生更改。如果那样的话,我会做一些类似。。。

On Artist Changed
    -Disable date picker, possibly add a small note next to it / under it / 
       over it that it is loading
    -Start ajax call with async true
    -In ajax success function, re-enable the picker and remove the message.

这将允许UI保持活动状态,允许用户在加载日期时输入其他信息,如果服务足够快,用户甚至一秒钟都不会知道它被禁用了。你的约会不会像其他方式那样"现场",但听起来不需要那么现场。无论如何,您都需要重新检查提交表单的日期。

因为您在显示日期选择器时启动了获取不可用日期的请求。你必须提前做这件事。在后端请求的回调中,您可以显示日期选择器。

var data = $.getJSON($url, function (data) {
         //your logic
}).success(function (data) {
        //Trigger the first click
        $('.datepicker').trigger('click');
});
$(".div_fader").on('click','.datepicker', function () {
        $(this).datepicker();
});