jquerydatepickermindate

Change jQuery UI datepicker minDate dynamically


I need to change minDate of jQuery's datepicker each the time value of #position or #type changes. Currently the value for the minDate changes only the first time either #position or #type evokes the .change() method.

I am currently using the code below:

$("#position, #type").change(function(){
     var pos = $("#position").val();
     var type = $("#type").val();
     var url =  "getdate/"+type+"/"+pos;
     $.get(url, function(msg){
         $('.date1').datepicker({
             MinDate: msg
         });
     });
})

Solution

  • That's because you are re-initiating the .datepicker method everytime there is a .change() event.

    Instead of this, initiate the datepicker once on the class .date1 and then change MinDate as follows:

    $('.date1').datepicker('option', 'minDate', msg);
    

    So this would yield:

    // first initialise
    $('.date1').datepicker({
         MinDate: msg
    });
    
    $("#position, #type").change(function(){
         var pos = $("#position").val();
         var type = $("#type").val();
         var url =  "getdate/"+type+"/"+pos;
         $.get(url, function(msg){
            // then change
            $('.date1').datepicker('option', 'minDate', msg);
         });
    })
    

    Alternatively, you can also destroy the .datepicker object as follows:

    $('.date1').datepicker('destroy');
    

    And then recreate the object as in your own code. So combined this would yield:

    // first initialise
    $('.date1').datepicker({
         MinDate: msg
    });
    
    $("#position, #type").change(function(){
         var pos = $("#position").val();
         var type = $("#type").val();
         var url =  "getdate/"+type+"/"+pos;
         $.get(url, function(msg){
            // first destroy
            $('.date1').datepicker('destroy');
            // then recreate
            $('.date1').datepicker({
               MinDate: msg
            });
         });
    })
    

    Also, please consult this question and answer:

    jQuery DatePicker -- Changing minDate and maxDate on the fly