Is there a JavaScript method to make a html date input display the datepicker?

南楼画角 提交于 2019-12-13 18:43:27

问题


I would like to trigger the display of a date input's date-picker from an external button.

<input id="date" type="date" />
<button>display date</button>

For instance if I had the above code, how would I show the date-picker (the box which appears and allows you to pick a date) by clicking the button? I do not want to use jQuery or other libraries. Is there a way to show the native date-picker from an external trigger with vanilla JavaScript?

I'm looking for something like this:

var button = document.querySelector("button");
button.onclick = () => {
    var input = document.querySelector("#date");
    input.showDatePicker();
}

回答1:


This works well on firefox and edge :

<input id="date" type="date" />
<button>display date</button>
<script type="text/javascript">
	var button = document.querySelector("button");
button.onclick = () => {
    var input = document.querySelector("#date");
    input.focus()
    input.click()
}
</script>



回答2:


You can with

let x = document.getElementById('myDate'),
  d = new Date(),
  m = d.getMonth() < 10 ? `0${d.getMonth()}` : `${d.getMonth()}`,
  day = d.getDay() < 10 ? `0${d.getDay()}` : `${d.getDay()}`;

x.value = d.getFullYear() + "-" + m + "-" + day;

Demo



来源:https://stackoverflow.com/questions/49088264/is-there-a-javascript-method-to-make-a-html-date-input-display-the-datepicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!