aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/html/element/input/datetime-local/index.html
blob: 99ddddd6bdb4e238ba0fae361f313b1a5559361d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
---
title: <input type="datetime-local">
slug: Web/HTML/Element/Input/datetime-local
translation_of: Web/HTML/Element/input/datetime-local
---
<p>{{HTMLRef}}</p>

<p>{{htmlelement("input")}} элемент типа <strong><code>datetime-local</code></strong> создает поля ввода, позволяющие легко ввести дату и время —  год, месяц, день, часы и минуты.</p>

<p>Интерфейс управления варьируется от браузера к браузеру, на данный момент поддержка носит фрагментарный характер, только с Chrome/Opera  и EDGE на рабочем столе — и большинство современных мобильных версиях браузера — наличие полезной реализации. В других браузерах элемент управления сводиться до простого <code><a href="/en-US/docs/Web/HTML/Element/input/text">&lt;input type="text"&gt;</a></code>.</p>

<div id="Basic_example">
<pre class="brush: html">&lt;input id="datetime" type="datetime-local"&gt;</pre>

<p>{{ EmbedLiveSample('Basic_example', 600, 40) }}</p>
</div>

<p>Для тех из вас, кто не использует поддерживающий браузер, Chrome/Opera datetime-local control выглядит как скриншот ниже. Нажатие на стрелку вниз с правой стороны приводит к выбору даты, чтобы вы могли выбрать дату; вы должны ввести время вручную.</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/14949/datetime-local-chrome.png" style="display: block; height: 224px; margin: 0px auto; width: 280px;"></p>

<p>В Edge <code>datetime-local</code> элемент управления выглядит как на скриншоте ниже. Клик на дате и времени отобразит два отдельных поля выбора, чтобы Вы могли легко установить дату и время. То есть, по сути, получаем два элемента <code>date</code> и <code>time</code>, объединенных в один:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/14953/datetime-local-picker-edge1.png" style="display: block; height: 398px; margin: 0px auto; width: 320px;"></p>

<p><img alt="" src="https://mdn.mozillademos.org/files/14955/datetime-local-picker-edge2.png" style="display: block; height: 394px; margin: 0px auto; width: 264px;"></p>

<table class="properties">
 <tbody>
  <tr>
   <td><strong>{{anch("Value")}}</strong></td>
   <td>A {{domxref("DOMString")}} representing a date and time, or empty.</td>
  </tr>
  <tr>
   <td><strong>события</strong></td>
   <td>{{event("change")}} и {{event("input")}}.</td>
  </tr>
  <tr>
   <td><strong>Supported Common Attributes</strong></td>
   <td>{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("readonly", "input")}}, and {{htmlattrxref("step", "input")}}.</td>
  </tr>
  <tr>
   <td><strong>IDL attributes</strong></td>
   <td><code>list</code>, <code>value</code>, <code>valueAsNumber</code>.</td>
  </tr>
  <tr>
   <td><strong>методы</strong></td>
   <td>{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}.</td>
  </tr>
 </tbody>
</table>

<h2 id="Значение">Значение</h2>

<p> {{domxref("DOMString")}} представление значения даты, введенной во входные данные. Вы можете установить значение по умолчанию для ввода, включая дату внутри {{htmlattrxref("value", "input")}} атрибута, как:</p>

<pre class="brush: html">&lt;label for="party"&gt;Enter a date and time for your party booking:&lt;/label&gt;
&lt;input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30"&gt;</pre>

<p>{{ EmbedLiveSample('Value', 600, 60) }}</p>

<p>Одна вещь, чтобы отметить, что отображаемый формат даты отличается от фактического <code>значения</code> — отображаемый формат даты будет выбран на основе установленного языкового стандарта операционной системы пользователя, в то время как дата<code>значение</code> всегда форматируется <code>yyyy-MM-ddThh:mm</code>. Когда значение передается на сервер, например, это будет выглядеть <code>partydate=2017-06-01T08:30</code>.</p>

<div class="note">
<p><strong>Примечание</strong>: также имейте в виду, что если такие данные поступают через http-запрос Get, двоеточие нужно экранировать для включения в параметры URL, например <code>partydate=2017-06-01T08%3A30</code>.</p>
</div>

<p>Вы также можете получить и установить значение даты в JavaScript, используя {{domxref("HTMLInputElement.value")}} свойство, например:</p>

<pre class="brush: js">var dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = '2017-06-01T08:30';</pre>

<h2 id="Использование_локальных_входных_данных_datetime">Использование локальных входных данных datetime</h2>

<p>Ввод даты и времени выглядит удобно на первый взгляд — он обеспечивает простой пользовательский интерфейс для выбора даты и времени, и они нормализуют формат данных, отправляемых на сервер, независимо от локали пользователя. Тем не менее, есть проблемы с <code>&lt;input type="datetime-local"&gt;</code> из-за ограниченной поддержки браузера.</p>

<p>Мы рассмотрим основные и более сложные способы использования <code>&lt;input type="datetime-local"&gt;</code>, затем предложим советы по устранению проблемы поддержки браузера позже (see {{anch("Handling browser support")}}).</p>

<h3 id="Базовое_использование_локальных_полей_ввода_datetime">Базовое использование локальных полей ввода datetime</h3>

<p>Самое простои использование <code>&lt;input type="datetime-local"&gt;</code> включает комбинацию базового <code>&lt;input&gt;</code> и {{htmlelement("label")}} элемента, как в примере ниже:</p>

<pre class="brush: html">&lt;form&gt;
    &lt;label for="party"&gt;Enter a date and time for your party booking:&lt;/label&gt;
    &lt;input id="party" type="datetime-local" name="partydate"&gt;
&lt;/form&gt;</pre>

<p>{{ EmbedLiveSample('Basic_uses_of_datetime-local', 600, 40) }}</p>

<h3 id="Установка_максимума_и_минимума_даты_и_времени">Установка максимума и минимума даты и времени</h3>

<p>Вы можете использовать {{htmlattrxref("min", "input")}} и {{htmlattrxref("max", "input")}} аттрибуты чтобы ограничить дату/время, которое может выбрать пользователь. В примере ниже мы устанавливает минимальные дату и время в <code>2017-06-01T08:30</code> и максимальные в <code>2017-06-30T16:30</code>:</p>

<pre class="brush: html">  &lt;form&gt;
    &lt;label for="party"&gt;Enter a date and time for your party booking:&lt;/label&gt;
    &lt;input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30"&gt;
  &lt;/form&gt;</pre>

<p>{{ EmbedLiveSample('Setting_maximum_and_minimum_dates_and_times', 600, 40) }}</p>

<p>Как результат:</p>

<ul>
 <li>Могут быть выбраны только дни из Июня 2017 — только дни, которые входят в заданный диапазон дат доступны для выбота, и в виджете нельзя увидеть даты, не принадлежaщие Июню.</li>
 <li>В зависимости от того, какой браузер Вы используете, Вы можете заметить, что вребя вне заданного диапазона не доступно к выбору (e.g. Edge), или доступно к выбору(e.g. Chrome) но невалидно (see {{anch("Validation")}}).</li>
</ul>

<div class="note">
<p><strong>Примечание</strong>: Существует возможность использовать {{htmlattrxref("step", "input")}} аттрибут для того, чтобы установить количество дней, которые будут пропущены каждый раз, когда дата увеличивается (например, если Вы хотите сделать доступными для выбора только Субботы). Однако, на момент написание этой статьи это нет эффективной реализации этой функции.</p>
</div>

<h3 id="Controlling_input_size">Controlling input size</h3>

<p><code>&lt;input type="datetime-local"&gt;</code> doesn't support form sizing attributes such as {{htmlattrxref("size", "input")}}. You'll have to resort to <a href="/en-US/docs/Web/CSS">CSS</a> for sizing needs.</p>

<h3 id="Setting_timezones">Setting timezones</h3>

<p>One thing the <code>datetime-local</code> input type doesn't provide is a way to set the timezone/locale of the datetime. This was available in the <code><a href="/en-US/docs/Web/HTML/Element/input/datetime">datetime</a></code> input type, but this type is now obsolete, having been removed from the spec. The main reasons why this was removed are a lack of implementation in browsers, and concerns over the user interface/experience. It is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control.</p>

<p>For example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in a <code><a href="/en-US/docs/Web/HTML/Element/input/hidden">hidden</a></code> input type. For example:</p>

<pre class="brush: html">&lt;input type="hidden" id="timezone" name="timezone" value="-08:00"&gt;</pre>

<p>On the other hand, if you were required to allow the user to enter a timezone along with a datetime entry, you could provide a means of inputting a timezone, such as a {{htmlelement("select")}} element:</p>

<pre class="brush: html">&lt;select name="timezone_offset" id="timezone-offset" class="span5"&gt;
    &lt;option value="-12:00"&gt;(GMT -12:00) Eniwetok, Kwajalein&lt;/option&gt;
    &lt;option value="-11:00"&gt;(GMT -11:00) Midway Island, Samoa&lt;/option&gt;
    &lt;option value="-10:00"&gt;(GMT -10:00) Hawaii&lt;/option&gt;
    &lt;option value="-09:50"&gt;(GMT -9:30) Taiohae&lt;/option&gt;
    &lt;option value="-09:00"&gt;(GMT -9:00) Alaska&lt;/option&gt;
    &lt;option value="-08:00"&gt;(GMT -8:00) Pacific Time (US &amp;amp; Canada)&lt;/option&gt;

  ...

&lt;/select&gt;</pre>

<p>In either case, the timedate and timezone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side.</p>

<div class="note">
<p><strong>Note</strong>: The above code snippet is taken from <a href="https://gist.github.com/nodesocket/3919205">All world timezones in an HTML select element</a>.</p>
</div>

<h2 id="Validation">Validation</h2>

<p>By default, <code>&lt;input type="datetime-local"&gt;</code> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a datetime — which is helpful — but you can still fill in no value and submit, or enter an invalid datetime (e.g. the 32th of April).</p>

<p>You can use {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} to restrict the available dates (see anch("Setting maximum and minimum dates")), and in addition use the {{htmlattrxref("required", "input")}} attribute to make filling in the date mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field.</p>

<p>Let's look at an example — here we've set minimum and maximum datetimes, and also made the field required:</p>

<pre class="brush: html">&lt;form&gt;
    &lt;div&gt;
        &lt;label for="party"&gt;Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm):&lt;/label&gt;
        &lt;input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30" required&gt;
        &lt;span class="validity"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;input type="submit" value="Book party!"&gt;
    &lt;/div&gt;
&lt;/form&gt;</pre>

<p>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:</p>

<p>{{ EmbedLiveSample('Validation', 600, 120) }}</p>

<p>Here's'a screenshot for those of you who aren't using a supporting browser:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/14957/datetime-local-error.png" style="display: block; height: 100px; margin: 0px auto; width: 558px;"></p>

<p>Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":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 {{htmlelement("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.</p>

<pre class="brush: css">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;
}</pre>

<div class="warning">
<p><strong>Important</strong>: HTML form validation is <em>not</em> 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).</p>
</div>

<h2 id="Handling_browser_support">Handling browser support</h2>

<p>As mentioned above, the major problem with using date inputs at the time of writing is browser support — only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile. As an example, the <code>datetime-local</code> picker on Firefox for Android looks like this:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/14951/datetime-local-fxa.png" style="display: block; height: 640px; margin: 0px auto; width: 360px;"></p>

<p>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.</p>

<p>The second problem is the most serious — as we mentioned earlier, with a <code>datetime-local</code> input the actual value is always normalized to the format <code>yyyy-mm-ddThh:mm</code>. 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 and times, for example:</p>

<ul>
 <li><code>ddmmyyyy</code></li>
 <li><code>dd/mm/yyyy</code></li>
 <li><code>mm/dd/yyyy</code></li>
 <li><code>dd-mm-yyyy</code></li>
 <li><code>mm-dd-yyyy</code></li>
 <li><code>mm-dd-yyyy hh:mm</code> (12 hour clock)</li>
 <li><code>mm-dd-yyyy hh:mm</code> (24 hour clock)</li>
 <li>etc.</li>
</ul>

<p>One way around this is to put a {{htmlattrxref("pattern", "input")}} attribute on your <code>datetime-local</code> input. Even though the <code>datetime-local</code> input doesn't use it, the text input fallback will. For example, try viewing the following demo in a non-supporting browser:</p>

<pre class="brush: html">&lt;form&gt;
  &lt;div&gt;
    &lt;label for="party"&gt;Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm):&lt;/label&gt;
    &lt;input id="party" type="datetime-local" name="partydate"
           min="2017-06-01T08:30" max="2017-06-30T16:30"
           pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" required&gt;
    &lt;span class="validity"&gt;&lt;/span&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;input type="submit" value="Book party!"&gt;
  &lt;/div&gt;
  &lt;input type="hidden" id="timezone" name="timezone" value="-08:00"&gt;
&lt;/form&gt;</pre>

<p>{{ EmbedLiveSample('Handling_browser_support', 600, 100) }}</p>

<p>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 <code>nnnn-nn-nnTnn:nn</code>, where <code>n</code> is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates and times.</p>

<p>And what user is going to understand the pattern they need to enter the time and date in?</p>

<p>We still have a problem.</p>

<div class="hidden">
<pre class="brush: css">div {
  margin-bottom: 10px;
}

input:invalid + span {
  position: relative;
}

input:invalid + span:after {
  content: '✖';
  position: absolute;
  right: -18px;
}

input:valid + span {
  position: relative;
}

input:valid + span:after {
  content: '✓';
  position: absolute;
  right: -18px;
}</pre>
</div>

<p>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, year, and time in separate controls ({{htmlelement("select")}} elements being popular — see below for an implementation), or use JavaScript libraries such as <a href="https://jqueryui.com/datepicker/">jQuery date picker</a>, and the <a href="http://timepicker.co/">jQuery timepicker plugin</a>.</p>

<h2 id="Examples">Examples</h2>

<p>In this example we create two sets of UI elements for choosing datetimes — a native <code>&lt;input type="datetime-local"&gt;</code> picker, and a set of five {{htmlelement("select")}} elements for choosing dates and times in older browsers that don't support the native input.</p>

<p>{{ EmbedLiveSample('Examples', 600, 140) }}</p>

<p>The HTML looks like so:</p>

<pre class="brush: html">&lt;form&gt;
  &lt;div class="nativeDateTimePicker"&gt;
    &lt;label for="party"&gt;Choose a date and time for your party:&lt;/label&gt;
    &lt;input type="datetime-local" id="party" name="bday"&gt;
    &lt;span class="validity"&gt;&lt;/span&gt;
  &lt;/div&gt;
  &lt;p class="fallbackLabel"&gt;Choose a date and time for your party:&lt;/p&gt;
  &lt;div class="fallbackDateTimePicker"&gt;
    &lt;div&gt;
      &lt;span&gt;
        &lt;label for="day"&gt;Day:&lt;/label&gt;
        &lt;select id="day" name="day"&gt;
        &lt;/select&gt;
      &lt;/span&gt;
      &lt;span&gt;
        &lt;label for="month"&gt;Month:&lt;/label&gt;
        &lt;select id="month" name="month"&gt;
          &lt;option selected&gt;January&lt;/option&gt;
          &lt;option&gt;February&lt;/option&gt;
          &lt;option&gt;March&lt;/option&gt;
          &lt;option&gt;April&lt;/option&gt;
          &lt;option&gt;May&lt;/option&gt;
          &lt;option&gt;June&lt;/option&gt;
          &lt;option&gt;July&lt;/option&gt;
          &lt;option&gt;August&lt;/option&gt;
          &lt;option&gt;September&lt;/option&gt;
          &lt;option&gt;October&lt;/option&gt;
          &lt;option&gt;November&lt;/option&gt;
          &lt;option&gt;December&lt;/option&gt;
        &lt;/select&gt;
      &lt;/span&gt;
      &lt;span&gt;
        &lt;label for="year"&gt;Year:&lt;/label&gt;
        &lt;select id="year" name="year"&gt;
        &lt;/select&gt;
      &lt;/span&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;span&gt;
        &lt;label for="hour"&gt;Hour:&lt;/label&gt;
        &lt;select id="hour" name="hour"&gt;
        &lt;/select&gt;
      &lt;/span&gt;
      &lt;span&gt;
        &lt;label for="minute"&gt;Minute:&lt;/label&gt;
        &lt;select id="minute" name="minute"&gt;
        &lt;/select&gt;
      &lt;/span&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/form&gt;</pre>

<p>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 respectively (see the code comments below for detailed explanations of how these functions work.) We also decided to dynamically generate the hours and months, as there are so many of them!</p>

<div class="hidden">
<pre class="brush: css">div {
  margin-bottom: 10px;
  position: relative;
}

input[type="number"] {
  width: 100px;
}

input + span {
  padding-right: 30px;
}

input:invalid+span:after {
  position: absolute;
  content: '✖';
  padding-left: 5px;
}

input:valid+span:after {
  position: absolute;
  content: '✓';
  padding-left: 5px;
}</pre>
</div>

<p>The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <code>&lt;input type="date"&gt;</code>, we create a new {{htmlelement("input")}} element, set its <code>type</code> to <code>date</code>, then immediately check what its type is set to — non-supporting browsers will return <code>text</code>, because the <code>date</code> type falls back to type <code>text</code>. If <code>&lt;input type="date"&gt;</code> is not supported, we hide the native picker and show the fallback picker UI ({{htmlelement("select")}}) instead.</p>

<pre class="brush: js">// define variables
var nativePicker = document.querySelector('.nativeDateTimePicker');
var fallbackPicker = document.querySelector('.fallbackDateTimePicker');
var fallbackLabel = document.querySelector('.fallbackLabel');

var yearSelect = document.querySelector('#year');
var monthSelect = document.querySelector('#month');
var daySelect = document.querySelector('#day');
var hourSelect = document.querySelector('#hour');
var minuteSelect = document.querySelector('#minute');

// 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();
  populateHours();
  populateMinutes();
}

function populateDays(month) {
  // delete the current set of &lt;option&gt; elements out of the
  // day &lt;select&gt;, 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;
    (year - 2016) % 4 === 0 ? dayNum = 29 : dayNum = 28;
  }

  // inject the right number of new &lt;option&gt; elements into the day &lt;select&gt;
  for(i = 1; i &lt;= 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 &lt;select&gt;
  for(var i = 0; i &lt;= 100; i++) {
    var option = document.createElement('option');
    option.textContent = year-i;
    yearSelect.appendChild(option);
  }
}

function populateHours() {
  // populate the hours &lt;select&gt; with the 24 hours of the day
  for(var i = 0; i &lt;= 23; i++) {
    var option = document.createElement('option');
    option.textContent = (i &lt; 10) ? ("0" + i) : i;
    hourSelect.appendChild(option);
  }
}

function populateMinutes() {
  // populate the minutes &lt;select&gt; with the 60 hours of each minute
  for(var i = 0; i &lt;= 59; i++) {
    var option = document.createElement('option');
    option.textContent = (i &lt; 10) ? ("0" + i) : i;
    minuteSelect.appendChild(option);
  }
}

// when the month or year &lt;select&gt; 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;
}</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comments</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('HTML WHATWG', 'forms.html#local-date-and-time-state-(type=datetime-local)', '&lt;input type="datetime-local"&gt;')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5 W3C', 'forms.html##local-date-and-time-state-(type=datetime-local)', '&lt;input type="datetime-local"&gt;')}}</td>
   <td>{{Spec2('HTML5 W3C')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Edge</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>20</td>
   <td>12</td>
   <td>{{CompatNo}}<sup>[1]</sup></td>
   <td>{{CompatNo}}</td>
   <td>10.62</td>
   <td>{{CompatNo}}<sup>[2]</sup></td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Edge</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>[1] This feature is not implemented yet. See {{bug("888320")}} and <a href="https://wiki.mozilla.org/TPE_DOM/Date_time_input_types">TPE DOM/Date time input types</a>.</p>

<p>[2] It is recognized but there is no UI.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>The generic {{HTMLElement("input")}} element and the interface used to manipulate it, {{domxref("HTMLInputElement")}}</li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/The_native_form_widgets#Date_and_time_picker">Date and Time picker tutorial</a></li>
</ul>