In the past when you needed a date picker input you had to use a plug-in or program one yourself.
All modern html5 compatible web browsers have a built-in input type="date" that is super
input element is shown below:
The code for a more practical date input element is shown below:
This example uses the element's onchange event to execute a function showDate to
access the date that the user has set. The code for the showDate function is dhown below:
var x = document.getElementById("myDate").value;
<input type="date" value="2018-01-08">
If you want to set the date displayed to a specific date, date simply use the date element's value
property. But the date that you provide must be in the yyyy-mm-dd format: (yyyy = year, mm = month
e.g. 01 for January, dd = day in two digits).
window.onload = function()
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById("theDate").value = today;
<input type="date" id="theDate">
Note that this function is called by the window.onload event so that the current date is
displayed immediately as the page loads. Of course you can combine this with use of the onchange
event to access the new date that the user has set.
To allow the user to choose a date range, use two date input elements as shown below:
The code for a date range picker is shown below:
var f = document.getElementById("from").value;
var t = document.getElementById("to").value;
var fromDate = f.replace(/-/g, "");
var toDate = t.replace(/-/g, "");
if(fromDate > toDate) document.getElementById("to").value = f;
A possible problem with a date range picker is that the user sets the to date to an earlier
date than the from date. There are several way to deal with that possibility. In the code shown
above, if the to date is before the from date, the code sets the to date to the
same as the from date. Note that before a comparison test is performed on the dates, the
hyphens are removed from the dates by use of a regular expression.
Of course you can combine this with the earlier function called by the window.onload event
to first set the from and to dates to the current date.