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
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/
You can simply use the defaultDate
and setDefaultDate
options from the documentation, and use them to initialize each date picker.
You set the defaultDate
field to a date object created from the input value, and you set the setDefaultDate
field to true to use the default date in the input when you open it.
document.addEventListener('DOMContentLoaded', () => {
const pickers = document.querySelectorAll('.datepicker');
pickers.forEach((picker) => {
const options = {
format: 'yyyy-mm-dd',
autoClose : true,
firstDay : 1,
defaultDate: new Date(picker.value),
setDefaultDate: true
};
M.Datepicker.init(picker, options);
});
});
body {
padding: 3em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<input class="datepicker" type=text value="2021-05-12" />
<input class="datepicker" type=text value="2021-05-25" />
If you wanted to do it with onOpen
and setDate
methods (maybe to have more fine-grained control on how the date is set, or handle formatting of the value
attribute), you could use the this.el.value
property to retrieve a pre-configured date. Here's a working example based on your fiddle: https://jsfiddle.net/2rLg0c1z/.
var datepickerOptions = {
format: 'yyyy-mm-dd',
autoClose: "true",
firstDay: 1,
onOpen: function() {
this.setDate(new Date(this.el.value));
}
}
Otherwise more simple way to automatically parse and set the date from value
attribute would be to use setDefaultDate
property, which would basically do the same on the initialization of the widget:
var datepickerOptions = {
format: 'yyyy-mm-dd',
autoClose: "true",
firstDay: 1,
setDefaultDate: true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With