Search code examples
javascriptmaterialize

How to set initial custom variable date upon datepicker opening in Materialize


I use two Materialize datepickers. Upon opening the date picker I want the date that in already in html input field to be displayed / used by the date picker. I was thinkig of onOpen callback and there use native .setDate() function. But I got two date pickers and did not find if onOpen accepts any arguments.

var datepickerOptions ={
        
  format: 'yyyy-mm-dd',
  autoClose : "true",
  firstDay : 1,
  onOpen : function(arg) {
   console.log(arg)
  }
}  
  
  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.datepicker');
    var instances = M.Datepicker.init(elems, datepickerOptions);
  });

I am using Materialize v1.0. and working jsFiddle is here


Solution

  • It is sufficient to add setDefaultDate: true option to your original example:

    var datepickerOptions = {
      format: 'yyyy-mm-dd',
      autoClose : "true",
      firstDay : 1,
      setDefaultDate: true
    } 
    

    This will automatically pick up the value you've added to your input fields in HTML markup. No need to set the date explicitly in the JavaScript code.

    This is minimal working Fiddle based on your example: https://jsfiddle.net/3j6cezfy/