HTML has a special input type for dates, like this:
<input type="date">. In supporting browsers (pretty good), users will get UI for selecting a date. Super useful stuff, especially since it falls back to a usable
text input. But how do you set it to a particular day?
To set a particular day, you’ll need to set the
value to a YYYY-MM-DD format, like this:
<input type="date" value="1980-08-26">
placeholder won’t do anything in a browser that supports date inputs. Date inputs can have
max, so only a date between a particular range can be selected. Those take the same format. Just for fun we’ve used a step value here to make only Tuesday selectable:
<input type="date" min="2017-08-15" max="2018-08-26" step="7">
<input id="today" type="date">
let today = new Date().toISOString().substr(0, 10); document.querySelector("#today").value = today; // or... document.querySelector("#today").valueAsDate = new Date();
It’s also possible to select a specific week or month. Prefilling those is like this:
<input type="week" value="2014-W02"> <input type="month" value="2018-08">
If you need both date and time, there is an input for that as well. Just for fun
<input type="datetime-local" value="2017-06-13T13:00">
Or just time! Here we’ll use step again just for fun to limit it to 15 minute increments:
<input type="time" value="13:00" step="900">
See the Pen Prefilling HTML date inputs by Chris Coyier (@chriscoyier) on CodePen.
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Mobile / Tablet
|iOS Safari||Opera Mobile||Opera Mini||Android||Android Chrome||Android Firefox|
Prefilling a Date Input is a post from CSS-Tricks