如何禁用datepicker上的所有先前日期

时间:2013-11-25 06:59:52

标签: javascript jquery jquery-ui jquery-ui-datepicker

我有两个日期选择器,用于选择开始日期和结束日期。一旦我选择了开始日期,我想在结束日期字段的日历上将所有以前的日期变灰,我尝试了以下代码,但是它的灰色显示了当前日期的前一个日期

脚本

$("#startDate").onChange(function () {
    var currentDate = new Date().getDate();
    var startDate = new Date($(this).val());
    var timeDiff = Math.abs(currentDate.getTime() - startDate.getTime());
    $("#hDate")[0].value = Math.ceil(timeDiff / (1000 * 3600 * 24));
});

$(".datepicker").datepicker({
    buttonImage: "../Images/calender.png",
    buttonImageOnly: true,
    showOn: "button",
    minDate: -($("#hDate")[0].value)
});

HTML

 <input type="text" placeholder="Start" class="datepicker" id="startDate">
 <input type="text" placeholder="End" class="datepicker" id="endDate">
 <input type="hidden" id="hDate" value="">

我该如何解决这个问题

2 个答案:

答案 0 :(得分:3)

选择日期时,datepicker会触发onSelect事件。使用此事件在另一个日期选择器中设置minDate选项。方法如下:

$("#endDate").datepicker();
$("#startDate").datepicker({
    onSelect: function (dateText, inst) {
        var date = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
        $("#endDate").datepicker("option", "minDate", date);
    }
});

Demo here

答案 1 :(得分:0)

$('#startDate').datepicker({dateFormat: 'yy-mm-dd'});
$('#endDate').datepicker({dateFormat: 'yy-mm-dd'});
$('#startDate').on("change", function() {
       //Begin the re-creation
       $('#end-datepicker').datepicker( "destroy" );
       $('#endDate').datepicker({
                /**
                 * Set the date to be the same as the start
                **/
                minDate : $('#startDate').datepicker( "getDate" ),
                dateFormat: 'yy-mm-dd',
                //Optional: setDate: The same as minDate.
             });
        });