'JavaScript open input date picker event
I am trying to open a date calendar input when a change event is activated.
There is a drop down field, and when a user clicks the "Specific Date" option, I would like the calendar to actually open up, however I have not been successful thus far.
The area I am wanting to open the calendar, I have added the comment: 'Below is what I have tried to open the date picker calendar'.
const datePickerEl = document.getElementById("js_datePickerToggle");
const hideDatePicker = () => {
datePickerEl.classList.add("displayNone");
};
const getDateRange = (option) => {
if (option === 'Today') {
hideDatePicker();
} else {
// display datepicker
datePickerEl.classList.remove("displayNone");
/*
* Below is what I have tried to open the date picker calendar
* datePickerEl.focus();
* datePickerEl.click();
* datePickerEl.select();
*/
}
}
const dateOptionEls = document.getElementsByName("dateRange");
dateOptionEls[0].addEventListener('change', (event) => {
const optionValue = dateOptionEls[0].options[dateOptionEls[0].selectedIndex].text;
getDateRange(optionValue);
});
.displayNone {
display: none;
}
<div>
<label>Date</label>
<select name="dateRange" dateRange=''>
<option value="Today">Today</option>
<option type="date" value="Specific date">Specific Date
<input type="date" id="js_datePickerToggle" class="displayNone">
</option>
</select>
</div>
Really appreciate your time.
Solution 1:[1]
After some research I found this answer to the date input element in general: Inspect HTML5 date picker shadow DOM
As described there, the shown datepicker element is so kind of separate window and it seems that you cannot call it direclty.
So the answer is: no you cannot open the datepicker. You should use some JavaScript based DateTimePickers. I could recommend flatpickr or pickmeup, they are made in Vanilla JavaScript and are very lightweight.
Solution 2:[2]
You can open the picker with inputElement.showPicker()
if it's of the type <input type="datetime-local">
.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/showPicker
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Der Alex |
Solution 2 |