Search code examples
javascriptjquerydatepickermaterialize

OnSelect Datepicker in Materialize to set Max Date + 9 between two inputs


I have two inputs between from date and to date, I want to set maxDate is 9 days reference first input. I use Materialize the latest version.

Example: when I select 1 August 2018 maxDate in id="to" is 10 August 2018

Here is my HTML

<input type="text" class="datepicker" id="from" value="from">
<input type="text" class="datepicker" id="to" value="to">

and my JS

$('#from').datepicker({
  autoClose : true,
  onSelect: function() {
    var minDate = $(this).setDate(new Date() + 9);
    $("#to").datepicker("option", "minDate", minDate)
   }
});
$("#to").datepicker({
  autoClose : true,
  onSelect: function() {
    var maxDate = $(this).setDate(new Date() - 9);
    $("#from").datepicker("option", "maxDate", maxDate)
  }
})

I create onSelect like that is not working. I using Materialize, but stack here. Anybody help? thank you.. Demo: https://jsfiddle.net/dedi_wibisono17/rt9780xs/58/


Solution

  • You should change your onSelect() to this :

    onSelect: function() {
    
           var toYear = this.date.getFullYear();
           var toMonth = this.date.getMonth();
           var toDay = this.date.getDate();
           maxDate = new Date(toYear, toMonth, toDay + 9);
    
           $("#to").datepicker({
              format : 'dd mmm yyyy',
              defaultDate: maxDate,
              setDefaultDate:maxDate
           })
    }
    

    here is the solution : jsfiddle