目的:

为了确保在两个日期选择器字段中设置的“From Date”和“To Date”不会落在当前日期之前,并且结束日期晚于开始日期

代码:
<script>
var startDateFieldName = "fromDate";
var endDateFieldName = "toDate";

$(document).ready(function(){
        $.datepicker.setDefaults({
                onSelect: function( selectedDate ) {
                        setDateRange(this, selectedDate);
                }
        });
        setTodayDate();
});

//set the date limit based on value. If does not present, set to current date.
function setTodayDate(){
        var date1_string = $("[name="+startDateFieldName+"]").val();
        var date2_string = $("[name="+endDateFieldName+"]").val();

        if (date1_string == "" && date2_string == ""){
                $("[name="+startDateFieldName+"], [name="+endDateFieldName+"]").datepicker( "option", "minDate", new Date());
        } else {
                if (date1_string != "") {
                        setDateRange($("[name="+startDateFieldName+"]"), date1_string);
                }
                if (date2_string != "") {
                        setDateRange($("[name="+endDateFieldName+"]"), date2_string);
                }
        }
}

//function to set min & max date
function setDateRange(element, selectedDate) {
        var option = $(element).attr("name") == startDateFieldName ? "minDate" : "maxDate";
        var instance = $(element).data( "datepicker" );
        var date = $.datepicker.parseDate(
                instance.settings.dateFormat ||
            $.datepicker._defaults.dateFormat
            ,selectedDate, instance.settings );
        $("[name="+startDateFieldName+"], [name="+endDateFieldName+"]").not(element).datepicker( "option", option, date );
}
</script>
  • No labels