<input type="date">
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since апÑÐµÐ»Ñ 2021 г..
* Some parts of this feature may have varying levels of support.
ÐлеменÑÑ <input> Ñипа date ÑоздаÑÑ Ð¿Ð¾Ð»Ñ Ð²Ð²Ð¾Ð´Ð° и позволÑÑÑ Ð¿Ð¾Ð»ÑзоваÑÐµÐ»Ñ Ð²Ð²ÐµÑÑи даÑÑ, либо иÑполÑзоваÑÑ text box Ð´Ð»Ñ Ð°Ð²ÑомаÑиÑеÑкой пÑовеÑки конÑенÑа или иÑполÑзоваÑÑ ÑпеÑиалÑнÑй инÑеÑÑÐµÐ¹Ñ date picker. ÐозвÑаÑаемое знаÑение вклÑÑÐ°ÐµÑ Ð³Ð¾Ð´, меÑÑÑ, денÑ, но не вÑемÑ. ÐÑполÑзÑйÑе Ð¿Ð¾Ð»Ñ Ð²Ð²Ð¾Ð´Ð° time или datetime-local, ÑÑÐ¾Ð±Ñ Ð²Ð²Ð¾Ð´Ð¸ÑÑ Ð²ÑÐµÐ¼Ñ Ð¸Ð»Ð¸ даÑÑ+вÑÐµÐ¼Ñ ÑооÑвеÑÑÑвенно.
ÐÑобÑажение date ÑазлиÑаеÑÑÑ Ð² завиÑимоÑÑи Ð¾Ñ Ð±ÑаÑзеÑа, кÑоме Ñого не вÑе бÑаÑзеÑÑ Ð¿Ð¾Ð´Ð´ÐµÑживаÑÑ date. ÐодÑобнее Ñм. Browser compatibility. РнеподдеÑживаемÑÑ
бÑаÑзеÑаÑ
ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ð±ÑÐ´ÐµÑ Ð¾ÑобÑажаÑÑÑÑ ÐºÐ°Ðº обÑÑнÑй <input type="text">.
ÐнÑеÑакÑивнÑй пÑимеÑ
<label for="start">Start date:</label>
<input
type="date"
id="start"
name="trip-start"
value="2018-07-22"
min="2018-01-01"
max="2018-12-31" />
label {
display: block;
font:
1rem "Fira Sans",
sans-serif;
}
input,
label {
margin: 0.4rem 0;
}
СÑеди бÑаÑзеÑов Ñо Ñвоим инÑеÑÑейÑом Ð´Ð»Ñ Ð²ÑбоÑа даÑÑ, еÑÑÑ Ð¸Ð½ÑеÑÑÐµÐ¹Ñ Ð±ÑаÑзеÑов Chrome и Opera, коÑоÑÑй вÑглÑÐ´Ð¸Ñ Ñак:

Ð Edge он вÑглÑÐ´Ð¸Ñ Ñак:

Рв Firefox вÑглÑÐ´Ð¸Ñ Ñак:

| Value | ÐозвÑаÑÐ°ÐµÑ String, Ñ Ð´Ð°Ñой в ÑоÑмаÑе гггг-мм-дд, **или **пÑÑÑÑÑ ÑÑÑокÑ** |
|---|---|
| СобÑÑÐ¸Ñ | change и input |
| ÐоддеÑживаемÑе аÑÑибÑÑÑ | autocomplete, list, readonly, and step |
| IDL attributes | list, value, valueAsDate, valueAsNumber. |
| ÐеÑÐ¾Ð´Ñ | select(), stepDown(), stepUp() |
ÐнаÑение
ÐозвÑаÑÐ°ÐµÑ String, пÑедÑÑавлÑÑÑий знаÑение даÑÑ Ð²Ð²ÐµÐ´Ñнной в input. ÐÑ Ð¼Ð¾Ð¶ÐµÑе ÑÑÑановиÑÑ Ð·Ð½Ð°Ñение по ÑмолÑÐ°Ð½Ð¸Ñ Ð´Ð»Ñ ÑлеменÑа Ñ Ð¿Ð¾Ð¼Ð¾ÑÑÑ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð°ÑÑибÑÑа в value, напÑимеÑ:
<input id="date" type="date" value="2017-06-01" />
ÐÑимеÑание:
ÐомниÑе, ÑÑо оÑобÑажаемÑй ÑоÑÐ¼Ð°Ñ Ð´Ð°ÑÑ Ð¾ÑлиÑаеÑÑÑ Ð¾Ñ Ð½Ð°ÑÑоÑÑего знаÑÐµÐ½Ð¸Ñ value â оÑобÑажаемÑй ÑоÑÐ¼Ð°Ñ Ð´Ð°ÑÑ Ð±ÑÐ´ÐµÑ Ð²ÑбÑан, базиÑÑÑÑÑ Ð½Ð° ÑегионалÑнÑÑ
паÑамеÑÑаÑ
бÑаÑзеÑа полÑзоваÑелÑ, Ñогда как знаÑение value вÑегда Ð¸Ð¼ÐµÐµÑ ÑоÑÐ¼Ð°Ñ Ð³Ð³Ð³Ð³-мм-дд.
ÐÑ Ñакже можеÑе полÑÑиÑÑ Ð¸Ð»Ð¸ ÑÑÑановиÑÑ Ð·Ð½Ð°Ñение даÑÑ Ð² JavaScript Ñ Ð¿Ð¾Ð¼Ð¾ÑÑÑ ÑвойÑÑв value и valueAsNumber ÑлеменÑа input. ÐапÑимеÑ:
var dateControl = document.querySelector('input[type="date"]');
dateControl.value = "2017-06-01";
console.log(dateControl.value); // prints "2017-06-01"
console.log(dateControl.valueAsNumber); // prints 1496275200000, a JavaScript timestamp (ms)
ÐÑÐ¾Ñ ÐºÐ¾Ð´ вÑбиÑÐ°ÐµÑ Ð¿ÐµÑвÑй ÑÐ»ÐµÐ¼ÐµÐ½Ñ <input>, type коÑоÑого date и ÑÑÑÐ°Ð½Ð°Ð²Ð»Ð¸Ð²Ð°ÐµÑ Ð·Ð½Ð°Ñение даÑÑ Ð² 2017-06-01 (1 ÐÑÐ½Ñ 2017). ÐаÑем он ÑÑиÑÑÐ²Ð°ÐµÑ ÑÑо знаÑение обÑаÑно в ÑÑÑоковом и ÑиÑловом ÑоÑмаÑаÑ
.
ÐополниÑелÑнÑе аÑÑибÑÑÑ
Рдополнение к обÑим аÑÑибÑÑам Ð´Ð»Ñ Ð²ÑеÑ
ÑлеменÑов <input>, Ñ "date" еÑÑÑ ÑледÑÑÑие дополниÑелÑнÑе аÑÑибÑÑÑ:
| ÐÑÑибÑÑ | ÐпиÑание |
|---|---|
max |
ÐакÑималÑно Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð°Ñ Ð´Ð°Ñа Ð´Ð»Ñ ÑÑÑановки |
min |
ÐинималÑно Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð°Ñ Ð´Ð°Ñа Ð´Ð»Ñ ÑÑÑановки |
step |
Шаг (в днÑÑ ), Ñ ÐºÐ¾ÑоÑÑм бÑÐ´ÐµÑ Ð¸Ð·Ð¼ÐµÐ½ÑÑÑÑÑ Ð´Ð°Ñа пÑи нажаÑии кнопок вниз или ввеÑÑ Ð´Ð°Ð½Ð½Ð¾Ð³Ð¾ ÑлеменÑа |
max
ÐакÑималÑно Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð°Ñ Ð´Ð°Ñа Ð´Ð»Ñ ÑÑÑановки. ÐÑли value ÑвлÑеÑÑÑ Ð±Ð¾Ð»ÐµÐµ поздней даÑой, Ñем даÑа, ÑÐºÐ°Ð·Ð°Ð½Ð½Ð°Ñ Ð² аÑÑибÑÑе max, ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ð¾ÑобÑÐ°Ð·Ð¸Ñ Ð¾ÑÐ¸Ð±ÐºÑ Ð¿Ñи помоÑи constraint validation. ÐÑли в аÑÑибÑÑе max Ñказано знаÑение, не ÑдовлеÑвоÑÑÑÑее ÑоÑмаÑÑ yyyy-MM-dd, знаÑÐ¸Ñ ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ð½Ðµ бÑÐ´ÐµÑ Ð¸Ð¼ÐµÑÑ Ð¼Ð°ÐºÑималÑной даÑÑ.
РаÑÑибÑÑе max должна бÑÑÑ Ñказана ÑÑÑока Ñ Ð´Ð°Ñой, коÑоÑÐ°Ñ Ð±Ð¾Ð»ÑÑе или Ñавна даÑе, Ñказанной в аÑÑибÑÑе min.
min
ÐинималÑно Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð°Ñ Ð´Ð°Ñа Ð´Ð»Ñ ÑÑÑановки. ÐÑли value ÑвлÑеÑÑÑ Ð±Ð¾Ð»ÐµÐµ Ñанней даÑой, Ñем даÑа, ÑÐºÐ°Ð·Ð°Ð½Ð½Ð°Ñ Ð² аÑÑибÑÑе min, ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ð¾ÑобÑÐ°Ð·Ð¸Ñ Ð¾ÑÐ¸Ð±ÐºÑ Ð¿Ñи помоÑи constraint validation. ÐÑли в аÑÑибÑÑе min Ñказано знаÑение, не ÑдовлеÑвоÑÑÑÑее ÑоÑмаÑÑ yyyy-MM-dd, знаÑÐ¸Ñ ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ð½Ðµ бÑÐ´ÐµÑ Ð¸Ð¼ÐµÑÑ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ñной даÑÑ.
РаÑÑибÑÑе min должна бÑÑÑ Ñказана ÑÑÑока Ñ Ð´Ð°Ñой, коÑоÑÐ°Ñ Ð¼ÐµÐ½ÑÑе или Ñавна даÑе, Ñказанной в аÑÑибÑÑе max.
step
ÐÑÑибÑÑ step â ÑÑо ÑиÑло, ÑказÑваÑÑее ÑÑÐ¾Ð²ÐµÐ½Ñ ÑоÑноÑÑи, коÑоÑÐ¾Ð¼Ñ Ð´Ð¾Ð»Ð¶Ð½Ð¾ ÑооÑвеÑÑÑвоваÑÑ Ð·Ð½Ð°Ñение, или оÑобое знаÑение any, коÑоÑое опиÑано ниже. ÐопÑÑÑÐ¸Ð¼Ñ ÑолÑко знаÑениÑ, ÑооÑвеÑÑÑвÑÑÑие оÑÐ½Ð¾Ð²Ð°Ð½Ð¸Ñ (min, еÑли Ñказано, value в пÑоÑивном ÑлÑÑае или лÑбое подÑ
одÑÑее знаÑение по ÑмолÑаниÑ, еÑли не Ñказано ни Ñо, ни дÑÑгое).
СÑÑоковое знаÑение any ознаÑаеÑ, ÑÑо поÑаговое изменение не подÑазÑмеваеÑÑÑ Ð¸ ÑазÑеÑÐµÐ½Ñ Ð»ÑбÑе знаÑÐµÐ½Ð¸Ñ (за иÑклÑÑением дÑÑгиÑ
огÑаниÑений, ÑакиÑ
как min and max).
ÐÑимеÑание: Ðогда введÑннÑе полÑзоваÑелем даннÑе не ÑооÑвеÑÑÑвÑÑÑ Ð¿Ð¾Ñаговой конÑигÑÑаÑии, Ð°Ð³ÐµÐ½Ñ Ð¿Ð¾Ð»ÑзоваÑÐµÐ»Ñ Ð¼Ð¾Ð¶ÐµÑ Ð¸ÑполÑзоваÑÑ Ð¾ÐºÑÑгление до ближайÑего допÑÑÑимого знаÑениÑ, пÑедпоÑиÑÐ°Ñ ÑиÑла в положиÑелÑном напÑавлении, когда еÑÑÑ Ð´Ð²Ð° одинаково Ð±Ð»Ð¸Ð·ÐºÐ¸Ñ Ð²Ð°ÑианÑа.
ÐÐ»Ñ Ð¿Ð¾Ð»ÐµÐ¹ ввода date знаÑение step задаÑÑÑÑ Ð² днÑÑ
; и ÑвлÑеÑÑÑ ÐºÐ¾Ð»Ð¸ÑеÑÑвом миллиÑекÑнд, Ñавное 86 400 000 ÑмножиÑÑ Ð½Ð° знаÑение step (полÑÑаемое ÑиÑловое знаÑение Ñ
ÑаниÑÑÑ Ð² миллиÑекÑндаÑ
). СÑандаÑÑное знаÑение step Ñавно 1, ÑÑо ознаÑÐ°ÐµÑ 1 денÑ.
ÐÑимеÑание:
ÐÐ»Ñ Ð¿Ð¾Ð»ÐµÐ¹ ввода date Ñказание Ð´Ð»Ñ step знаÑÐµÐ½Ð¸Ñ any даÑÑ Ñакой же ÑÑÑекÑ, ÑÑо и знаÑение 1.
ÐÑполÑзование полей ввода c Ñипом date
Ðа пеÑвÑй взглÑд, ÑÐ»ÐµÐ¼ÐµÐ½Ñ <input type="date"> вÑглÑÐ´Ð¸Ñ Ð·Ð°Ð¼Ð°Ð½Ñиво â он пÑедоÑÑавлÑÐµÑ Ð»Ñгкий гÑаÑиÑеÑкий инÑеÑÑÐµÐ¹Ñ Ð´Ð»Ñ Ð²ÑбоÑа даÑÑ, ноÑмализÑÐµÑ ÑоÑÐ¼Ð°Ñ Ð´Ð°ÑÑ, оÑпÑавлÑемой на ÑеÑÐ²ÐµÑ Ð½ÐµÐ·Ð°Ð²Ð¸Ñимо Ð¾Ñ Ð»Ð¾ÐºÐ°Ð»ÑнÑÑ
наÑÑÑоек полÑзоваÑелÑ. Тем не менее, еÑÑÑ Ð¿ÑÐ¾Ð±Ð»ÐµÐ¼Ñ Ñ <input type="date"> в ÑвÑзи Ñ Ð¾Ð³ÑаниÑенной поддеÑжкой бÑаÑзеÑов.
Ð ÑÑом Ñазделе Ð¼Ñ Ð¿Ð¾ÑмоÑÑим на пÑоÑÑÑе, а заÑем и более ÑложнÑе ÑпоÑÐ¾Ð±Ñ Ð¸ÑполÑÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ <input type="date">, и позже дадим ÑовеÑÑ Ð¿Ð¾ ÑменÑÑÐµÐ½Ð¸Ñ Ð²Ð»Ð¸ÑÐ½Ð¸Ñ Ð¿Ð¾Ð´Ð´ÐµÑжки бÑаÑзеÑами (ÑмоÑÑиÑе Handling browser support).
ÐÑимеÑание: ÐадеемÑÑ, Ñо вÑеменем поддеÑжка бÑаÑзеÑами ÑÑÐ°Ð½ÐµÑ Ð¿Ð¾Ð²ÑемеÑÑной, и ÑÑа пÑоблема иÑÑезнеÑ.
Ðак иÑполÑзоваÑÑ date?
СамÑй пÑоÑÑой ÑпоÑоб иÑполÑзоваÑÑ <input type="date"> - ÑÑо иÑполÑзоваÑÑ ÐµÐ³Ð¾ Ñ ÑлеменÑами <input> и label, как показано ниже:
<form>
<div>
<label for="bday">ÐведиÑе даÑÑ Ð²Ð°Ñего ÑождениÑ:</label>
<input type="date" id="bday" name="bday" />
</div>
</form>
УÑÑановка макÑималÑной и минималÑной даÑÑ
ÐÑ Ð¼Ð¾Ð¶ÐµÑе иÑполÑзоваÑÑ Ð°ÑÑибÑÑÑ min и max, ÑÑÐ¾Ð±Ñ Ð¾Ð³ÑаниÑиÑÑ Ð´Ð°ÑÑ, коÑоÑÑÑ Ð¼Ð¾Ð¶ÐµÑ Ð²ÑбÑаÑÑ Ð¿Ð¾Ð»ÑзоваÑелÑ. Ð ÑледÑÑÑем пÑимеÑе Ð¼Ñ ÑÑÑанавливаем минималÑнÑÑ Ð´Ð°ÑÑ 2017-04-01 и макÑималÑнÑÑ Ð´Ð°ÑÑ 2017-04-30. ÐолÑзоваÑÐµÐ»Ñ ÑÐ¼Ð¾Ð¶ÐµÑ Ð²ÑбÑаÑÑ Ð´Ð°ÑÑ ÑолÑко из ÑÑого диапазона:
<form>
<div>
<label for="party">УкажиÑе пÑедпоÑÑиÑелÑнÑÑ Ð´Ð°ÑÑ ÑобÑÑиÑ:</label>
<input
type="date"
id="party"
name="party"
min="2017-04-01"
max="2017-04-30" />
</div>
</form>
Ð ÑезÑлÑÑаÑе вÑÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ ÐºÐ¾Ð´Ð°, полÑзоваÑÐµÐ»Ñ ÑÐ¼Ð¾Ð¶ÐµÑ Ð²ÑбÑаÑÑ Ð»Ñбой Ð´ÐµÐ½Ñ Ð°Ð¿ÑÐµÐ»Ñ 2017 года, но не ÑÐ¼Ð¾Ð¶ÐµÑ Ð²ÑбÑаÑÑ Ð¸ даже пÑоÑмоÑÑеÑÑ Ð´Ð½Ð¸ дÑÑÐ³Ð¸Ñ Ð¼ÐµÑÑÑев и годов, в Ñом ÑиÑле ÑеÑез Ð²Ð¸Ð´Ð¶ÐµÑ date picker.
ÐÑимеÑание:
ÐÑ Ð´Ð¾Ð»Ð¶Ð½Ñ ÑмеÑÑ Ð¸ÑполÑзоваÑÑ Ð°ÑÑибÑÑ step, ÑÑÐ¾Ð±Ñ Ð¼ÐµÐ½ÑÑÑ ÐºÐ¾Ð»Ð¸ÑеÑÑво дней, на коÑоÑое бÑÐ´ÐµÑ Ð¿ÑоиÑÑ
одиÑÑ Ñаг пÑи изменении даÑÑ (напÑимеÑ, ÑÑÐ¾Ð±Ñ ÑделаÑÑ Ð²ÑбиÑаемÑми ÑолÑко ÑÑббоÑÑ). Ðднако, не поÑ
оже, ÑÑо ÑÑо где-Ñо пÑименÑлоÑÑ Ð½Ð° даннÑй моменÑ.
Controlling input size
<input type="date"> doesn't support form sizing attributes such as size. You'll have to resort to CSS for sizing needs.
Validation
By default, <input type="date"> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date â which is helpful â but you can still leave the field empty or (in browsers where the input falls back to type text) enter an invalid date (e.g. the 32nd of April).
If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you'll have to check the results to be sure the value is within these dates, since they're only enforced if the date picker is fully supported on the user's device.
In addition, you can use the required attribute to make filling in the date mandatory â again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.
Let's look at an example â here we've set minimum and maximum dates, and also made the field required:
<form>
<div>
<label for="party"
>Choose your preferred party date (required, April 1st to 20th):</label
>
<input
type="date"
id="party"
name="party"
min="2017-04-01"
max="2017-04-20"
required />
<span class="validity"></span>
</div>
<div>
<input type="submit" />
</div>
</form>
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here's a screenshot for those of you who aren't using a supporting browser:

Here's the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a <span> next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively.
div {
margin-bottom: 10px;
display: flex;
align-items: center;
}
label {
display: inline-block;
width: 300px;
}
input:invalid + span:after {
content: "â";
padding-left: 5px;
}
input:valid + span:after {
content: "â";
padding-left: 5px;
}
ÐÑедÑпÑеждение: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).
Handling browser support
As mentioned above, the major problem with using date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:

Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
The second problem is the more serious of the two; as we mentioned earlier, with a date input, the actual value is always normalized to the format yyyy-mm-dd. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates, for example:
ddmmyyyydd/mm/yyyymm/dd/yyyydd-mm-yyyymm-dd-yyyyMonth dd yyyy
One way around this is to put a pattern attribute on your date input. Even though the date input doesn't use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:
<form>
<div>
<label for="bday">Enter your birthday:</label>
<input
type="date"
id="bday"
name="bday"
required
pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" />
<span class="validity"></span>
</div>
<div>
<input type="submit" />
</div>
</form>
If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern nnnn-nn-nn, where n is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates, such as yyyy-dd-mm (whereas we want yyyy-mm-dd). So we still have a problem.
The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls (<select> elements being popular; see below for an implementation), or to use a JavaScript library such as jQuery date picker.
Examples
In this example we create two sets of UI elements for choosing dates: a native <input type="date"> picker and a set of three <select> elements for choosing dates in older browsers that don't support the native input.
HTML
The HTML looks like so:
<form>
<div class="nativeDatePicker">
<label for="bday">Enter your birthday:</label>
<input type="date" id="bday" name="bday" />
<span class="validity"></span>
</div>
<p class="fallbackLabel">Enter your birthday:</p>
<div class="fallbackDatePicker">
<span>
<label for="day">Day:</label>
<select id="day" name="day"></select>
</span>
<span>
<label for="month">Month:</label>
<select id="month" name="month">
<option selected>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</span>
<span>
<label for="year">Year:</label>
<select id="year" name="year"></select>
</span>
</div>
</form>
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)
JavaScript
The other part of the code that may be of interest is the feature detection code â to detect whether the browser supports <input type="date">, we create a new <input> element, set its type to date, then immediately check what its type is set to â non-supporting browsers will return text, because the date type falls back to type text. If <input type="date"> is not supported, we hide the native picker and show the fallback picker UI (<select>) instead.
// define variables
var nativePicker = document.querySelector(".nativeDatePicker");
var fallbackPicker = document.querySelector(".fallbackDatePicker");
var fallbackLabel = document.querySelector(".fallbackLabel");
var yearSelect = document.querySelector("#year");
var monthSelect = document.querySelector("#month");
var daySelect = document.querySelector("#day");
// hide fallback initially
fallbackPicker.style.display = "none";
fallbackLabel.style.display = "none";
// test whether a new date input falls back to a text input or not
var test = document.createElement("input");
test.type = "date";
// if it does, run the code inside the if() {} block
if (test.type === "text") {
// hide the native picker and show the fallback
nativePicker.style.display = "none";
fallbackPicker.style.display = "block";
fallbackLabel.style.display = "block";
// populate the days and years dynamically
// (the months are always the same, therefore hardcoded)
populateDays(monthSelect.value);
populateYears();
}
function populateDays(month) {
// delete the current set of <option> elements out of the
// day <select>, ready for the next set to be injected
while (daySelect.firstChild) {
daySelect.removeChild(daySelect.firstChild);
}
// Create variable to hold new number of days to inject
var dayNum;
// 31 or 30 days?
if (
month === "January" ||
month === "March" ||
month === "May" ||
month === "July" ||
month === "August" ||
month === "October" ||
month === "December"
) {
dayNum = 31;
} else if (
month === "April" ||
month === "June" ||
month === "September" ||
month === "November"
) {
dayNum = 30;
} else {
// If month is February, calculate whether it is a leap year or not
var year = yearSelect.value;
var leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
dayNum = leap ? 29 : 28;
}
// inject the right number of new <option> elements into the day <select>
for (i = 1; i <= dayNum; i++) {
var option = document.createElement("option");
option.textContent = i;
daySelect.appendChild(option);
}
// if previous day has already been set, set daySelect's value
// to that day, to avoid the day jumping back to 1 when you
// change the year
if (previousDay) {
daySelect.value = previousDay;
// If the previous day was set to a high number, say 31, and then
// you chose a month with less total days in it (e.g. February),
// this part of the code ensures that the highest day available
// is selected, rather than showing a blank daySelect
if (daySelect.value === "") {
daySelect.value = previousDay - 1;
}
if (daySelect.value === "") {
daySelect.value = previousDay - 2;
}
if (daySelect.value === "") {
daySelect.value = previousDay - 3;
}
}
}
function populateYears() {
// get this year as a number
var date = new Date();
var year = date.getFullYear();
// Make this year, and the 100 years before it available in the year <select>
for (var i = 0; i <= 100; i++) {
var option = document.createElement("option");
option.textContent = year - i;
yearSelect.appendChild(option);
}
}
// when the month or year <select> values are changed, rerun populateDays()
// in case the change affected the number of available days
yearSelect.onchange = function () {
populateDays(monthSelect.value);
};
monthSelect.onchange = function () {
populateDays(monthSelect.value);
};
//preserve day selection
var previousDay;
// update what day has been set to previously
// see end of populateDays() for usage
daySelect.onchange = function () {
previousDay = daySelect.value;
};
ÐÑимеÑание: Remember that some years have 53 weeks in them (see Weeks per year)! You'll need to take this into consideration when developing production apps.
СпеÑиÑикаÑии
| Specification |
|---|
| HTML > # date-state-(type=date) > |
СовмеÑÑимоÑÑÑ Ñ Ð±ÑаÑзеÑами
СмоÑÑиÑе Ñакже
- The generic
<input>element and the interface used to manipulate it,HTMLInputElement - Date and Time picker tutorial