DEV Community

Cover image for HTML tags | input
Carlos Espada
Carlos Espada

Posted on • Edited on

HTML tags | input

It 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 user agent.

The element can be displayed in several ways, depending on the type attribute. If this attribute is not specified, the default type adopted is text.

The different input types are as follows:

  • button: a push button with no default behavior displaying the value of the value attribute, empty by default.
  • checkbox: a check box allowing single values to be selected/deselected.
  • color: a control for specifying a color. Opens a color picker when active in supporting browsers.
  • date: a control for entering a date (year, month, and day, with no time). Opens a date picker or numeric wheels for year, month, day when active in supporting browsers.
  • datetime-local: a control for entering a date and time, with no time zone. Opens a date picker or numeric wheels for date- and time-components when active in supporting browsers.
  • email: a field for editing an email address. Looks like a text input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards.
  • file: a control that lets the user select a file. Use the accept attribute to define the types of files that the control can select.
  • hidden: a control that is not displayed but whose value is submitted to the server.
  • image: a graphical submit button. Displays an image defined by the src attribute. The alt attribute displays if the image src is missing.
  • month: a control for entering a month and year, with no time zone.
  • number: a control for entering a number. Displays a spinner and adds default validation when supported. Displays a numeric keypad in some devices with dynamic keypads.
  • password: a single-line text field whose value is obscured. Will alert user if site is not secure.
  • radio: a radio button, allowing a single value to be selected out of multiple choices with the same name attribute value.
  • range: a control for entering a number whose exact value is not important. Displays as a range widget defaulting to the middle value. Used in conjunction min and max to define the range of acceptable values.
  • reset: a button that resets the contents of the form to default values. Not recommended.
  • search: a single-line text field for entering search strings. Line-breaks are automatically removed from the input value. May include a delete icon in supporting browsers that can be used to clear the field. Displays a search icon instead of enter key on some devices with dynamic keypads.
  • submit: a button that submits the form.
  • tel: a control for entering a telephone number. Displays a telephone keypad in some devices with dynamic keypads.
  • text: the default value. A single-line text field. Line-breaks are automatically removed from the input value.
  • time: a control for entering a time value with no time zone.
  • url: a field for entering a URL. Looks like a text input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards.
  • week: a control for entering a date consisting of a week-year number and a week number with no time zone.

Since every <input> element, regardless of type, is based on the HTMLInputElement interface, they technically share the exact same set of attributes. However, in reality, most attributes have an effect on only a specific subset of input types. In addition, the way some attributes impact an input depends on the input type, impacting different input types in different ways.

accept

Valid for the file input type only, defines which file types are selectable in a file upload control.

alt

Valid for the image button only, provides alternative text for the image, displaying the value of the attribute if the image src is missing or otherwise fails to load. Required for accessibility.

autocomplete

Takes as its value a space-separated string that describes what, if any, type of autocomplete functionality the input should provide. A typical implementation of autocomplete recalls previous values entered in the same input field or a browser integrating with a device's contacts list to autocomplete email addresses in an email input field.

It has no effect on input types that do not return numeric or text data, being valid for all input types except checkbox, file, radio or any of the button types.

autofocus

A Boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the <dialog> containing the element has been displayed).

An element with the autofocus attribute may gain focus before the DOMContentLoaded event is fired.

No more than one element in the document may have the autofocus attribute. If put on more than one element, the first one with the attribute receives focus.

It cannot be used on inputs of type hidden, since hidden inputs cannot be focused.

Automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. When autofocus is assigned, screen-readers "teleport" their user to the form control without warning them beforehand.

Use careful consideration for accessibility when applying the autofocus attribute. Automatically focusing on a control can cause the page to scroll on load. The focus can also cause dynamic keyboards to display on some touch devices. While a screen reader will announce the label of the form control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content.

capture

Valid for the file input type only, defines which media—microphone, video or camera—should be used to capture a new file for upload with file upload control in supporting scenarios.

checked

Valid for both radio and checkbox types, is a Boolean attribute. If present on a radio type, it indicates that the radio button is the currently selected one in the group of same-named radio buttons. If present on a checkbox type, it indicates that the checkbox is checked by default (when the page loads).

It does not indicate whether this checkbox is currently checked: if the checkbox’s state is changed, this content attribute does not reflect the change (only the HTMLInputElement’s checked IDL attribute is updated.)

Unlike other input controls, a checkboxes and radio buttons value are only included in the submitted data if they are currently checked. If they are, the name and the value of the checked controls are submitted with the form as part of a name/value pair. If not, they aren't listed in the form data at all.

The default value for checkboxes and radio buttons is on.

dirname

Valid for text and search input types only, enables the submission of the directionality of the element. When included, the form control will submit with two name/value pairs: the first being the name and value, the second being the value of the dirname as the name with the value of ltr or rtl being set by the browser.

<form action="page.html" method="post">
  <label>Fruit: <input type="text" name="fruit" dirname="fruit.dir" value="cherry"></label>
  <input type="submit"/>
</form>
<!-- page.html?fruit=cherry&fruit.dir=ltr -->
Enter fullscreen mode Exit fullscreen mode

When the form above is submitted, the input cause both the name/value pair of fruit=cherry and the dirname/direction pair of fruit.dir=ltr to be sent.

disabled

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.

Specifically, disabled inputs do not receive the click event, and disabled inputs are not submitted with the form.

Although not required by the specification, Firefox will by default persist the dynamic disabled state of an <input> across page loads. Use the autocomplete attribute to control this feature.

form

A string specifying the <form> element with which the input is associated (that is, its form owner). This string's value, if present, must match the id of a <form> element in the same document. If this attribute isn't specified, the <input> element is associated with the nearest containing form, if any.

The form attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document.

An input can only be associated with one form.

formaction

Valid for the image and submit input types only. It is a string indicating the URL to which to submit the data. This takes precedence over the action attribute on the <form> element that owns the <input>.

formenctype

Valid for the image and submit input types only. It is a string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values:

  • application/x-www-form-urlencoded: the default value, sends the form data as a string after URL encoding the text using an algorithm such as encodeURI().
  • multipart/form-data: uses the FormData API to manage the data, allowing for files to be submitted to the server. You must use this encoding type if your form includes any <input> elements of type file (<input type="file">).
  • text/plain: plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted.

If specified, the value of the formenctype attribute overrides the owning form's action attribute.

formmethod

Valid for the image and submit input types only. IT is a string indicating the HTTP method to use when submitting the form's data; this value overrides any method attribute given on the owning form. Permitted values are:

  • get: a URL is constructed by starting with the URL given by the formaction or action attribute, appending a question mark (?) character, then appending the form's data, encoded as described by formenctype or the form's enctype attribute. This URL is then sent to the server using an HTTP get request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value.
  • post: the form's data is included in the body of the request that is sent to the URL given by the formaction or action attribute using an HTTP post method. This method supports complex data and file attachments.
  • dialog: this method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all.

formnovalidate

Valid for the image and submit input types only. It is a Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the novalidate attribute on the element's owning form.

formtarget

Valid for the image and submit input types only. It is a string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a browsing context (that is, a tab, window, or <iframe>. A value specified here overrides any target given by thetargetattribute on the

` that owns this input.

In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used:

  • _self: loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified.
  • _blank: loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.
  • _parent: loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as _self.
  • _top: loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as _self.

height

Valid for the image input button only, is the height of the image file to display to represent the graphical submit button.

id

Global attribute valid for all elements, including all the input types, it defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking. The value is used as the value of the <label>'s for attribute to link the label with the form control.

inputmode

Global value valid for all elements, it provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. Values include decimal, email, none, numeric, search, tel, text and url.

list

The value given to the list attribute should be the id of a <datalist> element located in the same document. The <datalist> 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 type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

It is valid for all input types except checkbox, file, hidden, password, radio or any of the button types.

Depending on the browser, the user may see a custom color palette suggested, tic marks along a range, or even a input that opens like a <select> but allows for non-listed values.

max

Valid for date, datetime-local, month, number, range, time and week, it defines the greatest value in the range of permitted values. If the value entered into the element exceeds this, the element fails constraint validation. If the value of the max attribute isn't a number, then the element has no maximum value.

There is a special case: if the data type is periodic (such as for dates or times), the value of max may be lower than the value of min, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM.

maxlength

Valid for email, password, search, tel, text and url, it defines the maximum number of characters (as UTF-16 code units) the user can enter into the field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of minlength.

The input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long. By default, browsers prevent users from entering more characters than allowed by the maxlength attribute.

min

Valid for date, datetime-local, month, number, range, time and week, it defines the most negative value in the range of permitted values. If the value entered into the element is less than this this, the element fails constraint validation. If the value of the min attribute isn't a number, then the element has no minimum value.

This value must be less than or equal to the value of the max attribute. If the min attribute is present but is not specified or is invalid, no min value is applied. If the min attribute is valid and a non-empty value is less than the minimum allowed by the min attribute, constraint validation will prevent form submission.

There is a special case: if the data type is periodic (such as for dates or times), the value of max may be lower than the value of min, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM.

minlength

Valid for email, password, search, tel, text and url, it defines the minimum number of characters (as UTF-16 code units) the user can enter into the entry field. This must be an non-negative integer value smaller than or equal to the value specified by maxlength. If no minlength is specified, or an invalid value is specified, the input has no minimum length.

The input will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long, preventing form submission.

multiple

A Boolean attribute which, if set, means the user can enter comma separated email addresses in the email widget or can choose more than one file with the file input.

name

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.

Consider the name a required attribute (even though it's not). If an input has no name specified, or name is empty, the input's value is not submitted with the form (disabled controls, unchecked radio buttons, unchecked checkboxes and reset buttons are also not sent).

There are two special cases:

  • _charset_: if used as the name of an <input> element of type hidden, the input's value is automatically set by the user agent to the character encoding being used to submit the form.
  • isindex: for historical reasons, the name isindex is not allowed.

The name attribute creates a unique behavior for radio buttons: only one radio button in a same-named group of radio buttons can be checked at a time. Selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. The value of that one checked radio button is sent along with the name if the form is submitted,

Avoid giving form elements a name 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.

pattern

Valid for password, tel and text. When specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the RegExp type; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.

If the pattern attribute is present but is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. If the pattern attribute is valid and a non-empty value does not match the pattern, constraint validation will prevent form submission.

If using the pattern attribute, inform the user about the expected format by including explanatory text nearby. You can also include a title attribute to explain what the requirements are to match the pattern; most browsers will display this title as a tooltip. The visible explanation is required for accessibility. The tooltip is an enhancement.

placeholder

Valid for password, search, tel, text and url, is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that provides a hint as to the expected type of data, rather than an explanation or prompt. The text must not include carriage returns or line feeds. So for example if a field is expected to capture a user's first name, and its label is "First Name", a suitable placeholder might be "e.g. Fausto".

It should never be required to understand your forms. It is not a label, and should not be used as a substitute, because it isn't. The placeholder is used to provide a hint as to what an inputted value should look like, not an explanation or prompt.

Not only is the placeholder not accessible to screen readers, but once the user enters any text into the form control, or if the form control already has a value, the placeholder disappears. Browsers with automatic page translation features may skip over attributes when translating, meaning the placeholder may not get translated.

Don't use the placeholder attribute if you can avoid it. If you need to label an <input> element, use the <label> element.

readonly

A Boolean attribute which, if present, indicates that the user should not be able to edit the value of the input. The readonly attribute is supported by the date, datetime-local, email, month, number, password, search, tel, text, time, url and week input types.

required

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 required attribute is supported by
the checkbox, date, datetime-local, email, file, month, number, password, radio, search, tel, text, time, url and week input types.

size

Valid for email, password, tel, text and url input types only. Specifies how much of the input is shown. Basically creates same result as setting CSS width property with a few specialities. The actual unit of the value depends on the input type. For password and text, it is a number of characters (or em units) with a default value of 20, and for others, it is pixels. CSS width takes precedence over size attribute.

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×44 CSS pixels is recommended.

src

Valid for the image input button only, is a string specifying the URL of the image file to display to represent the graphical submit button.

step

Valid for the numeric input types, including number, date/time input types and range, the step attribute is a number that specifies the granularity that the value must adhere to.

If not explicitly included:

  • step defaults to 1 for number and range.
  • For the date/time input types, step is expressed in seconds, with the default step being 60 seconds. The step scale factor is 1000 (which converts the seconds to milliseconds, as used in other algorithms).

The value must be a positive number—integer or float—or the special value any, which means no stepping is implied, and any value is allowed (barring other constraints, such as min and max).

If any is not explicity set, valid values for the number, date/time input types and range input types are equal to the basis for stepping — the min value and increments of the step value, up to the max value, if specified.

For example, if you have <input type="number" min="10" step="2">, then any even integer, 10 or greater, is valid. If omitted, , any integer is valid, but floats (like 4.2) are not valid, because step defaults to 1. For 4.2 to be valid, step would have had to be set to any, 0.1, 0.2, or any the min value would have had to be a number ending in .2, such as <input type="number" min="-5.2">.

When the data entered by the user doesn't adhere to the stepping configuration, the value is considered invalid in contraint validation and will match the :invalid pseudoclass.

tabindex

Global attribute valid for all elements, including all the input types, an integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. As all input types except for input of type hidden are focusable, this attribute should not be used on form controls, because doing so would require the management of the focus order for all elements within the document with the risk of harming usability and accessibility if done incorrectly.

title

Global attribute valid for all elements, including all input types, containing a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip. The title should NOT be used as the primary explanation of the purpose of the form control. Instead, use the <label> element with a for attribute set to the form control's id attribute.

type

A string specifying the type of control to render. If omitted (or an unknown value is specified), the input type text is used, creating a plaintext input field.

value

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 HTMLInputElement object's value property. The value attribute is always optional, though should be considered mandatory for checkbox, hidden and radio.

width

Valid for the image input button only, is the width of the image file to display to represent the graphical submit button.

Inputs, being replaced elements, have a few features not applicable to non form elements. There are CSS selectors that can specification target form controls based on their UI features, also known as UI pseudo-classes. The input element can also be targeted by type with attribute selectors. There are some properties that are especially useful as well.

  • :blank: <input> and <textarea> elements that currently have no value.
  • :checked: matches checkbox and radio input types that are currently checked (and the <option> in a <select> that is currently selected).
  • :default: form elements that are the default in a group of related elements. Matches checkbox and radio input types that were checked on page load or render.
  • :disabled: any currently disabled element that has an enabled state, meaning it otherwise could be activated (selected, clicked on, typed into, etc.) or accept focus were it not disabled.
  • :enabled: any currently enabled element that can be activated (selected, clicked on, typed into, etc.) or accept focus and also has a disabled state, in which it can't be activated or accept focus.
  • :indeterminate: checkbox elements whose indeterminate property is set to true by JavaScript, radio elements, when all radio buttons with the same name value in the form are unchecked, and <progress> elements in an indeterminate state.
  • :in-range: a non-empty input whose current value is within the range limits specified by the min and max attributes and the step.
  • :invalid: form controls that have constraint validation applied and are currently not valid. Matches a form control whose value doesn't match the constraints set on it by its attributes, such as max, pattern, required and step.
  • :optional: <input>, <select> or <textarea> element that does NOT have the required attribute set on it. Does not match elements that can't be required.
  • :out-of-range: a non-empty input whose current value is NOT within the range limits specified by the min and max attributes or does not adher to the step constraint.
  • :placeholder-shown: element that is currently displaying placeholder text, including <input> and <textarea> elements with the placeholder attribute present that has, as of yet, no value.
  • :read-only: element not editable by the user.
  • :read-write: element that is editable by the user.
  • :required: <input>, <select> or <textarea> element that has the required attribute set on it. Only matches elements that can be required. The attribute included on a non-requirable element will not make for a match.
  • :user-invalid: similar to :invalid, but is activated on blur. Matches invalid input but only after the user interaction, such as by focusing on the control, leaving the control, or attempting to submit the form containing the invalid control.
  • :valid: form controls that can have constraint validation applied and are currently valid.

In addition to using CSS to style inputs based on the :valid or :invalid UI states based on the current state of each input, the browser provides for client-side validation on (attempted) form submission. On form submission, if there is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you.

If a form control doesn't have the required attribute, no value, or an empty string, is not invalid.

We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted.

Always validate input constraints both client side and server side. Constraint validation doesn't remove the need for validation on the server side. Invalid values can still be sent by older browsers or by bad actors.

By default, the appearance of placeholder text is a translucent or light gray. The ::placeholder pseudo-element is the input's placeholder text. It can be styled with a limited subset of CSS properties, the same as that applied to the ::first-line pseudo-element.

The appearance property enables the displaying of (almost) any element as a platform-native style based on the operating system's theme as well as the removal of any platform-native styling with the none value. You could make a <div> look like a radio button with div {appearance: radio;} or a radio look like a checkbox with [type="checkbox] {appearance: checkbox;}, but don't. Setting appearance: none removes platform native borders, but not functionality.

A property specific to text entry-related elements is the CSS caret-color property, which lets you set the color used to draw the text input caret.

In certain cases (typically involving non-textual inputs and specialized interfaces), the <input> element is a replaced element. When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS object-position and object-fit properties.

  • Type: inline-block
  • Self-closing: No
  • Semantic value: No

Definition and example | Support

Top comments (4)

Collapse
 
grahamthedev profile image
GrahamTheDev

Great article! ❤🦄!

Just FYI DEV supports <dl>, <dt> and <dd> elements.

Would have been ideal for that first section and last section (I don't need to say any more as you already wrote about them in number 34! 😋🤣)

Collapse
 
carlosespada profile image
Carlos Espada

Thanks! :)

You're absolutely right, thank you very much for the advice. I'll review what is written because there are many places where you can use a <dl>, even in its own article ;)

Collapse
 
chiaralyn profile image
ChiaraLyn

Excellent, detailed, and complete article, thank you!!!

Collapse
 
carlosespada profile image
Carlos Espada

Thanks Chiara, I'm glad you find it interesting :)