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
|
---
title: '<input>: The Input (Form Input) element'
slug: Web/HTML/Element/input
tags:
- Data entry
- Element
- Forms
- HTML
- HTML forms
- HTML input tag
- Input
- MakeBrowserAgnostic
- NeedsBrowserCompatibility
- NeedsMobileBrowserCompatibility
- NeedsTranslation
- Reference
- TopicStub
- Web
translation_of: Web/HTML/Element/input
---
<div>{{HTMLRef}}</div>
<p><span class="seoSummary">The <strong>HTML <code><input></code> element</strong> is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and {{Glossary("user agent")}}.</span></p>
<div>{{EmbedInteractiveExample("pages/tabbed/input-text.html", "tabbed-shorter")}}</div>
<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div>
<h2 id="Form_<input>_types">Form <code><input></code> types</h2>
<p>How an <code><input></code> works varies considerably depending on the value of its <code>type</code> attribute, hence the different types are covered in their own separate reference pages. If this attribute is not specified, the default type adopted is <code>text</code>.</p>
<p>The available types are as follows:</p>
<ul>
<li><code>{{HTMLElement("input/button", "button")}}</code>: A push button with no default behavior.</li>
<li><code>{{HTMLElement("input/checkbox", "checkbox")}}</code>: A check box allowing single values to be selected/deselected.</li>
<li><code>{{HTMLElement("input/color", "color")}}</code>: {{HTMLVersionInline("5")}} A control for specifying a color. A color picker's UI has no required features other than accepting simple colors as text (<a href="https://www.w3.org/TR/html5/forms.html#color-state-(type=color)">more info</a>).</li>
<li><code>{{HTMLElement("input/date", "date")}}</code>: {{HTMLVersionInline("5")}} A control for entering a date (year, month, and day, with no time).</li>
<li><code>{{HTMLElement("input/datetime-local", "datetime-local")}}</code>: {{HTMLVersionInline("5")}} A control for entering a date and time, with no time zone.</li>
<li><code>{{HTMLElement("input/email", "email")}}</code>: {{HTMLVersionInline("5")}} A field for editing an e-mail address.</li>
<li><code>{{HTMLElement("input/file", "file")}}</code>: A control that lets the user select a file. Use the <strong>accept</strong> attribute to define the types of files that the control can select.</li>
<li><code>{{HTMLElement("input/hidden", "hidden")}}</code>: A control that is not displayed but whose value is submitted to the server.</li>
<li><code>{{HTMLElement("input/image", "image")}}</code>: A graphical submit button. You must use the <strong>src</strong> attribute to define the source of the image and the <strong>alt</strong> attribute to define alternative text. You can use the <strong>height</strong> and <strong>width</strong> attributes to define the size of the image in pixels.</li>
<li><code>{{HTMLElement("input/month", "month")}}</code>: {{HTMLVersionInline("5")}} A control for entering a month and year, with no time zone.</li>
<li><code>{{HTMLElement("input/number", "number")}}</code>: {{HTMLVersionInline("5")}} A control for entering a number.</li>
<li><code>{{HTMLElement("input/password", "password")}}</code>: A single-line text field whose value is obscured. Use the <strong>maxlength</strong> and <strong>minlength</strong> attributes to specify the maximum length of the value that can be entered.
<div class="note"><strong>Note</strong>: Any forms involving sensitive information like passwords (e.g. login forms) should be served over HTTPS; Firefox now implements multiple mechanisms to warn against insecure login forms — see <a href="/en-US/docs/Web/Security/Insecure_passwords">Insecure passwords</a>. Other browsers are also implementing similar mechanisms.</div>
</li>
<li><code>{{HTMLElement("input/radio", "radio")}}</code>: A radio button, allowing a single value to be selected out of multiple choices.</li>
<li><code>{{HTMLElement("input/range", "range")}}</code>: {{HTMLVersionInline("5")}} A control for entering a number whose exact value is not important.</li>
<li><code>{{HTMLElement("input/reset", "reset")}}</code>: A button that resets the contents of the form to default values.</li>
<li><code>{{HTMLElement("input/search", "search")}}</code>: {{HTMLVersionInline("5")}} A single-line text field for entering search strings. Line-breaks are automatically removed from the input value.</li>
<li><code>{{HTMLElement("input/submit", "submit")}}</code>: A button that submits the form.</li>
<li><code>{{HTMLElement("input/tel", "tel")}}</code>: {{HTMLVersionInline("5")}} A control for entering a telephone number.</li>
<li><code>{{HTMLElement("input/text", "text")}}</code>: A single-line text field. Line-breaks are automatically removed from the input value.</li>
<li><code>{{HTMLElement("input/time", "time")}}</code>: {{HTMLVersionInline("5")}} A control for entering a time value with no time zone.</li>
<li><code>{{HTMLElement("input/url", "url")}}</code>: {{HTMLVersionInline("5")}} A field for entering a URL.</li>
<li><code>{{HTMLElement("input/week", "week")}}</code>: {{HTMLVersionInline("5")}} A control for entering a date consisting of a week-year number and a week number with no time zone.</li>
</ul>
<p>Some input types are now obsolete:</p>
<ul>
<li><code>{{HTMLElement("input/datetime", "datetime")}}</code>: {{HTMLVersionInline("5")}} {{deprecated_inline}} {{obsolete_inline}} A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone. <strong>This feature has been <a href="https://github.com/whatwg/html/issues/336">removed from WHATWG HTML.</a></strong></li>
</ul>
<h2 id="Attributes">Attributes</h2>
<p>The <code><input></code> element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes. Since every <code><input></code> element, regardless of type, is based on the {{domxref("HTMLInputElement")}} interface, they technically all share the exact same set of attributes. However, in reality, many attributes only function on specific input types, and some input types support very few of these attributes. In addition, some input types handle certain attributes in special ways.</p>
<p>Here, you'll find information about the individual attributes which are common to all <code><input></code> element types, as well as a few non-standard attributes that may be worth knowing about.</p>
<h3 id="Attributes_common_to_all_input_types">Attributes common to all input types</h3>
<p>This section lists the attributes which are used by all form <code><input></code> types. Attributes that are unique to particular input types—or attributes which are common to all input types but have special behaviors when used on a given input type—are instead documented on those types' pages.</p>
<div class="note">
<p><strong>Note</strong>: This includes the <a href="/en-US/docs/Web/HTML/Global_attributes">global HTML attributes</a>.</p>
</div>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Attribute</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>{{anch("autocomplete")}}</code></td>
<td>A string indicating the type of autocomplete functionality, if any, to allow on the input</td>
</tr>
<tr>
<td><code>{{anch("autofocus")}}</code></td>
<td>A Boolean which, if present, makes the input take focus when the form is presented</td>
</tr>
<tr>
<td><code>{{anch("disabled")}}</code></td>
<td>A Boolean attribute which is present if the input should be disabled</td>
</tr>
<tr>
<td><code>{{anch("form")}}</code></td>
<td>The {{domxref("Element.id", "id")}} of the {{HTMLElement("form")}} of which the input is a member; if absent, the input is a member of the nearest containing form, or is not a member of a form at all</td>
</tr>
<tr>
<td><code>{{anch("list")}}</code></td>
<td>The <code>id</code> of a {{HTMLElement("datalist")}} element that provides a list of suggested values for the input</td>
</tr>
<tr>
<td><code>{{anch("name")}}</code></td>
<td>The input's name, to identify the input in the data submitted with the form's data</td>
</tr>
<tr>
<td><code>{{anch("readonly")}}</code></td>
<td>A Boolean attribute which, if true, indicates that the input cannot be edited</td>
</tr>
<tr>
<td><code>{{anch("required")}}</code></td>
<td>A Boolean which, if true, indicates that the input must have a value before the form can be submitted</td>
</tr>
<tr>
<td><code>{{anch("tabindex")}}</code></td>
<td>A numeric value providing guidance to the {{Glossary("user agent")}} as to the order in which controls receive focus when the user presses the <kbd>Tab</kbd> key</td>
</tr>
<tr>
<td><code>{{anch("type")}}</code></td>
<td>A string indicating which {{anch("Form <input> types", "input type")}} the <code><input></code> element represents</td>
</tr>
<tr>
<td><code>{{anch("value")}}</code></td>
<td>The input's current value</td>
</tr>
</tbody>
</table>
<h4 id="htmlattrdefautocomplete">{{htmlattrdef("autocomplete")}}</h4>
<p>A string that describes what if any type of autocomplete functionality the input should provide. A typical implementation of autocomplete simply recalls previous values entered in the same input field, but more complex forms of autocomplete can exist. For instance, a browser could integrate with a device's contacts list to autocomplete email addresses in an email input field. See {{SectionOnPage("/en-US/docs/Web/HTML/Attributes/autocomplete", "Values")}} for permitted values.</p>
<p>This attribute has no effect on input types that do not return numeric or text data, such as <code>checkbox</code> or <code>image</code>.</p>
<p>See <a href="/en-US/docs/Web/HTML/Attributes/autocomplete">The HTML autocomplete attribute</a> for additional information.</p>
<h4 id="htmlattrdefautofocus">{{htmlattrdef("autofocus")}}</h4>
<p>A Boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the {{HTMLElement("dialog")}} containing the element has been displayed).</p>
<div class="note">
<p><strong>Note:</strong> An element with the <code>autofocus</code> attribute may gain focus before the {{domxref("DOMContentLoaded")}} event is fired.</p>
</div>
<p>No more than one element in the document may have the <code>autofocus</code> attribute, and <code>autofocus</code> cannot be used on inputs of type <code>hidden</code>, because hidden inputs can't be focused.</p>
<div class="warning">
<p><strong>Warning:</strong> Automatically focusing a form control can confuse visually-impaired people using screen-reading technology. When <code>autofocus</code> is assigned, screen-readers "teleport" their user to the form control without warning them beforehand.</p>
</div>
<h4 id="htmlattrdefdisabled">{{htmlattrdef("disabled")}}</h4>
<p>A Boolean attribute which, if present, indicates that the user should not be able to interact with the input. Disabled inputs are typically rendered with a dimmer color or using some other form of indication that the field is not available for use.</p>
<p>Specifically, disabled inputs do not receive the {{event("click")}} event, and disabled inputs are not submitted with the form.</p>
<div class="note">
<p><strong>Note:</strong> Although not required by the specification, Firefox will by default <a href="https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing">persist the dynamic disabled state</a> of an <code><input></code> across page loads. Use the {{htmlattrxref("autocomplete","input")}} attribute to control this feature.</p>
</div>
<h4 id="htmlattrdefform">{{htmlattrdef("form")}}</h4>
<p>A string specifying the {{HTMLElement("form")}} element with which the input is associated (that is, its <strong>form owner</strong>). This string's value, if present, must match the {{htmlattrxref("id")}} of a <code><form></code> element in the same document. If this attribute isn't specified, the <code><input></code> element is associated with the nearest containing form, if any.</p>
<p>The <code>form</code> attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document.</p>
<div class="note">
<p><strong>Note:</strong> An input can only be associated with one form.</p>
</div>
<h4 id="htmlattrdeflist">{{htmlattrdef("list")}}</h4>
<p>The {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document which provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the {{htmlattrxref("type", "input")}} are not included in the suggested options.</p>
<p>The <code>list</code> attribute is not supported by the <code>hidden</code>, <code>password</code>, <code>checkbox</code>, <code>radio</code>, <code>file</code>, or any of the button types.</p>
<h4 id="htmlattrdefname">{{htmlattrdef("name")}}</h4>
<p>A string specifying a name for the input control. This name is submitted along with the control's value when the form data is submitted, as well as with the owning {{HTMLElement("form")}} element's {{domxref("HTMLFormElement.elements", "elements")}} object.</p>
<p>When an input element is given a <code>name</code>, that name becomes a property of the owning form element's {{domxref("HTMLFormElement.elements")}} property. That means if you have an input whose <code>name</code> is set to <code>guest</code> and another whose <code>name</code> is <code>hat-size</code>, the following code can be used:</p>
<pre class="brush: js">let form = document.querySelector("form");
let guestName = form.elements.guest;
let hatSize = form.elements["hat-size"];
</pre>
<p>When this code has run, <code>guestName</code> will be the {{domxref("HTMLInputElement")}} for the <code>guest</code> field, and <code>hatSize</code> the object for the <code>hat-size</code> field.</p>
<div class="warning">
<p><strong>Warning:</strong> You should avoid giving form elements a <code>name</code> that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.</p>
</div>
<p>The name <code>_charset_</code> has a special meaning. If used as the name of an <code><input></code> element of type <code><a href="/en-US/docs/Web/HTML/Element/input/hidden">hidden</a></code>, the input's <code>value</code> is automatically set by the {{Glossary("user agent")}} to the character encoding being used to submit the form.</p>
<p>If no <code>name</code> is specified, or <code>name</code> is empty, the input's value is not submitted with the form.</p>
<div class="note">
<p><strong>Note:</strong> For historical reasons, the name <code>isindex</code> is not allowed. If you really want to know why, see <a href="https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-name">Naming form controls: the <code>name</code> attribute</a> in the HTML specification.</p>
</div>
<h4 id="htmlattrdefreadonly">{{htmlattrdef("readonly")}}</h4>
<p>A Boolean attribute which, if present, indicates that the user should not be able to edit the value of the input.</p>
<p>The difference between <code>disabled</code> and <code>readonly</code> is that read-only controls can still function, whereas disabled controls generally do not function as controls until they are enabled.</p>
<div class="blockIndicator note">
<p><strong>Note:</strong> The <code>required</code> attribute is not permitted on inputs with the <code>readonly</code> attribute specified.</p>
</div>
<div class="blockIndicator note">
<p><strong>Note:</strong> Only text controls can be made read-only, since for other controls (such as checkboxes and buttons) there is no useful distinction between being read-only and being disabled, so the <code>readonly</code> attribute does not apply.</p>
</div>
<h4 id="htmlattrdefrequired">{{htmlattrdef("required")}}</h4>
<p><code>required</code> is a Boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted. The <code>required</code> attribute is supported by all input types <em>except the following</em>:</p>
<div class="threecolumns">
<ul>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/color">color</a></code></li>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/hidden">hidden</a></code></li>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/range">range</a></code></li>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/submit">submit</a></code></li>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/image">image</a></code></li>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/reset">reset</a></code></li>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/button">button</a></code></li>
</ul>
</div>
<p>When an input has the <code>required</code> attribute, the {{cssxref(":required")}} pseudo-class also applies to it. Conversely, inputs without the <code>required</code> attribute (except the elements that don't support it) have the {{cssxref(":optional")}} pseudo-class applied.</p>
<div class="note">
<p><strong>Note:</strong> Because a read-only field cannot have a value, <code>required</code> does not have any effect on inputs with the {{htmlattrxref("readonly", "input/text")}} attribute also specified.</p>
</div>
<h4 id="htmlattrdeftabindex">{{htmlattrdef("tabindex")}}</h4>
<p>An optional numeric value that defines both whether or not the input should be focusable through use of the <kbd>Tab</kbd> key as well as whether or not the element participates in sequential focus navigation. This value also establishes the order in which the element is reached using the <kbd>Tab</kbd> key.</p>
<p>The values of <code>tabindex</code> have special meanings depending on sign:</p>
<ul>
<li>A negative value of <code>tabindex</code> indicates that the element should be focusable by the user, but not using sequential keyboard navigation. It's recommended to always use a value of -1 as using other values can be complicated.</li>
<li>A <code>tabindex</code> of 0 means that the element should be focusable and should be reachable by sequential keyboard navigation, but that the tab order is left up to the {{Glossary("user agent")}}, which should apply the user's platform conventions. This is usually the best value to use when you want an element to be focusable and to participate in keyboard navigation rather than trying to manage the tab order yourself.</li>
<li>A positive value of <code>tabindex</code> indicates the tabbing order of the element. Each time the user presses the <kbd>Tab</kbd> key, the element with the next sequentially higher <code>tabindex</code> is focused. Most platforms provide a reverse-tab feature, typically using the combination of <kbd>Shift</kbd> + <kbd>Tab</kbd>, which reverses the tabbing order.</li>
</ul>
<p>If <code>tabindex</code> is omitted or is not a valid integer, the user agent follows platform conventions to determine what to do.</p>
<h4 id="htmlattrdeftype">{{htmlattrdef("type")}}</h4>
<p>A string specifying the type of control to render. For example, to create a checkbox, a value of <code>checkbox</code> is used. If omitted (or an unknown value is specified), the input type <code>text</code> is used, creating a plaintext input field.</p>
<p>Permitted values are listed in {{anch("Form <input> types")}}.</p>
<h4 id="htmlattrdefvalue">{{htmlattrdef("value")}}</h4>
<p>The input control's value. When specified in the HTML, this is the initial value, and from then on it can be altered or retrieved at any time using JavaScript to access the respective {{domxref("HTMLInputElement")}} object's <code>value</code> property. The <code>value</code> attribute is always optional.</p>
<div class="note">
<p><strong>Note:</strong> Unlike other input controls, checkboxes and radio buttons are only included in the submitted data if the checkbox or radio button is currently <code>checked</code>. If it is, then the <code>value</code> attribute is reported as the input's value.</p>
<p>For example, if a checkbox whose <code>name</code> is <code>status</code> has a <code>value</code> of <code>active</code>, and the checkbox is checked, the form data submitted will include <code>status=active</code>. If the checkbox isn't active, it isn't listed in the form data at all. The default <code>value</code> for checkboxes and radio buttons is <code>on</code>.</p>
</div>
<h2 id="Methods">Methods</h2>
<p>The following methods are provided by the {{domxref("HTMLInputElement")}} interface which represents <code><input></code> elements in the DOM. Also available are those methods specified by the parent interfaces, {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, and {{domxref("EventTarget")}}.</p>
<dl>
<dt>{{domxref("HTMLInputElement.checkValidity", "checkValidity()")}}</dt>
<dd>Immediately runs the validity check on the element, triggering the document to fire the {{domxref("HTMLInputElement.invalid_event", "invalid")}} event at the element if the value isn't valid.</dd>
<dt>{{domxref("HTMLInputElement.reportValidity", "reportValidity()")}}</dt>
<dd>Returns <code>true</code> if the element's value passes validity checks; otherwise, returns <code>false</code>.</dd>
<dt>{{domxref("HTMLInputElement.select", "select()")}}</dt>
<dd>Selects the entire content of the <code><input></code> element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing.</dd>
<dt>{{domxref("HTMLInputElement.setCustomValidity", "setCustomValidity()")}}</dt>
<dd>Sets a custom message to display if the input element's value isn't valid.</dd>
<dt>{{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}</dt>
<dd>Sets the contents of the specified range of characters in the input element to a given string. A <code>selectMode</code> parameter is available to allow controlling how the existing content is affected.</dd>
<dt>{{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}</dt>
<dd>Selects the specified range of characters within a textual input element. Does nothing for inputs which aren't presented as text input fields.</dd>
<dt>{{domxref("HTMLInputElement.stepDown", "stepDown()")}}</dt>
<dd>Decrements the value of a numeric input by one, by default, or by the specified number of units.</dd>
<dt>{{domxref("HTMLInputElement.stepUp", "stepUp()")}}</dt>
<dd>Increments the value of a numeric input by one or by the specified number of units.</dd>
</dl>
<h2 id="Styling_input_elements">Styling input elements</h2>
<p>You can style <code><input></code> elements using various color-related attributes in particular. One unusual one that is specific to text entry-related elements is the CSS {{cssxref("caret-color")}} property, which lets you set the color used to draw the text input caret:</p>
<h3 id="HTML">HTML</h3>
<pre class="brush: html"><label for="textInput">Note the red caret:</label>
<input id="textInput" class="custom" size="32">
</pre>
<h3 id="CSS">CSS</h3>
<pre class="brush: css">input.custom {
caret-color: red;
font: 16px "Helvetica", "Arial", "sans-serif"
}
</pre>
<h3 id="Result">Result</h3>
<p>{{EmbedLiveSample('Styling_input_elements', 500, 80)}}</p>
<p>For more information about adding color to elements in HTML, see <a href="/en-US/docs/Web/HTML/Applying_color">Applying color to HTML elements using CSS</a>.</p>
<h2 id="Labels_and_placeholders">Labels and placeholders</h2>
<div class="note">
<p><strong>TL;DR:</strong> To save you time, here's the key point: don't use the {{htmlattrxref("placeholder", "input")}} attribute if you can avoid it. If you need to label an <code><input></code> element, use the {{HTMLElement("label")}} element.</p>
</div>
<p>There are three seemingly similar ways to associate assistive text with an <code><input></code>. However, they are actually quite different, and only one of them is always a good choice. Here we will look at each of them and learn best practices for providing the user with guidance when entering data into a form.</p>
<h3 id="The_<label>_element">The <label> element</h3>
<p>The {{HTMLElement("label")}} element is the only way to provide explanatory information about a form field that is <em>always</em> appropriate (aside from any layout concerns you have). It's never a bad idea to use a <code><label></code> to explain what should be entered into an <code><input></code> or {{HTMLElement("textarea")}}.</p>
<h3 id="The_placeholder_attribute">The placeholder attribute</h3>
<p>The {{htmlattrxref("placeholder", "input")}} attribute lets you specify a text that appears within the <code><input></code> element's content area itself when empty. It's intended to be used to show an example input, rather than an explanation or prompt, but tends to be badly misused.</p>
<p>Here are two inputs that take a password, each with a placeholder:</p>
<p><img alt="Example of correct and incorrect placeholder usage" src="https://mdn.mozillademos.org/files/16094/placeholder-badgood.png" style="border-style: solid; border-width: 1px; height: 66px; width: 230px;"></p>
<p>The first one uses a placeholder string <code>MyGr8P@sswrd</code>, demonstrating what a password might look like. And no, that's not <em>really</em> a great password.</p>
<p>The second one uses a prompt string, <code>Enter your password</code> as a placeholder. The first, and most obvious, problem with doing this is that as soon as the user types their first character, they no longer have a prompt explaining what that field is for.</p>
<p>That's why, instead, you should use the {{HTMLElement("label")}} element. The placeholder should never be required in order to understand your forms. While some people are able to remember what a given empty box is meant for after its only identifying text vanishes, others cannot.</p>
<p>If the user can't understand your form if the placeholders are missing (say, in a browser that doesn't support <code>placeholder</code>, or in the case above where the user starts typing then gets confused), you're not using placeholders properly.</p>
<p>In addition, browsers with automatic page translation features may skip over attributes when translating. That means the <code>placeholder</code> may not get translated, resulting in important information not being translated.</p>
<p>If you feel like you need to use a placeholder, it's possible to use both a placeholder and a label:</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/16110/label-and-placeholder.png" style="border-style: solid; border-width: 1px; height: 48px; width: 234px;"></p>
<h3 id="Unadorned_text_adjacent_to_the_<input>_element">Unadorned text adjacent to the <input> element</h3>
<p>You can also just have plain text adjacent to the <code><input></code> element, like this:</p>
<pre class="brush: html"><p>Enter your name: <input id="name" type="text" size="30"></p></pre>
<p>Please don't do this. This doesn't create a relationship between the prompt and the <code><input></code> element, which is important for reasons we'll get into in the next section.</p>
<h3 id="Why_you_should_use_labels">Why you should use labels</h3>
<p>In addition to the information provided above, there are a number of other reasons why <code><label></code> is the best way to explain <code><input></code>s:</p>
<ul>
<li>The semantic pairing of <code><input></code> and <code><label></code> elements is useful for assistive technologies such as screen readers. By pairing them using the <code><label></code>'s {{htmlattrxref("for", "label")}} attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely.</li>
<li>By pairing a <code><label></code> with an <code><input></code>, clicking on either one will focus the <code><input></code>. If you use plaintext to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions.</li>
<li>As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your web site—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels.</li>
</ul>
<h2 id="Examples">Examples</h2>
<p>You can find multiple examples of <code><input></code> element usage on the pages covering each individual type — see {{anch("Form <input> types")}}, and also see the {{anch("Live example")}} at the top of the article.</p>
<h2 id="Technical_summary">Technical summary</h2>
<table class="properties">
<tbody>
<tr>
<th scope="row"><a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a></th>
<td><a href="/en-US/docs/Web/HTML/Content_categories#Flow_content">Flow content</a>, listed, submittable, resettable, form-associated element, <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>. If the {{htmlattrxref("type", "input")}} is not <code>hidden</code>, then labelable element, palpable content.</td>
</tr>
<tr>
<th scope="row">Permitted content</th>
<td>None, it is an {{Glossary("empty element")}}.</td>
</tr>
<tr>
<th scope="row">Tag omission</th>
<td>Must have a start tag and must not have an end tag.</td>
</tr>
<tr>
<th scope="row">Permitted parents</th>
<td>Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#Phrasing_content">phrasing content</a>.</td>
</tr>
<tr>
<th scope="row">Permitted ARIA roles</th>
<td>
<ul>
<li><code>type=button</code>: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}, {{ARIARole("tab")}}</li>
<li><code>type=checkbox</code>: {{ARIARole("button")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("option")}}, {{ARIARole("switch")}}</li>
<li><code>type=image</code>: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}</li>
<li><code>type=radio</code>: {{ARIARole("menuitemradio")}}</li>
<li><code>type=color|date|datetime|datetime-local|email|file</code>: None</li>
<li><code>type=hidden|month|number|password|range|reset</code>: None</li>
<li><code>type=search|submit|tel|text|url|week</code>: None</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">DOM interface</th>
<td>{{domxref("HTMLInputElement")}}</td>
</tr>
</tbody>
</table>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('HTML WHATWG', 'forms.html#the-input-element', '<input>')}}</td>
<td>{{Spec2('HTML WHATWG')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('HTML Media Capture', '#the-capture-attribute','<input capture>')}}</td>
<td>{{Spec2('HTML Media Capture')}}</td>
<td>Adds the <code>capture</code> attribute</td>
</tr>
<tr>
<td>{{SpecName('HTML5 W3C', 'forms.html#the-input-element', '<input>')}}</td>
<td>{{Spec2('HTML5 W3C')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('HTML4.01', 'interact/forms.html#h-17.4', '<form>')}}</td>
<td>{{Spec2('HTML4.01')}}</td>
<td></td>
</tr>
</tbody>
</table>
<h2 id="Accessibility_concerns">Accessibility concerns</h2>
<h3 id="Labels">Labels</h3>
<p>When including inputs, it is recommended to add labels along side. This is so those who use assistive technologies can tell what the input is for. For more information about labels in general see {{anch("Labels and placeholders")}} .</p>
<p>The following is an example of how to associate the <code><label></code> with an <code><input></code> element in the above style. You need to give the <code><input></code> an <code>id</code> attribute. The <code><label></code> then needs a <code>for</code> attribute whose value is the same as the input's <code>id</code>.</p>
<pre><label for="peas">Do you like peas?</label>
<input type="checkbox" name="peas" id="peas">
</pre>
<h3 id="Size">Size</h3>
<p>Interactive elements such as form input should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44 by 44 <a href="https://www.w3.org/TR/WCAG21/#dfn-css-pixels">CSS pixels</a> is recommended.</p>
<ul>
<li><a href="https://www.w3.org/WAI/WCAG21/Understanding/target-size.html">Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1</a></li>
<li><a href="http://adrianroselli.com/2019/06/target-size-and-2-5-5.html">Target Size and 2.5.5 | Adrian Roselli</a></li>
<li><a href="https://a11yproject.com/posts/large-touch-targets/">Quick test: Large touch targets - The A11Y Project</a></li>
</ul>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<div>{{Compat("html.elements.input")}}</div>
<p>[1] It is recognized but there is no UI.</p>
<p>[2] Missing for <code>type="checkbox"</code> and <code>type="radio"</code>.</p>
<p>[3] In Safari <code>autocapitalize="words"</code> capitalizes every word's second character.</p>
<p>[4] <code>datetime</code> has been removed from the spec and browsers in favour of <code>datetime-local</code>.</p>
<p>[5] see {{bug(1355389)}}</p>
<p>[6] Not yet implemented. For progress, see {{bug("888320")}} and <a href="https://wiki.mozilla.org/TPE_DOM/Date_time_input_types">TPE DOM/Date time input types</a>.</p>
<h2 id="Notes">Notes</h2>
<h3 id="Custom_error_messages">Custom error messages</h3>
<p>If you want to present a custom error message when a field fails to validate, you need to use the <a href="/en-US/docs/Web/API/Constraint_validation#Constraint_validation_interfaces">Constraint validation features</a> available on <code><input></code> (and related) elements. Take the following form:</p>
<pre class="brush: html"><form>
<label for="name">Enter username (upper and lowercase letters): </label>
<input type="text" name="name" id="name" required pattern="[A-Za-z]+">
<button>Submit</button>
</form></pre>
<p>The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the <code>pattern</code>.</p>
<p>If you wanted to instead display custom error messages, you could use JavaScript like the following:</p>
<pre class="brush: js">const nameInput = document.querySelector('input');
const form = document.querySelector('form');
nameInput.addEventListener('input', () => {
nameInput.setCustomValidity('');
nameInput.checkValidity();
});
nameInput.addEventListener('invalid', () => {
if(nameInput.value === '') {
nameInput.setCustomValidity('Enter your username!');
} else {
nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!');
}
});</pre>
<p>The example renders like so:</p>
<p>{{EmbedLiveSample('Custom_error_messages')}}</p>
<p>In brief:</p>
<ul>
<li>We check the valid state of the input element every time its value is changed by running the <code>checkValidity()</code> method via the <code>input</code> event handler.</li>
<li>If the value is invalid, an <code>invalid</code> event is raised, and the <code>invalid</code> event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an <code>if()</code> block, and set a custom validity error message.</li>
<li>As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.</li>
<li>If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking <code>setCustomValidity()</code> with an empty string value. We therefore do this every time the <code>input</code> event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it current contains a valid value on submission.</li>
</ul>
<div class="blockIndicator note">
<p><strong>Note</strong>: Firefox supported a proprietary error attribute — <code>x-moz-errormessage</code> — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see {{bug(1513890)}}).</p>
</div>
<h3 id="Localization">Localization</h3>
<p>The allowed inputs for certain <input> types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.</p>
<p>Firefox uses the following heuristics to determine the locale to validate the user's input (at least for <code>type="number"</code>):</p>
<ul>
<li>Try the language specified by a <code>lang</code>/<code>xml:lang</code> attribute on the element or any of its parents.</li>
<li>Try the language specified by any Content-Language HTTP header or</li>
<li>If none specified, use the browser's locale.</li>
</ul>
<h3 id="Using_mozactionhint_on_Firefox_mobile">Using mozactionhint on Firefox mobile</h3>
<p>You can use the {{htmlattrxref("mozactionhint", "input")}} attribute to specify the text for the label of the enter key on the virtual keyboard when your form is rendered on Firefox mobile. For example, to have a "Next" label, you can do this:</p>
<pre class="brush: html"><input type="text" mozactionhint="next">
</pre>
<p>The result is:</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/3251/mozactionhint.png" style="border-style: solid; border-width: 1px; height: 400px; width: 240px;"></p>
<p>Note the "Next" key in the lower-right corner of the keyboard.</p>
<h2 id="See_also">See also</h2>
<ul>
<li>Other form-related elements: {{HTMLElement("form")}}, {{HTMLElement("button")}}, {{HTMLElement("datalist")}}, {{HTMLElement("legend")}}, {{HTMLElement("label")}}, {{HTMLElement("select")}}, {{HTMLElement("optgroup")}}, {{HTMLElement("option")}}, {{HTMLElement("textarea")}}, {{HTMLElement("keygen")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}} and {{HTMLElement("meter")}}.</li>
<li><a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">Form constraint validation</a></li>
<li><a class="external" href="http://webdesignerwall.com/tutorials/cross-browser-html5-placeholder-text">Cross-browser HTML5 placeholder text</a></li>
<li>The CSS {{cssxref("caret-color")}} property</li>
<li>In certain cases (typically involving non-textual inputs and specialized interfaces), the <code><input></code> element is a <a href="/en-US/docs/Web/CSS/Replaced_element">replaced element</a>. When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS {{cssxref("object-position")}} and {{cssxref("object-fit")}} properties</li>
</ul>
|