<input type="number"> - HTML: HyperText Markup Language

<input type="number">
=====================

`<input>` elements of type **`number`** are used to let the user enter a number. They include built-in validation to reject non-numerical entries.

The browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by tapping with a fingertip.

Try it
------

On browsers that don't support inputs of type `number`, a `number` input falls back to type `text`.

Value
-----

A number representing the value of the number entered into the input. You can set a default value for the input by including a number inside the `value` attribute, like so:

```html
<input id="number" type="number" value="42" />
```

Additional attributes
---------------------

In addition to the attributes commonly supported by all `<input>` types, inputs of type `number` support these attributes.

### `list`

The values of the list attribute is 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.

### `max`

The maximum value to accept for this input. 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.

This value must be greater than or equal to the value of the `min` attribute.

### `min`

The minimum value to accept for this input. If the `value` of the element is less than this, the element fails constraint validation. If a value is specified for `min` that isn't a valid number, the input has no minimum value.

This value must be less than or equal to the value of the `max` attribute.

### `placeholder`

The `placeholder` attribute 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 demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds.

If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

**Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See `<input>` labels for more information.

### `readonly`

A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the `HTMLInputElement` `value` property.

**Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified.

### `step`

The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping (`min` if specified, `value` otherwise, and an appropriate default value if neither of those is provided) are valid.

A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as `min` and `max`).

**Note:** When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.

The default stepping value for `number` inputs is `1`, allowing only integers to be entered—*unless* the stepping base is not an integer.

Using number inputs
-------------------

The `number` input type should only be used for incremental numbers, especially when spinbutton incrementing and decrementing are helpful to user experience. The `number` input type is not appropriate for values that happen to only consist of numbers but aren't strictly speaking a number, such as postal codes in many countries or credit card numbers. For non-numeric inputs, consider using a different input type, such as `<input type="tel">` or other `<input>` type with the `inputmode` attribute:

```html
<input type="text" inputmode="numeric" pattern="\d\*" />
```

`<input type="number">` elements can help simplify your work when building the user interface and logic for entering numbers into a form. When you create a number input with the proper `type` value, `number`, you get automatic validation that the entered text is a number, and usually a set of up and down buttons to step the value up and down.

**Warning:** Logically, you should not be able to enter characters inside a number input other than numbers. Some browsers allow invalid characters, others do not; see Firefox bug 1398528.

**Note:** A user can tinker with your HTML behind the scenes, so your site *must not* use simple client-side validation for any security purposes. You *must* verify on the server side any transaction in which the provided value may have security implications of any kind.

Mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value.

### A simple number input

In its most basic form, a number input can be implemented like this:

```html
<label for="ticketNum">Number of tickets you would like to buy:</label>
<input id="ticketNum" type="number" name="ticketNum" value="0" />
```

A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the `required` attribute is used, the input is no longer considered valid when empty.

**Note:** Any number is an acceptable value, as long as it is a valid floating point number (that is, not NaN or Infinity).

### Placeholders

Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each `<input>`. This is where **placeholders** come in. A placeholder is a value most commonly used to provide a hint as to the format the input should take `value`. It is displayed inside the edit box when the element's `value` is `""`. Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.

Here, we have an `number` input with the placeholder "`Multiple of 10`". Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

```html
<input type="number" placeholder="Multiple of 10" />
```

### Controlling step size

By default, the up and down buttons provided for you to step the number up and down will step the value up and down by 1. You can change this by providing a `step` attribute, which takes as its value a number specifying the step amount. Our above example contains a placeholder saying that the value should be a multiple of 10, so it makes sense to add a `step` value of `10`:

```html
<input type="number" placeholder="multiple of 10" step="10" />
```

In this example, you should find that the up and down step arrows will increase and decrease the value by 10 each time, not 1. You can still manually enter a number that's not a multiple of 10, but it will be considered invalid.

### Specifying minimum and maximum values

You can use the `min` and `max` attributes to specify a minimum and maximum value that the field can have. For example, let's give our example a minimum of `0`, and a maximum of `100`:

```html
<input type="number" placeholder="multiple of 10" step="10" min="0" max="100" />
```

In this updated version, you should find that the up and down step buttons will not allow you to go below 0 or above 100. You can still manually enter a number outside these bounds, but it will be considered invalid.

### Allowing decimal values

One issue with number inputs is that their step size is 1 by default. If you try to enter a number with a decimal (such as "1.0"), it will be considered invalid. If you want to enter a value that requires decimals, you'll need to reflect this in the `step` value (e.g. `step="0.01"` to allow decimals to two decimal places). Here's a simple example:

```html
<input type="number" placeholder="1.0" step="0.01" min="0" max="10" />
```

See that this example allows any value between `0.0` and `10.0`, with decimals to two places. For example, "9.52" is valid, but "9.521" is not.

### Controlling input size

`<input>` elements of type `number` don't support form sizing attributes such as `size`. You'll have to resort to CSS to change the size of these controls.

For example, to adjust the width of the input to be only as wide as is needed to enter a three-digit number, we can change our HTML to include an `id` and to shorten our placeholder since the field will be too narrow for the text we have been using so far:

```html
<input
 type="number"
 placeholder="x10"
 step="10"
 min="0"
 max="100"
 id="number" />
```

Then we add some CSS to narrow the width of the element with the `id` selector `#number`:

```css
#number {
  width: 3em;
}
```

The result looks like this:

### Offering suggested values

You can provide a list of default options from which the user can select by specifying the `list` attribute, which contains as its value the `id` of a `<datalist>`, which in turn contains one `<option>` element per suggested value. Each `option`'s `value` is the corresponding suggested value for the number entry box.

```html
<input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers" />
<span class="validity"></span>

<datalist id="defaultNumbers">
  <option value="10045678"></option>
  <option value="103421"></option>
  <option value="11111111"></option>
  <option value="12345678"></option>
  <option value="12999922"></option>
</datalist>
```

Validation
----------

We have already mentioned a number of validation features of `number` inputs, but let's review them now:

* `<input type="number">` elements automatically invalidate any entry that isn't a number (or empty, unless `required` is specified).
* You can use the `required` attribute to make an empty entry invalid. (In other words, the input *must* be filled in.)
* You can use the `step` attribute to constrain valid values to a certain set of steps (e.g., multiples of 10).
* You can use the `min` and `max` attributes to constrain valid values to lower and upper bounds.

The following example exhibits all of the above features, as well as using some CSS to display valid and invalid icons, depending on the `input`'s value:

```html
<form>
  <div>
    <label for="balloons">Number of balloons to order (multiples of 10):</label>
    <input
 id="balloons"
 type="number"
 name="balloons"
 step="10"
 min="0"
 max="100"
 required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" />
  </div>
</form>
```

Try submitting the form with different invalid values entered — e.g., no value; a value below 0 or above 100; a value that is not a multiple of 10; or a non-numerical value — and see how the error messages the browser gives you differ with different ones.

The CSS applied to this example is as follows:

```css
div {
  margin-bottom: 10px;
}

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

input:valid + span::after {
  content: "✓";
  padding-left: 5px;
}
```

Here we use the `:invalid` and `:valid` pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent `<span>` element, as a visual indicator of validity.

We put it on a separate `<span>` element for added flexibility. Some browsers don't display generated content very effectively on some types of form inputs. (Read, for example, the section on `<input type="date">` validation.)

**Warning:** HTML form validation is *not* a substitute for server-side 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 bypass your HTML 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).

### Pattern validation

`<input type="number">` elements do not support use of the `pattern` attribute for making entered values conform to a specific regex pattern.

The rationale for this is that number inputs won't be valid if they contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the `min` and `max` attributes (as explained above).

Examples
--------

We've already covered the fact that by default, the increment is `1`, and you can use the `step` attribute to allow decimal inputs. Let's take a closer look.

In the following example is a form for entering the user's height. It defaults to accepting a height in meters, but you can click the relevant button to change the form to accept feet and inches instead. The input for the height in meters accepts decimals to two places.

The HTML looks like this:

```html
<form>
  <div class="metersInputGroup">
    <label for="meters">Enter your height — meters:</label>
    <input
 id="meters"
 type="number"
 name="meters"
 step="0.01"
 min="0"
 placeholder="e.g. 1.78"
 required />
    <span class="validity"></span>
  </div>
  <div class="feetInputGroup" style="display: none;">
    <span>Enter your height — </span>
    <label for="feet">feet:</label>
    <input id="feet" type="number" name="feet" min="0" step="1" />
    <span class="validity"></span>
    <label for="inches">inches:</label>
    <input id="inches" type="number" name="inches" min="0" max="11" step="1" />
    <span class="validity"></span>
  </div>
  <div>
    <input
 type="button"
 class="meters"
 value="Enter height in feet and inches" />
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>
```

You'll see that we are using many of the attributes we've already looked at in the article earlier on. Since we want to accept a meter value in centimeters, we've set the `step` value to `0.01`, so that values like *1.78* are not seen as invalid. We've also provided a placeholder for that input.

We've hidden the feet and inches inputs initially using `style="display: none;"`, so that meters is the default entry type.

Now, onto the CSS. This looks very similar to the validation styling we saw before; nothing remarkable here.

```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;
}
```

And finally, the JavaScript:

```js
const metersInputGroup = document.querySelector(".metersInputGroup");
const feetInputGroup = document.querySelector(".feetInputGroup");
const metersInput = document.querySelector("#meters");
const feetInput = document.querySelector("#feet");
const inchesInput = document.querySelector("#inches");
const switchBtn = document.querySelector('input[type="button"]');

switchBtn.addEventListener("click", () => {
  if (switchBtn.getAttribute("class") === "meters") {
    switchBtn.setAttribute("class", "feet");
    switchBtn.value = "Enter height in meters";

    metersInputGroup.style.display = "none";
    feetInputGroup.style.display = "block";

    feetInput.setAttribute("required", "");
    inchesInput.setAttribute("required", "");
    metersInput.removeAttribute("required");

    metersInput.value = "";
  } else {
    switchBtn.setAttribute("class", "meters");
    switchBtn.value = "Enter height in feet and inches";

    metersInputGroup.style.display = "block";
    feetInputGroup.style.display = "none";

    feetInput.removeAttribute("required");
    inchesInput.removeAttribute("required");
    metersInput.setAttribute("required", "");

    feetInput.value = "";
    inchesInput.value = "";
  }
});
```

After declaring a few variables, an event listener is added to the `button` to control the switching mechanism. This is pretty simple, mostly involving changing over the button's `class` and `<label>`, and updating the display values of the two sets of inputs when the button is pressed.

(Note that we're not converting back and forth between meters and feet/inches here, which a real-life web application would probably do.)

**Note:** When the user clicks the button, the `required` attribute(s) are removed from the input(s) we are hiding, and empty the `value` attribute(s). This is so the form can be submitted if both input sets aren't filled in. It also ensures that the form won't submit data that the user didn't mean to.

If you didn't do this, you'd have to fill in both feet/inches **and** meters to submit the form!

Accessibility concerns
----------------------

The implicit role for the `<input type="number">` element is `spinbutton`. If spinbutton is not an important feature for your form control, consider *not* using `type="number"`. Instead, use `inputmode="numeric"` along with a `pattern` attribute that limits the characters to numbers and associated characters. With `<input type="number">`, there is a risk of users accidentally incrementing a number when they're trying to do something else. Additionally, if users try to enter something that's not a number, there's no explicit feedback about what they're doing wrong.

Also consider using the `autocomplete` attribute to help users complete forms more quickly and with fewer chances of errors. For example, to enable autofill on a zip code field, set `autocomplete="postal-code"`.

Technical summary
-----------------

|  |  |
| --- | --- |
| **Value** | A `Number` representing a number, or empty |
| **Events** | `change` and
 `input` |
| **Supported common attributes** | `autocomplete`,
 `list`,
 `placeholder`,
 `readonly` |
| **IDL attributes** | `list`, `value`, `valueAsNumber` |
| **DOM interface** | `HTMLInputElement` |
| **Methods** | `select()`,
 `stepUp()`,
 `stepDown()` |
| **Implicit ARIA Role** | `spinbutton` |

Specifications
--------------

| Specification |
| --- |
| HTML Standard # number-state-(type=number) |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTML forms guide
* `<input>`
* `<input type="tel">`
* Compatibility of CSS properties
* Article: Why Gov.UK changed the input type for numbers


<input type="email"> - HTML: HyperText Markup Language

<input type="email">
====================

`<input>` elements of type **`email`** are used to let the user enter and edit an email address, or, if the `multiple` attribute is specified, a list of email addresses.

Try it
------

The input value is automatically validated to ensure that it's either empty or a properly-formatted email address (or list of addresses) before the form can be submitted. The `:valid` and `:invalid` CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid email address or not.

Value
-----

The `<input>` element's `value` attribute contains a string which is automatically validated as conforming to email syntax. More specifically, there are three possible value formats that will pass validation:

1. An empty string ("") indicating that the user did not enter a value or that the value was removed.
2. A single properly-formed email address. This doesn't necessarily mean the email address exists, but it is at least formatted correctly. In simple terms, this means `username@domain` or `username@domain.tld`. There's more to it than that, of course; see Validation for a regular expression that matches the email address validation algorithm.
3. If and only if the `multiple` attribute is specified, the value can be a list of properly-formed comma-separated email addresses. Any trailing and leading whitespace is removed from each address in the list.

See Validation for details on how email addresses are validated to ensure that they're formatted properly.

Additional attributes
---------------------

In addition to the attributes that operate on all `<input>` elements regardless of their type, `email` inputs support the following attributes.

### list

The values of the list attribute is 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.

### maxlength

The maximum string length (measured in UTF-16 code units) that the user can enter into the `email` input. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `email` input 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 value of the field is greater than `maxlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

### minlength

The minimum string length (measured in UTF-16 code units) that the user can enter into the `email` input. This must be a 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 `email` 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. Constraint validation is only applied when the value is changed by the user.

### multiple

A Boolean attribute which, if present, indicates that the user can enter a list of multiple email addresses, separated by commas and, optionally, whitespace characters. See Allowing multiple email addresses for an example, or HTML attribute: multiple for more details.

**Note:** Normally, if you specify the `required` attribute, the user must enter a valid email address for the field to be considered valid. However, if you add the `multiple` attribute, a list of zero email addresses (an empty string, or one which is entirely whitespace) is a valid value. In other words, the user does not have to enter even one email address when `multiple` is specified, regardless of the value of `required`.

### pattern

The `pattern` attribute, when specified, is a regular expression that the input's `value` must match for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the `RegExp` type, and as documented in our guide on regular expressions; 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 specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

**Note:** Use the `title` attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.

See the section Pattern validation for details and an example.

### `placeholder`

The `placeholder` attribute 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 demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds.

If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

**Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See `<input>` labels for more information.

### `readonly`

A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the `HTMLInputElement` `value` property.

**Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified.

### `size`

The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (`font` settings in use).

This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the `maxlength` attribute.

Using email inputs
------------------

Email addresses are among the most frequently-inputted textual data forms on the web; they're used when logging into websites, when requesting information, to allow order confirmation, for webmail, and so forth. As such, the `email` input type can make your job as a web developer much easier since it can help simplify your work when building the user interface and logic for email addresses. When you create an email input with the proper `type` value, `email`, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate email address. This can help avoid cases in which the user mistypes their address, or provides an invalid address.

It's important, however, to note that this is not enough to ensure that the specified text is an email address which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be an email address.

**Note:** It's also crucial to remember that a user can tinker with your HTML behind the scenes, so your site *must not* use this validation for any security purposes. You *must* verify the email address on the server side of any transaction in which the provided text may have any security implications of any kind.

### A simple email input

Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. The specification does, however, allow browsers latitude on this. For example, the element could be integrated with the user's device's built-in address book to allow picking email addresses from that list. In its most basic form, an `email` input can be implemented like this:

```html
<input id="emailAddress" type="email" />
```

Notice that it's considered valid when empty and when a single validly-formatted email address is entered, but is otherwise not considered valid. By adding the `required` attribute, only validly-formed email addresses are allowed; the input is no longer considered valid when empty.

### Allowing multiple email addresses

By adding the `multiple` Boolean attribute, the input can be configured to accept multiple email addresses.

```html
<input id="emailAddress" type="email" multiple />
```

The input is now considered valid when a single email address is entered, or when any number of email addresses separated by commas and, optionally, some number of whitespace characters are present.

**Note:** When `multiple` is used, the value *is* allowed to be empty.

Some examples of valid strings when `multiple` is specified:

* `""`
* `"me@example"`
* `"me@example.org"`
* `"me@example.org,you@example.org"`
* `"me@example.org, you@example.org"`
* `"me@example.org,you@example.org, us@example.org"`

Some examples of invalid strings:

* `","`
* `"me"`
* `"me@example.org you@example.org"`
### Placeholders

Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each `<input>`. This is where **placeholders** come in. A placeholder is a value that demonstrates the form the `value` should take by presenting an example of a valid value, which is displayed inside the edit box when the element's `value` is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.

Here, we have an `email` input with the placeholder `sophie@example.com`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

```html
<input type="email" placeholder="sophie@example.com" />
```

### Controlling the input size

You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself.

#### Physical input element size

The physical size of the input box can be controlled using the `size` attribute. With it, you can specify the number of characters the input box can display at a time. In this example the `email` edit box is 15 characters wide:

```html
<input type="email" size="15" />
```

#### Element value length

The `size` is separate from the length limitation on the entered email address itself so that you can have fields fit in a small space while still allowing longer email address strings to be entered. You can specify a minimum length, in characters, for the entered email address using the `minlength` attribute; similarly, use `maxlength` to set the maximum length of the entered email address.

The example below creates a 32 character-wide email address entry box, requiring that the contents be no shorter than 3 characters and no longer than 64 characters.

```html
<input type="email" size="32" minlength="3" maxlength="64" />
```

### Providing default options

#### Providing a single default using the value attribute

As always, you can provide a default value for an `email` input box by setting its `value` attribute:

```html
<input type="email" value="default@example.com" />
```

#### Offering suggested values

Taking it a step further, you can provide a list of default options from which the user can select by specifying the `list` attribute. This doesn't limit the user to those options, but does allow them to select commonly-used email addresses more quickly. This also offers hints to `autocomplete`. The `list` attribute specifies the ID of a `<datalist>`, which in turn contains one `<option>` element per suggested value; each `option`'s `value` is the corresponding suggested value for the email entry box.

```html
<input type="email" size="40" list="defaultEmails" />

<datalist id="defaultEmails">
  <option value="jbond007@mi6.defence.gov.uk"></option>
  <option value="jbourne@unknown.net"></option>
  <option value="nfury@shield.org"></option>
  <option value="tony@starkindustries.com"></option>
  <option value="hulk@grrrrrrrr.arg"></option>
</datalist>
```

With the `<datalist>` element and its `<option>`s in place, the browser will offer the specified values as potential values for the email address; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested email addresses. Then, as the user types, the list is filtered to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

Validation
----------

There are two levels of content validation available for `email` inputs. First, there's the standard level of validation offered to all `<input>`s, which automatically ensures that the contents meet the requirements to be a valid email address. But there's also the option to add additional filtering to ensure that your own specialized needs are met, if you have any.

**Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format.It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it completely. It's also possible for someone to 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 (or data which is too large, is of the wrong type, and so forth) is entered into your database.

### Basic validation

Browsers automatically provide validation to ensure that only text that matches the standard format for Internet email addresses is entered into the input box. Browsers use an algorithm equivalent to the following regular expression:

```js
/^[a-zA-Z0-9.!#$%&'\*+/=?^\_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)\*$/;
```

To learn more about how form validation works and how to take advantage of the `:valid` and `:invalid` CSS properties to style the input based on whether the current value is valid, see Form data validation.

**Note:** There are known specification issues related to international domain names and the validation of email addresses in HTML. See W3C bug 15489 for details.

### Pattern validation

If you need the entered email address to be restricted further than just "any string that looks like an email address," you can use the `pattern` attribute to specify a regular expression the value must match for it to be valid. If the `multiple` attribute is specified, each individual item in the comma-delineated list of values must match the regular expression.

For example, let's say you're building a page for employees of Best Startup Ever, Inc. which will let them contact their IT department for help. In our simplified form, the user needs to enter their email address and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid email address, but for security purposes, we require that the address be an internal corporate email address.

Since inputs of type `email` validate against both the standard email address validation *and* the specified `pattern`, you can implement this easily. Let's see how:
```

body {
  font: 16px sans-serif;
}

.emailBox {
  padding-bottom: 20px;
}

.messageBox {
  padding-bottom: 20px;
}

label {
  line-height: 22px;
}

label::after {
  content: ":";
}
```

```html
<form>
  <div class="emailBox">
    <label for="emailAddress">Your email address</label><br />
    <input
 id="emailAddress"
 type="email"
 size="64"
 maxlength="64"
 required
 placeholder="username@beststartupever.com"
 pattern=".+@beststartupever\.com"
 title="Please provide only a Best Startup Ever corporate email address" />
  </div>

  <div class="messageBox">
    <label for="message">Request</label><br />
    <textarea
 id="message"
 cols="80"
 rows="8"
 required
 placeholder="My shoes are too tight, and I have forgotten how to dance."></textarea>
  </div>
  <input type="submit" value="Send Request" />
</form>
```

Our `<form>` contains one `<input>` of type `email` for the user's email address, a `<textarea>` to enter their message for IT into, and an `<input>` of type `"submit"`, which creates a button to submit the form. Each text entry box has a `<label>` associated with it to let the user know what's expected of them.

Let's take a closer look at the email address entry box. Its `size` and `maxlength` attributes are both set to 64 in order to show room for 64 characters worth of email address, and to limit the number of characters actually entered to a maximum of 64. The `required` attribute is specified, making it mandatory that a valid email address be provided.

An appropriate `placeholder` is provided—`username@beststartupever.com`—to demonstrate what constitutes a valid entry. This string demonstrates both that an email address should be entered, and suggests that it should be a corporate beststartupever.com account. This is in addition to the fact that using type `email` will validate the text to ensure that it's formatted like an email address. If the text in the input box isn't an email address, you'll get an error message that looks something like this:

![Invalid email address in error state with a popout from the input reading 'please enter an email address'.](/en-US/docs/Web/HTML/Element/input/email/enter-valid-email-address.png)

If we left things at that, we would at least be validating on legitimate email addresses. But we want to go one step farther: we want to make sure that the email address is in fact in the form "\_username\_@beststartupever.com". This is where we'll use `pattern`. We set `pattern` to `.+@beststartupever.com`. This simple regular expression requests a string that consists of at least one character of any kind, then an "@" followed by the domain name "beststartupever.com".

Note that this is not even close to an adequate filter for valid email addresses; it would allow things such as " @beststartupever.com" (note the leading space) or "@@beststartupever.com", neither of which is valid. However, the browser runs both the standard email address filter *and* our custom pattern against the specified text. As a result, we wind up with a validation which says "make sure this resembles a valid email address, and if it is, make sure it's also a beststartupever.com address."

It's advisable to use the `title` attribute along with `pattern`. If you do, the `title` *must* describe the pattern. That is, it should explain what format the data should take on, rather than any other information. That's because the `title` may be displayed or spoken as part of a validation error message. For example, the browser might present the message "The entered text doesn't match the required pattern." followed by your specified `title`. If your `title` is something like "Email address", the result would be the message "The entered text doesn't match the required pattern. Email address", which isn't very good.

That's why, instead, we specify the string "Please provide only a Best Startup Ever corporate email address" By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate email address."

![A valid email address, but the input is in error state with a popout from the input reading 'The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate email address.'](/en-US/docs/Web/HTML/Element/input/email/email-pattern-match-bad.png)

**Note:** If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem.

Examples
--------

Here we have an email input with the ID `emailAddress` which is allowed to be up to a maximum of 256 characters long. The input box itself is physically 64 characters wide, and displays the text `user@example.gov` as a placeholder anytime the field is empty. In addition, by using the `multiple` attribute, the box is configured to allow the user to enter zero or more email addresses, separated by commas, as described in Allowing multiple email addresses. As a final touch, the `list` attribute contains the ID of a `<datalist>` whose `<option>`s specify a set of suggested values the user can choose from.

As an added touch, the `<label>` element is used to establish a label for the email entry box, with its `for` attribute referencing the `emailAddress` ID of the `<input>` element. By associating the two elements in this way, clicking on the label will focus the input element.

```html
<label for="emailAddress">Email</label><br />
<input
 id="emailAddress"
 type="email"
 placeholder="user@example.gov"
 list="defaultEmails"
 size="64"
 maxlength="256"
 multiple />

<datalist id="defaultEmails">
  <option value="jbond007@mi6.defence.gov.uk"></option>
  <option value="jbourne@unknown.net"></option>
  <option value="nfury@shield.org"></option>
  <option value="tony@starkindustries.com"></option>
  <option value="hulk@grrrrrrrr.arg"></option>
</datalist>
```

Technical summary
-----------------

|  |  |
| --- | --- |
| **Value** |
 A string representing an email address, or
 empty
  |
| **Events** | `change` and
 `input` |
| **Supported Common Attributes** | `autocomplete`,
 `list`,
 `maxlength`,
 `minlength`,
 `multiple`,
 `name`,
 `pattern`,
 `placeholder`,
 `readonly`,
 `required`,
 `size`, and
 `type` |
| **IDL attributes** | `list` and `value` |
| **DOM interface** | `HTMLInputElement` |
| **Methods** | `select()` |
| **Implicit ARIA Role** |
 with no `list` attribute:
 `textbox`with `list` attribute: `combobox` |

Specifications
--------------

| Specification |
| --- |
| HTML Standard # email-state-(type=email) |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTML forms guide
* `<input>`
* `<input type="tel">`
* `<input type="url">`
* Attributes:
    + `list`
    + `minlength`
    + `maxlength`
    + `multiple`
    + `pattern`
    + `placeholder`
    + `readonly`
    + `size`
* Compatibility of CSS properties


<input type="month"> - HTML: HyperText Markup Language

<input type="month">
====================

`<input>` elements of type **`month`** create input fields that let the user enter a month and year allowing a month and year to be easily entered.
 The value is a string whose value is in the format "`YYYY-MM`", where `YYYY` is the four-digit year and `MM` is the month number.

Try it
------

 The control's UI varies in general from browser to browser; at the moment support is patchy, with only Chrome/Opera and Edge on desktop — and most modern mobile browser versions — having usable implementations.
 In browsers that don't support `month` inputs, the control degrades gracefully to a simple `<input type="text">`, although there may be automatic validation of the entered text to ensure it's formatted as expected.

 For those of you using a browser that doesn't support `month`, the screenshot below shows what it looks like in Chrome and Opera.
 Clicking the down arrow on the right-hand side brings up a date picker that lets you select the month and year.

![Month control on Chrome browser](/en-US/docs/Web/HTML/Element/input/month/month-control-chrome.png)

The Microsoft Edge `month` control looks like this:

![Month control on Edge browser](/en-US/docs/Web/HTML/Element/input/month/month-control-edge.png)

Value
-----

 A string representing the value of the month and year entered into the input, in the form YYYY-MM (four or more digit year, then a hyphen ("`-`"), followed by the two-digit month).
 The format of the month string used by this input type is described in Month strings.

### Setting a default value

You can set a default value for the input control by including a month and year inside the `value` attribute, like so:

```html
<label for="bday-month">What month were you born in?</label>
<input id="bday-month" type="month" name="bday-month" value="2001-06" />
```

One thing to note is that the displayed date format differs from the actual `value`; most user agents display the month and year in a locale-appropriate form, based on the set locale of the user's operating system, whereas the date `value` is always formatted `yyyy-MM`.

When the above value is submitted to the server, for example, it will look like `bday-month=1978-06`.

### Setting the value using JavaScript

You can also get and set the date value in JavaScript using the `HTMLInputElement.value` property, for example:

```html
<label for="bday-month">What month were you born in?</label>
<input id="bday-month" type="month" name="bday-month" />
```

```js
const monthControl = document.querySelector('input[type="month"]');
monthControl.value = "2001-06";
```

Additional attributes
---------------------

In addition to the attributes common to `<input>` elements, month inputs offer the following attributes.

### list

 The values of the list attribute is 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.

### max

 The latest year and month, in the string format discussed in the Value section above, to accept.
 If the `value` entered into the element exceeds this, the element fails constraint validation.
 If the value of the `max` attribute isn't a valid string in "`yyyy-MM`" format, then the element has no maximum value.

This value must specify a year-month pairing later than or equal to the one specified by the `min` attribute.

### min

 The earliest year and month to accept, in the same "`yyyy-MM`" format described above.
 If the `value` of the element is less than this, the element fails constraint validation.
 If a value is specified for `min` that isn't a valid year and month string, the input has no minimum value.

This value must be a year-month pairing which is earlier than or equal to the one specified by the `max` attribute.

### readonly

 A Boolean attribute which, if present, means this field cannot be edited by the user.
 Its `value` can, however, still be changed from JavaScript code that directly sets the value of the `HTMLInputElement.value` property.

**Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified.

### step

 The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below.
 Only values which are equal to the basis for stepping (`min` if specified, `value` otherwise, and an appropriate default value if neither of those is provided) are valid.

A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as `min` and `max`).

**Note:** When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.

 For `month` inputs, the value of `step` is given in months, with a scaling factor of 1 (since the underlying numeric value is also in months).
 The default value of `step` is 1 month.

Using month inputs
------------------

 Date-related inputs (including `month`) sound convenient at first glance; they promise an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user's locale.
 However, there are issues with `<input type="month">` because at this time, many major browsers don't yet support it.

We'll look at basic and more complex uses of `<input type="month">`, then offer advice on mitigating the browser support issue in the section Handling browser support).

### Basic uses of month

The simplest use of `<input type="month">` involves a basic `<input>` and `<label>` element combination, as seen below:

```html
<form>
  <label for="bday-month">What month were you born in?</label>
  <input id="bday-month" type="month" name="bday-month" />
</form>
```

### Setting maximum and minimum dates

 You can use the `min` and `max` attributes to restrict the range of dates that the user can choose.
 In the following example we specify a minimum month of `1900-01` and a maximum month of `2013-12`:

```html
<form>
  <label for="bday-month">What month were you born in?</label>
  <input
 id="bday-month"
 type="month"
 name="bday-month"
 min="1900-01"
 max="2013-12" />
</form>
```

The result here is that:

* Only months between in January 1900 and December 2013 can be selected; months outside that range can't be scrolled to in the control.
* Depending on what browser you are using, you might find that months outside the specified range might not be selectable in the month picker (e.g. Edge), or invalid (see Validation) but still available (e.g. Chrome).
### Controlling input size

`<input type="month">` doesn't support form sizing attributes such as `size`.
 You'll have to resort to CSS for sizing needs.

Validation
----------

 By default, `<input type="month">` does not apply any validation to entered values.
 The UI implementations generally don't let you enter anything that isn't a date — which is helpful — but you can still submit the form with the `month` input empty, or enter an invalid date (e.g. the 32nd of April).

 To help avoid this, you can use `min` and `max` to restrict the available dates (see Setting maximum and minimum dates), and in addition use the `required` 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.

Let's look at an example; here we've set minimum and maximum dates, and also made the field required:

```html
<form>
  <div>
    <label for="month">
      What month would you like to visit (June to Sept.)?
    </label>
    <input
 id="month"
 type="month"
 name="month"
 min="2022-06"
 max="2022-09"
 required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>
```

 If you try to submit the form without both the month and year specified (or with a date outside the set bounds), the browser displays an error.
 Try playing with the example now:

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

![Month required prompt on Chrome browser](/en-US/docs/Web/HTML/Element/input/month/month-required.png)

 Here's the CSS used in the above example.
 Here we make use of the `:valid` and `:invalid` CSS properties to style the input based on whether the current value is valid.
 We had to put the icons on a `<span>` next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively.

```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;
}
```

**Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format.
 It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely.
 It's also possible for someone to 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, of the wrong type, and so forth).

Handling browser support
------------------------

 As mentioned above, the major problem with using date inputs at the time of writing is that many major browsers don't yet implement them all; only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile.
 As an example, the `month` picker on Chrome for Android looks like this:

![Month picker on Chrome for Android](/en-US/docs/Web/HTML/Element/input/month/month-android.png)

Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.

 The second problem is the more serious of the two.
 As mentioned earlier, with a `month` input the actual value is always normalized to the format `yyyy-mm`.
 On the other hand, in its default configuration, a `text` input has no idea what format the date should be in, and this is an issue because of the number of different ways in which people write dates.
 For example:

* `mmyyyy` (072022)
* `mm/yyyy` (07/2022)
* `mm-yyyy` (07-2022)
* `yyyy-mm` (2022-07)
* `Month yyyy` (July 2022)
* and so forth…

 One way around this is to put a `pattern` attribute on your `month` input.
 Even though the `month` input doesn't use it, if the browser falls back to treating it like a `text` input, the pattern will be used.
 For example, try viewing the following demo in a browser that doesn't support `month` inputs:

```html
<form>
  <div>
    <label for="month">
      What month would you like to visit (June to Sept.)?
    </label>
    <input
 id="month"
 type="month"
 name="month"
 min="2022-06"
 max="2022-09"
 required
 pattern="[0-9]{4}-[0-9]{2}" />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>
```

 If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern `nnnn-nn`, where `n` is a number from 0 to 9.
 Of course, this doesn't stop people from entering invalid dates (such as `0000-42`), or incorrectly formatted dates that follow the pattern.

 There's also the problem that the user won't necessarily know which of the many date formats is expected.
 We have work left to do.
```

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;
}
```

The best way to deal with dates in forms in a cross-browser way (until all major browsers have supported them for a while) is to get the user to enter the month and year in separate controls (`<select>` elements being popular; see below for an implementation), or use JavaScript libraries such as the jQuery date picker plugin.

Examples
--------

 In this example, we create two sets of UI elements, each designed to let the user select a month and year.
 The first is a native `month` input, and the other is a pair of `<select>` elements that allow choosing a month and year independently, for compatibility with browsers that don't yet support `<input type="month">`.

### HTML

The form that requests the month and year looks like this:

```html
<form>
  <div class="nativeDatePicker">
    <label for="month-visit">What month would you like to visit us?</label>
    <input type="month" id="month-visit" name="month-visit" />
    <span class="validity"></span>
  </div>
  <p class="fallbackLabel">What month would you like to visit us?</p>
  <div class="fallbackDatePicker">
    <div>
      <span>
        <label for="month">Month:</label>
        <select id="month" name="month">
          <option selected>January</option>
          <option>February</option>
          <option>March</option>
          <option>April</option>
          <option>May</option>
          <option>June</option>
          <option>July</option>
          <option>August</option>
          <option>September</option>
          <option>October</option>
          <option>November</option>
          <option>December</option>
        </select>
      </span>
      <span>
        <label for="year">Year:</label>
        <select id="year" name="year"></select>
      </span>
    </div>
  </div>
</form>
```

 The `<div>` with the ID `nativeDatePicker` uses the `month` input type to request the month and year, while the `<div>` with the ID `fallbackDatePicker` instead uses a pair of `<select>` elements.
 The first requests the month, and the second the year.

 The `<select>` for choosing the month is hardcoded with the names of the months, as they don't change (leaving localization out of things).
 The list of available year values is dynamically generated depending on the current year (see the code comments below for detailed explanations of how these functions work).
```

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;
}
```

### JavaScript

The JavaScript code that handles selecting which approach to use and to set up the list of years to include in the non-native year `<select>` follows.

 The part of the example that may be of most interest is the feature detection code.
 In order to detect whether the browser supports `<input type="month">`, we create a new `<input>` element, try setting its `type` to `month`, then immediately check what its type is set to.
 Browsers that don't support type `month` will return `text`, since that's What month falls back to when not supported.
 If `<input type="month">` is not supported, we hide the native picker and show the fallback picker UI instead.

```js
// Get UI elements
const nativePicker = document.querySelector(".nativeDatePicker");
const fallbackPicker = document.querySelector(".fallbackDatePicker");
const fallbackLabel = document.querySelector(".fallbackLabel");

const yearSelect = document.querySelector("#year");
const monthSelect = document.querySelector("#month");

// 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
const test = document.createElement("input");

try {
  test.type = "month";
} catch (e) {
  console.log(e.description);
}

// 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 years dynamically
  // (the months are always the same, therefore hardcoded)
  populateYears();
}

function populateYears() {
  // Get the current year as a number
  const date = new Date();
  const year = date.getFullYear();

  // Make this year, and the 100 years before it available in the year <select>
  for (let i = 0; i <= 100; i++) {
    const option = document.createElement("option");
    option.textContent = year - i;
    yearSelect.appendChild(option);
  }
}
```

**Note:** Remember that some years have 53 weeks in them (see Weeks per year)!
 You'll need to take this into consideration when developing production apps.

Technical summary
-----------------

|  |  |
| --- | --- |
| **Value** |
 A string representing a month and year, or
 empty.
  |
| **Events** | `change` and
 `input` |
| **Supported common attributes** | `autocomplete`,
 `list`,
 `readonly`, and
 `step`.
  |
| **IDL attributes** | `value` |
| **DOM interface** | `HTMLInputElement` |
| **Methods** | `select()`,
 `stepDown()`,
 `stepUp()`.
  |
| **Implicit ARIA Role** | `no corresponding role` |

Specifications
--------------

| Specification |
| --- |
| HTML Standard # month-state-(type=month) |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The generic `<input>` element and the interface used to manipulate it, `HTMLInputElement`
* Date and time formats used in HTML
* Date and Time picker tutorial
* `<input type="datetime-local">`, `<input type="date">`, `<input type="time">`, and `<input type="week">`
* Compatibility of CSS properties


<input type="button"> - HTML: HyperText Markup Language

<input type="button">
=====================

`<input>` elements of type **`button`** are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typically for the `click` event).

Try it
------

**Note:** While `<input>` elements of type `button` are still perfectly valid HTML, the newer `<button>` element is now the favored way to create buttons. Given that a `<button>`'s label text is inserted between the opening and closing tags, you can include HTML in the label, even images.

Value
-----

### Button with a value

An `<input type="button">` elements' `value` attribute contains a string that is used as the button's label. The `value` provides the accessible description for the button.

```html
<input type="button" value="Click Me" />
```

### Button without a value

If you don't specify a `value`, you get an empty button:

```html
<input type="button" />
```

Using buttons
-------------

`<input type="button">` elements have no default behavior (their cousins, `<input type="submit">` and `<input type="reset">` are used to submit and reset forms, respectively). To make buttons do anything, you have to write JavaScript code to do the work.

### A simple button

We'll begin by creating a simple button with a `click` event handler that starts our machine (well, it toggles the `value` of the button and the text content of the following paragraph):

```html
<form>
  <input type="button" value="Start machine" />
</form>
<p>The machine is stopped.</p>
```

```js
const button = document.querySelector("input");
const paragraph = document.querySelector("p");

button.addEventListener("click", updateButton);

function updateButton() {
  if (button.value === "Start machine") {
    button.value = "Stop machine";
    paragraph.textContent = "The machine has started!";
  } else {
    button.value = "Start machine";
    paragraph.textContent = "The machine is stopped.";
  }
}
```

The script gets a reference to the `HTMLInputElement` object representing the `<input>` in the DOM, saving this reference in the variable `button`. `addEventListener()` is then used to establish a function that will be run when `click` events occur on the button.

### Adding keyboard shortcuts to buttons

Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any `<input>` for which it makes sense — you use the `accesskey` global attribute.

In this example, `s` is specified as the access key (you'll need to press `s` plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).

```html
<form>
  <input type="button" value="Start machine" accesskey="s" />
</form>
<p>The machine is stopped.</p>
```

```
const button = document.querySelector("input");
const paragraph = document.querySelector("p");

button.addEventListener("click", updateButton);

function updateButton() {
  if (button.value === "Start machine") {
    button.value = "Stop machine";
    paragraph.textContent = "The machine has started!";
  } else {
    button.value = "Start machine";
    paragraph.textContent = "The machine is stopped.";
  }
}
```

**Note:** The problem with the above example of course is that the user will not know what the access key is! In a real site, you'd have to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).

### Disabling and enabling a button

To disable a button, specify the `disabled` global attribute on it, like so:

```html
<input type="button" value="Disable me" disabled />
```

#### Setting the disabled attribute

You can enable and disable buttons at run time by setting `disabled` to `true` or `false`. In this example our button starts off enabled, but if you press it, it is disabled using `button.disabled = true`. A `setTimeout()` function is then used to reset the button back to its enabled state after two seconds.

```html
<input type="button" value="Enabled" />
```

```js
const button = document.querySelector("input");

button.addEventListener("click", disableButton);

function disableButton() {
  button.disabled = true;
  button.value = "Disabled";
  setTimeout(() => {
    button.disabled = false;
    button.value = "Enabled";
  }, 2000);
}
```

#### Inheriting the disabled state

If the `disabled` attribute isn't specified, the button inherits its `disabled` state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a `<fieldset>` element, and then setting `disabled` on the container.

The example below shows this in action. This is very similar to the previous example, except that the `disabled` attribute is set on the `<fieldset>` when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.

```html
<fieldset>
  <legend>Button group</legend>
  <input type="button" value="Button 1" />
  <input type="button" value="Button 2" />
  <input type="button" value="Button 3" />
</fieldset>
```

```js
const button = document.querySelector("input");
const fieldset = document.querySelector("fieldset");

button.addEventListener("click", disableButton);

function disableButton() {
  fieldset.disabled = true;
  setTimeout(() => {
    fieldset.disabled = false;
  }, 2000);
}
```

**Note:** Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a `<button>` across page loads. Use the `autocomplete` attribute to control this feature.

Validation
----------

Buttons don't participate in constraint validation; they have no real value to be constrained.

Examples
--------

The below example shows a very simple drawing app created using a `<canvas>` element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas.

```html
<div class="toolbar">
  <input type="color" aria-label="select pen color" />
  <input
 type="range"
 min="2"
 max="50"
 value="30"
 aria-label="select pen size" /><span class="output">30</span>
  <input type="button" value="Clear canvas" />
</div>

<canvas class="myCanvas">
  <p>Add suitable fallback here.</p>
</canvas>
```

```
body {
  background: #ccc;
  margin: 0;
  overflow: hidden;
}

.toolbar {
  background: #ccc;
  width: 150px;
  height: 75px;
  padding: 5px;
}

input[type="color"],
input[type="button"] {
  width: 90%;
  margin: 0 auto;
  display: block;
}

input[type="range"] {
  width: 70%;
}

span {
  position: relative;
  bottom: 5px;
}
```

```js
const canvas = document.querySelector(".myCanvas");
const width = (canvas.width = window.innerWidth);
const height = (canvas.height = window.innerHeight - 85);
const ctx = canvas.getContext("2d");

ctx.fillStyle = "rgb(0 0 0)";
ctx.fillRect(0, 0, width, height);

const colorPicker = document.querySelector('input[type="color"]');
const sizePicker = document.querySelector('input[type="range"]');
const output = document.querySelector(".output");
const clearBtn = document.querySelector('input[type="button"]');

// covert degrees to radians
function degToRad(degrees) {
  return (degrees \* Math.PI) / 180;
}

// update sizepicker output value

sizePicker.oninput = () => {
  output.textContent = sizePicker.value;
};

// store mouse pointer coordinates, and whether the button is pressed
let curX;
let curY;
let pressed = false;

// update mouse pointer coordinates
document.onmousemove = (e) => {
  curX = e.pageX;
  curY = e.pageY;
};

canvas.onmousedown = () => {
  pressed = true;
};

canvas.onmouseup = () => {
  pressed = false;
};

clearBtn.onclick = () => {
  ctx.fillStyle = "rgb(0 0 0)";
  ctx.fillRect(0, 0, width, height);
};

function draw() {
  if (pressed) {
    ctx.fillStyle = colorPicker.value;
    ctx.beginPath();
    ctx.arc(
      curX,
      curY - 85,
      sizePicker.value,
      degToRad(0),
      degToRad(360),
      false,
    );
    ctx.fill();
  }

  requestAnimationFrame(draw);
}

draw();
```

Technical summary
-----------------

|  |  |
| --- | --- |
| **Value** | A string used as the button's label |
| **Events** | `click` |
| **Supported common attributes** | `type` and
 `value` |
| **IDL attributes** | `value` |
| **DOM interface** | `HTMLInputElement` |
| **Methods** | None |
| **Implicit ARIA Role** | `button` |

Specifications
--------------

| Specification |
| --- |
| HTML Standard # button-state-(type=button) |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `<input>` and the `HTMLInputElement` interface which implements it.
* The more modern `<button>` element.
* Compatibility of CSS properties


<input type="checkbox"> - HTML: HyperText Markup Language

<input type="checkbox">
=======================

`<input>` elements of type **`checkbox`** are rendered by default as boxes that are checked (ticked) when activated, like you might see in an official government paper form. The exact appearance depends upon the operating system configuration under which the browser is running. Generally this is a square but it may have rounded corners. A checkbox allows you to select single values for submission in a form (or not).

Try it
------

**Note:** Radio buttons are similar to checkboxes, but with an important distinction — same-named radio buttons are grouped into a set in which only one radio button can be selected at a time, whereas checkboxes allow you to turn single values on and off. Where multiple same-named controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected.

Value
-----

A string representing the value of the checkbox. This is not displayed on the client-side, but on the server this is the `value` given to the data submitted with the checkbox's `name`. Take the following example:

```html
<form>
  <div>
    <input
 type="checkbox"
 id="subscribeNews"
 name="subscribe"
 value="newsletter" />
    <label for="subscribeNews">Subscribe to newsletter?</label>
  </div>
  <div>
    <button type="submit">Subscribe</button>
  </div>
</form>
```

In this example, we've got a name of `subscribe`, and a value of `newsletter`. When the form is submitted, the data name/value pair will be `subscribe=newsletter`.

If the `value` attribute was omitted, the default value for the checkbox is `on`, so the submitted data in that case would be `subscribe=on`.

**Note:** If a checkbox is unchecked when its form is submitted, neither the name nor the value is submitted to the server. There is no HTML-only method of representing a checkbox's unchecked state (e.g. `value=unchecked`). If you wanted to submit a default value for the checkbox when it is unchecked, you could include JavaScript to create a <input type="hidden"> within the form with a value indicating an unchecked state.

Additional attributes
---------------------

In addition to the common attributes shared by all `<input>` elements, "`checkbox`" inputs support the following attributes.

`checked`

A boolean attribute indicating whether this 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.)

**Note:** Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently `checked`. If it is, then the value of the checkbox's `value` attribute is reported as the input's value, or `on` if no `value` is set.
 Unlike other browsers, Firefox by default persists the dynamic checked state of an `<input>` across page loads. Use the `autocomplete` attribute to control this feature.

`value`

The `value` attribute is one which all `<input>`s share; however, it serves a special purpose for inputs of type `checkbox`: when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the `value` attribute. If the `value` is not otherwise specified, it is the string `on` by default. This is demonstrated in the section Value above.

Using checkbox inputs
---------------------

We already covered the most basic use of checkboxes above. Let's now look at the other common checkbox-related features and techniques you'll need.

### Handling multiple checkboxes

The example we saw above only contained one checkbox; in real-world situations you'll be likely to encounter multiple checkboxes. If they are completely unrelated, then you can just deal with them all separately, as shown above. However, if they're all related, things are not quite so simple.

For example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the Examples section).

```html
<fieldset>
  <legend>Choose your interests</legend>
  <div>
    <input type="checkbox" id="coding" name="interest" value="coding" />
    <label for="coding">Coding</label>
  </div>
  <div>
    <input type="checkbox" id="music" name="interest" value="music" />
    <label for="music">Music</label>
  </div>
</fieldset>
```

In this example you will see that we've given each checkbox the same `name`. If both checkboxes are checked and then the form is submitted, you'll get a string of name/value pairs submitted like this: `interest=coding&interest=music`. When this string reaches the server, you need to parse it other than as an associative array, so all values, not only the last value, of `interest` are captured. For one technique used with Python, see Handle Multiple Checkboxes with a Single Serverside Variable, for example.

### Checking boxes by default

To make a checkbox checked by default, you give it the `checked` attribute. See the below example:

```html
<fieldset>
  <legend>Choose your interests</legend>
  <div>
    <input type="checkbox" id="coding" name="interest" value="coding" checked />
    <label for="coding">Coding</label>
  </div>
  <div>
    <input type="checkbox" id="music" name="interest" value="music" />
    <label for="music">Music</label>
  </div>
</fieldset>
```

### Providing a bigger hit area for your checkboxes

In the above examples, you may have noticed that you can toggle a checkbox by clicking on its associated `<label>` element as well as on the checkbox itself. This is a really useful feature of HTML form labels that makes it easier to click the option you want, especially on small-screen devices like smartphones.

Beyond accessibility, this is another good reason to properly set up `<label>` elements on your forms.

### Indeterminate state checkboxes

In addition to the checked and unchecked states, there is a third state a checkbox can be in: **indeterminate**. This is a state in which it's impossible to say whether the item is toggled on or off. This is set using the `HTMLInputElement` object's `indeterminate` property via JavaScript (it cannot be set using an HTML attribute):

```js
inputInstance.indeterminate = true;
```

A checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers.

There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkboxes). If all of the sub-options are checked, the owning checkbox is also checked, and if they're all unchecked, the owning checkbox is unchecked. If any one or more of the sub-options have a different state than the others, the owning checkbox is in the indeterminate state.

This can be seen in the below example (thanks to CSS Tricks for the inspiration). In this example we keep track of the ingredients we are collecting for a recipe. When you check or uncheck an ingredient's checkbox, a JavaScript function checks the total number of checked ingredients:

* If none are checked, the recipe name's checkbox is set to unchecked.
* If one or two are checked, the recipe name's checkbox is set to `indeterminate`.
* If all three are checked, the recipe name's checkbox is set to `checked`.

So in this case the `indeterminate` state is used to state that collecting the ingredients has started, but the recipe is not yet complete.

```js
const overall = document.querySelector("#enchantment");
const ingredients = document.querySelectorAll("ul input");

overall.addEventListener("click", (e) => {
  e.preventDefault();
});

for (const ingredient of ingredients) {
  ingredient.addEventListener("click", updateDisplay);
}

function updateDisplay() {
  let checkedCount = 0;
  for (const ingredient of ingredients) {
    if (ingredient.checked) {
      checkedCount++;
    }
  }

  if (checkedCount === 0) {
    overall.checked = false;
    overall.indeterminate = false;
  } else if (checkedCount === ingredients.length) {
    overall.checked = true;
    overall.indeterminate = false;
  } else {
    overall.checked = false;
    overall.indeterminate = true;
  }
}
```

**Note:** If you submit a form with an indeterminate checkbox, the same thing happens as if the checkbox were unchecked — no data is submitted to represent the checkbox.

Validation
----------

Checkboxes do support validation (offered to all `<input>`s). However, most of the `ValidityState`s will always be `false`. If the checkbox has the `required` attribute, but is not checked, then `ValidityState.valueMissing` will be `true`.

Examples
--------

The following example is an extended version of the "multiple checkboxes" example we saw above — it has more standard options, plus an "other" checkbox that when checked causes a text field to appear to enter a value for the "other" option. This is achieved with a simple block of JavaScript. The example includes implicit labels, with the `<input>` directly inside the `<label>`. The text input, without a visible label, includes the `aria-label` attribute which provides its accessible name. This example also includes some CSS to improve the styling.

### HTML

```html
<form>
  <fieldset>
    <legend>Choose your interests</legend>
    <div>
      <label>
        <input type="checkbox" id="coding" name="interest" value="coding" />
        Coding
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="music" name="interest" value="music" />
        Music
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="art" name="interest" value="art" />
        Art
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="sports" name="interest" value="sports" />
        Sports
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="cooking" name="interest" value="cooking" />
        Cooking
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="other" name="interest" value="other" />
        Other
      </label>
      <input
 type="text"
 id="otherValue"
 name="other"
 aria-label="Other interest" />
    </div>
    <div>
      <button type="submit">Submit form</button>
    </div>
  </fieldset>
</form>
```

### CSS

```css
html {
  font-family: sans-serif;
}

form {
  width: 600px;
  margin: 0 auto;
}

div {
  margin-bottom: 10px;
}

fieldset {
  background: cyan;
  border: 5px solid blue;
}

legend {
  padding: 10px;
  background: blue;
  color: cyan;
}
```

### JavaScript

```js
const otherCheckbox = document.querySelector("#other");
const otherText = document.querySelector("#otherValue");
otherText.style.visibility = "hidden";

otherCheckbox.addEventListener("change", () => {
  if (otherCheckbox.checked) {
    otherText.style.visibility = "visible";
    otherText.value = "";
  } else {
    otherText.style.visibility = "hidden";
  }
});
```

Technical summary
-----------------

|  |  |
| --- | --- |
| **Value** |
 A string representing the value of the
 checkbox.
  |
| **Events** | `change` and `input` |
| **Supported common attributes** | `checked` |
| **IDL attributes** | `checked`,
 `indeterminate` and
 `value` |
| **DOM interface** | `HTMLInputElement` |
| **Methods** | `select()` |
| **Implicit ARIA Role** | `checkbox` |

Specifications
--------------

| Specification |
| --- |
| HTML Standard # checkbox-state-(type=checkbox) |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `:checked`, `:indeterminate`: CSS selectors that let you style checkboxes based on their current state
* `HTMLInputElement`: HTML DOM API that implements the `<input>` element
* CSS property compatibility table for form controls


<input type="text"> - HTML: HyperText Markup Language

<input type="text">
===================

`<input>` elements of type **`text`** create basic single-line text fields.

Try it
------

Value
-----

The `value` attribute is a string that contains the current value of the text entered into the text field. You can retrieve this using the `HTMLInputElement` `value` property in JavaScript.

```js
let theText = myTextInput.value;
```

If no validation constraints are in place for the input (see Validation for more details), the value may be an empty string (`""`).

Additional attributes
---------------------

In addition to the attributes that operate on all `<input>` elements regardless of their type, text inputs support the following attributes.

### `list`

The values of the list attribute is 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.

### `maxlength`

The maximum string length (measured in UTF-16 code units) that the user can enter into the `text` input. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `text` input 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 value of the field is greater than `maxlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

### `minlength`

The minimum string length (measured in UTF-16 code units) that the user can enter into the `text` input. This must be a 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 `text` 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. Constraint validation is only applied when the value is changed by the user.

### `pattern`

The `pattern` attribute, when specified, is a regular expression that the input's `value` must match for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the `RegExp` type, and as documented in our guide on regular expressions; 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 specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

**Note:** Use the `title` attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.

See Specifying a pattern for further details and an example.

### `placeholder`

The `placeholder` attribute 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 demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds.

If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

**Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See `<input>` accessibility concerns for more information.

### `readonly`

A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the `HTMLInputElement` `value` property.

**Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified.

### `size`

The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (`font` settings in use).

This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the `maxlength` attribute.

### `spellcheck`

`spellcheck` is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of `spellcheck` on `<input>` elements. The permitted values for `spellcheck` are:

`false`

Disable spell checking for this element.

`true`

Enable spell checking for this element.

`""` (empty string) or no value

Follow the element's default behavior for spell checking. This may be based upon a parent's `spellcheck` setting or other factors.

An input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled.

The value returned by reading `spellcheck` may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting.

Non-standard attributes
-----------------------

The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped.

### `autocorrect`

A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are:

`on`

Enable automatic correction of typos, as well as processing of text substitutions if any are configured.

`off`

Disable automatic correction and text substitutions.

### `mozactionhint`
Deprecated

A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the `Enter` or `Return` key while editing the field.

**Deprecated: Use `enterkeyhint` instead.**

Using text inputs
-----------------

`<input>` elements of type `text` create basic, single-line inputs. You should use them anywhere you want the user to enter a single-line value and there isn't a more specific input type available for collecting that value (for example, if it's a date, URL, email, or search term, you've got better options available).

### Basic example

```html
<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input type="text" id="uname" name="name" />
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

This renders like so:

When submitted, the data name/value pair sent to the server will be `name=Chris` (if "Chris" was entered as the input value before submission). You must remember to include `name` attribute on the `<input>` element, otherwise the text field's value won't be included with the submitted data.

### Setting placeholders

You can provide a useful placeholder inside your text input that can provide a hint as to what to enter by including using the `placeholder` attribute. Look at the following example:

```html
<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input
 type="text"
 id="uname"
 name="name"
 placeholder="Lower case, all one word" />
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

You can see how the placeholder is rendered below:

The placeholder is typically rendered in a lighter color than the element's foreground color, and automatically vanishes when the user begins to enter text into the field (or whenever the field has a value set programmatically by setting its `value` attribute).

### Physical input element size

The physical size of the input box can be controlled using the `size` attribute. With it, you can specify the number of characters the text input can display at a time. This affects the width of the element, letting you specify the width in terms of characters rather than pixels. In this example, for instance, the input is 30 characters wide:

```html
<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input
 type="text"
 id="uname"
 name="name"
 placeholder="Lower case, all one word"
 size="30" />
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

Validation
----------

`<input>` elements of type `text` have no automatic validation applied to them (since a basic text input needs to be capable of accepting any arbitrary string), but there are some client-side validation options available, which we'll discuss below.

**Note:** HTML form validation is *not* a substitute for server-scripts that ensure 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 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 (or data which is too large, is of the wrong type, and so forth) is entered into your database.

### A note on styling

There are useful pseudo-classes available for styling form elements to help the user see when their values are valid or invalid. These are `:valid` and `:invalid`. In this section, we'll use the following CSS, which will place a check (tick) mark next to inputs containing valid values, and a cross (X) next to inputs containing invalid values.

```css
div {
  margin-bottom: 10px;
  position: relative;
}

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;
}
```

The technique also requires a `<span>` element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don't display icons placed directly after them very well.

### Making input required

You can use the `required` attribute as an easy way of making entering a value required before form submission is allowed:

```html
<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input type="text" id="uname" name="name" required />
    <span class="validity"></span>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

```
div {
  margin-bottom: 10px;
  position: relative;
}
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;
}
```

This renders like so:

If you try to submit the form with no search term entered into it, the browser will show an error message.

### Input value length

You can specify a minimum length (in characters) for the entered value using the `minlength` attribute; similarly, use `maxlength` to set the maximum length of the entered value, in characters.

The example below requires that the entered value be 4–8 characters in length.

```html
<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input
 type="text"
 id="uname"
 name="name"
 required
 size="10"
 placeholder="Username"
 minlength="4"
 maxlength="8" />
    <span class="validity"></span>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

```
div {
  margin-bottom: 10px;
  position: relative;
}
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;
}
```

This renders like so:

If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to enter more than 8 characters, the browser won't let you.

**Note:** If you specify a `minlength` but do not specify `required`, the input is considered valid, since the user is not required to specify a value.

### Specifying a pattern

You can use the `pattern` attribute to specify a regular expression that the inputted value must match in order to be considered valid (see Validating against a regular expression for a simple crash course on using regular expressions to validate inputs).

The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.

```html
<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input
 type="text"
 id="uname"
 name="name"
 required
 size="45"
 pattern="[a-z]{4,8}" />
    <span class="validity"></span>
    <p>Usernames must be lowercase and 4-8 characters in length.</p>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

```
div {
  margin-bottom: 10px;
  position: relative;
}

p {
  font-size: 80%;
  color: #999;
}

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;
}
```

This renders like so:

Examples
--------

You can see good examples of text inputs used in context in our Your first HTML form and How to structure an HTML form articles.

Technical summary
-----------------

|  |  |
| --- | --- |
| **Value** |
 A string representing the text contained in
 the text field.
  |
| **Events** | `change` and
 `input` |
| **Supported Common Attributes** | `autocomplete`,
 `list`,
 `maxlength`,
 `minlength`,
 `pattern`,
 `placeholder`,
 `readonly`,
 `required` and
 `size` |
| **IDL attributes** | `list`, `value` |
| **DOM interface** | `HTMLInputElement` |
| **Methods** | `select()`,
 `setRangeText()`
 and
 `setSelectionRange()`.
  |
| **Implicit ARIA Role** |
 with no `list` attribute:
 `textbox` | with `list` attribute: `combobox` |

Specifications
--------------

| Specification |
| --- |
| HTML Standard # text-(type=text)-state-and-search-state-(type=search) |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTML Forms
* `<input>` and the `HTMLInputElement` interface it's based upon.
* `<input type="search">`
* `<textarea>`: Multi-line text input
* Compatibility of CSS properties