You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Problem

There are 2 date picker fields in the form and represented "From Date" and "To Date". Need to ensure that both dates are not before today and the end date is later than the start date.

Code
<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