Topic: Setting datepicker with JavaScript
How can I set the date of a datepicker with JavaScript so when we open the datepicker it shows the date I set. Presently when I set the date picker with $('#idOfTheDatePicker').val('01-01-2020'), the date is showed correctly, but if I click in the field, the calendar pops up with the today's date instead of the one I set with JavaScript.
Mateusz Łubianka staff answered 5 years ago
Hi @Kiril,
@lemons is right. To set default date you should to use data-value. You can set it in your html code or via jQuery. Link: https://mdbootstrap.com/docs/jquery/forms/date-picker/#pre-fill-values
Best,
Kiril commented 5 years ago
I need to set the date after the initialization, so the data-value doesn't work for me.
lemons answered 5 years ago
Here you go:https://mdbootstrap.com/snippets/jquery/lhock/1608686
You have to use the "picker" directly to call the set method after initialization. I do load the date before initalization most of the time, as it keeps my logic more clean.
@MDB team: you could add this to your docs
Mateusz Łubianka staff answered 5 years ago
If you want to set value after the initialization you should use:
$('#').pickadate('picker').set(thing, value);
The thing can be: clear, select, highlight, view, min, max, disable, enable, interval. In this case you have to use 'select'.
$('#').pickadate('picker').set('select', [2015, 3, 20]);
$('#').pickadate('picker').set('select', new Date(2015, 3, 30));
$('#').pickadate('picker').set('select', '2016-04-20', { format: 'yyyy-mm-dd' });
$('#').pickadate('picker').set('clear');
You can see good example in lemons snippet. @lemons, I think it's very good idea to add this to MDB docs, I'll create a task for our team. Thank you for your opinion.
Best
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB jQuery
- MDB Version: 4.10.1
- Device: Desktop
- Browser: Chrome
- OS: Windows 10
- Provided sample code: No
- Provided link: No
lemons commented 5 years ago
Add the data-value attribute to the html datepicker element. data-value="[2020,0,1]" (note months begin to count with 0 instead of 1). You can also set the attribute via jquery before initialization.
Kiril commented 5 years ago
I tried that, but I have to set the date after initialization.