Tuesday, 29 August 2017

Prefilling a Date Input

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">

Minor note: placeholder won't do anything in a browser that supports date inputs. Date inputs can have min and 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">

How about defaulting the input to the value of today? Unfortunately, there is no HTML-only solution for that, but it's possible with JavaScript.

<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">

Live Demo

See the Pen Prefilling HTML date inputs by Chris Coyier (@chriscoyier) on CodePen.

Support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
20 9 57 No 13 No

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
11 10 No 4.4 59 55

Prefilling a Date Input is a post from CSS-Tricks



from CSS-Tricks http://ift.tt/2wfpYqH
via IFTTT

No comments:

Post a Comment

Passkeys: What the Heck and Why?

These things called  passkeys  sure are making the rounds these days. They were a main attraction at  W3C TPAC 2022 , gained support in  Saf...