Set ui datepicker max/minDate on the fly

karlisup picture karlisup · Feb 25, 2011 · Viewed 8.6k times · Source

Thought it would be more easier than it is. Task:

1)disable future days. (Set maxDate as today - done)

2)from js variable get date and set it as a minDate on the fly - how?

main function (which I use for few pages):

jQuery(
    function($){
        $('#datepicker').datepicker({
             onSelect: function(dateText, inst){calendarOptions(dateText);},
            // beforeShow: function() {$("#datepicker").datepicker( "option", "minDate", curdate ).next('button').text('Kalendārs').button({icons:{primary : 'ui-icon-plus'}})}, 
             showOn: "button",
             dateFormat: 'dd.mm.yy',
             prevText: '«',
             nextText: '»',
             monthNames: ['Janvāris','Februāris','Marts','Aprīlis','Maijs','Jūnijs', 'Jūlijs','Augusts','Septembris','Oktobris','Novembris','Decembris'],
             monthNamesShort: ['JAN', 'FEB', 'MAR', 'APR', 'MAI', 'JUN', 'JUL', 'AUG', 'SEP', 'OKT', 'NOV', 'DEC'],
             dayNamesMin: ['S', 'P','O','T','C','P','S'],
             firstDay: 1,
             maxDate: calendarMaxDate()
        }).next('button').text('Kalendārs').button({icons:{primary : 'ui-icon-plus'}});
    }

);

And then comes js code for page I want to edit now:

function calendarMaxDate(){//disable future days
var date = new Date(); 
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
return new Date(currentYear, currentMonth, currentDate)
//return null; // set to default
}

function calendarOptions(dateText){ // sets selected date to 'external' input field
autofield_date.setValue(dateText);
}

jQuery(
    function($){ // calls function before ui datepicker button is pressed
        $('.ui-datepicker-trigger').click(function() {
        alert(autofield_dekl.getValue());
            MinDate();
        });
    }
);

function MinDate(){ //pass curdate value as'minDate' to calendar on the fly

    jQuery( //not sure about this part
        function($){ //without onload function it throws an error: $("#datepicker") is null
            $("#datepicker").datepicker( "option", "minDate", curdate ).next('button').text('Kalendārs').button({icons:{primary : 'ui-icon-plus'}})//;
        }
    )
    alert(curdate);
}

function MinDate() works only in the first time when the button has been pressed.

Answer

zeph picture zeph · Aug 11, 2011

i found a possible answer on this site

apparently you use the option value to do so:

 $("#datepicker").datepicker('option', 'minDate', newDate);