<legend>: The Field Set Legend element - HTML: HyperText Markup Language

<legend>: The Field Set Legend element
======================================

The **`<legend>`** HTML element represents a caption for the content of its parent `<fieldset>`.

Try it
------

Attributes
----------

This element only includes the global attributes.

Examples
--------

See `<form>` for examples on `<legend>`.

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

|  |  |
| --- | --- |
| Content categories | None. |
| Permitted content | Phrasing content
 and
 headings
 (h1–h6 elements).
  |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents |
 A `<fieldset>` whose first child is this
 `<legend>` element
  |
| Implicit ARIA role | No corresponding role |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | `HTMLLegendElement` |

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

| Specification |
| --- |
| HTML Standard # the-legend-element |

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

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

See also
--------

* ARIA: Form role


<td>: The Table Data Cell element - HTML: HyperText Markup Language

<td>: The Table Data Cell element
=================================

The **`<td>`** HTML element defines a cell of a table that contains data. It participates in the *table model*.

Try it
------

Attributes
----------

This element includes the global attributes.

`colspan`

This attribute contains a non-negative integer value that indicates for how many columns the cell extends. Its default value is `1`. Values higher than 1000 will be considered as incorrect and will be set to the default value (1).

`headers`

This attribute contains a list of space-separated strings, each corresponding to the **id** attribute of the `<th>` elements that apply to this element.

`rowspan`

This attribute contains a non-negative integer value that indicates for how many rows the cell extends. Its default value is `1`; if its value is set to `0`, it extends until the end of the table section (`<thead>`, `<tbody>`, `<tfoot>`, even if implicitly defined), that the cell belongs to. Values higher than 65534 are clipped down to 65534.

### Deprecated attributes

`abbr`
Deprecated

This attribute contains a short abbreviated description of the cell's content. Some user-agents, such as speech readers, may present this description before the content itself.

**Note:** Do not use this attribute as it is obsolete in the latest standard. Alternatively, you can put the abbreviated description inside the cell and place the long content in the **title** attribute.

`align`
Deprecated

This enumerated attribute specifies how the cell content's horizontal alignment will be handled. Possible values are:

* `left`: The content is aligned to the left of the cell.
* `center`: The content is centered in the cell.
* `right`: The content is aligned to the right of the cell.
* `justify` (with text only): The content is stretched out inside the cell so that it covers its entire width.
* `char` (with text only): The content is aligned to a character inside the `<th>` element with minimal offset. This character is defined by the `char` and `charoff` attributes.

The default value when this attribute is not specified is `left`.

**Note:**

* To achieve the same effect as the `left`, `center`, `right` or `justify` values, apply the CSS `text-align` property to the element.
* To achieve the same effect as the `char` value, give the `text-align` property the same value you would use for the `char`.

`axis`
Deprecated

This attribute contains a list of space-separated strings. Each string is the `id` of a group of cells that this header applies to.

`bgcolor`
Deprecated

This attribute defines the background color of each cell in a column. It is a 6-digit hexadecimal RGB code, prefixed by a '`#`'. One of the predefined color keywords can also be used.

To achieve a similar effect, use the CSS `background-color` property.

`char`
Deprecated

The content in the cell element is aligned to a character. Typical values include a period (.) to align numbers or monetary values. If `align` is not set to `char`, this attribute is ignored.

`charoff`
Deprecated

This attribute is used to shift column data to the right of the character specified by the **char** attribute. Its value specifies the length of this shift.

`height`
Deprecated

This attribute is used to define a recommended cell height. Use the CSS `height` property instead.

`scope`
Deprecated

This enumerated attribute defines the cells that the header (defined in the `<th>`) element relates to. Only use this attribute with the `<th>` element to define the row or column for which it is a header.

`valign`
Deprecated

This attribute specifies how a text is vertically aligned inside a cell. Possible values for this attribute are:

* `baseline`: Positions the text near the bottom of the cell and aligns it with the baseline of the characters instead of the bottom. If characters don't descend below the baseline, the baseline value achieves the same effect as `bottom`.
* `bottom`: Positions the text near the bottom of the cell.
* `middle`: Centers the text in the cell.
* and `top`: Positions the text near the top of the cell.

To achieve a similar effect, use the CSS `vertical-align` property.

`width`
Deprecated

This attribute is used to define a recommended cell width. Use the CSS `width` property instead.

Examples
--------

See `<table>` for examples on `<td>`.

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

|  |  |
| --- | --- |
| Content categories | Sectioning root. |
| Permitted content | Flow content. |
| Tag omission |
 The start tag is mandatory.The end tag may be omitted, if it is
 immediately followed by a `<th>` or
 `<td>` element or if there are no more data in its
 parent element.
  |
| Permitted parents | A `<tr>` element. |
| Implicit ARIA role | `cell`
 if a descendant of a `<table>` element
  |
| Permitted ARIA roles | Any |
| DOM interface | `HTMLTableCellElement` |

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

| Specification |
| --- |
| HTML Standard # the-td-element |

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

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


<center>: The Centered Text element - HTML: HyperText Markup Language

<center>: The Centered Text element
===================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`<center>`** HTML element is a block-level element that displays its block-level or inline contents centered horizontally within its containing element. The container is usually, but isn't required to be, `<body>`.

This tag has been deprecated in HTML 4 (and XHTML 1) in favor of the CSS `text-align` property, which can be applied to the `<div>` element or to an individual `<p>`. For centering blocks, use other CSS properties like `margin-left` and `margin-right` and set them to `auto` (or set `margin` to `0 auto`).

DOM interface
-------------

This element implements the `HTMLElement` interface.

Example 1
---------

```html
<center>
  This text will be centered.
  <p>So will this paragraph.</p>
</center>
```

### Result

Example 2 (CSS alternative)
---------------------------

```html
<div style="text-align:center">
  This text will be centered.
  <p>So will this paragraph.</p>
</div>
```

### Result

Example 3 (CSS alternative)
---------------------------

```html
<p style="text-align:center">
  This line will be centered.<br />
  And so will this line.
</p>
```

### Result

**Note:** Applying `text-align``:center` to a `<div>` or `<p>` element centers the *contents* of those elements while leaving their overall dimensions unchanged.

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

| Specification |
| --- |
| HTML Standard # center |

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

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

See also
--------

* `text-align`
* `display`


<optgroup>: The Option Group element - HTML: HyperText Markup Language

<optgroup>: The Option Group element
====================================

The **`<optgroup>`** HTML element creates a grouping of options within a `<select>` element.

Try it
------

**Note:** Optgroup elements may not be nested.

Attributes
----------

This element includes the global attributes.

`disabled`

If this Boolean attribute is set, none of the items in this option group is selectable. Often browsers grey out such control and it won't receive any browsing events, like mouse clicks or focus-related ones.

`label`

The name of the group of options, which the browser can use when labeling the options in the user interface. This attribute is mandatory if this element is used.

Examples
--------

```html
<select>
  <optgroup label="Group 1">
    <option>Option 1.1</option>
  </optgroup>
  <optgroup label="Group 2">
    <option>Option 2.1</option>
    <option>Option 2.2</option>
  </optgroup>
  <optgroup label="Group 3" disabled>
    <option>Option 3.1</option>
    <option>Option 3.2</option>
    <option>Option 3.3</option>
  </optgroup>
</select>
```

### Result

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

|  |  |
| --- | --- |
| Content categories | None. |
| Permitted content | Zero or more `<option>` elements. |
| Tag omission |
 The start tag is mandatory. The end tag is optional if this element is
 immediately followed by another `<optgroup>` element, or
 if the parent element has no more content.
  |
| Permitted parents | A `<select>` element. |
| Implicit ARIA role | `group` |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | `HTMLOptGroupElement` |

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

| Specification |
| --- |
| HTML Standard # the-optgroup-element |

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

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

See also
--------

* Other form-related elements: `<form>`, `<legend>`, `<label>`, `<button>`, `<select>`, `<datalist>`, `<option>`, `<fieldset>`, `<textarea>`, `<input>`, `<output>`, `<progress>` and `<meter>`.


<nobr>: The Non-Breaking Text element - HTML: HyperText Markup Language

<nobr>: The Non-Breaking Text element
=====================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`<nobr>`** HTML element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text.

**Warning:** Although this element is widely supported, it was *never* standard HTML, so you shouldn't use it. Instead, use the CSS property `white-space` like this:

```html
<span style="white-space: nowrap;">Long line with no breaks</span>
```

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

| Specification |
| --- |
| HTML Standard # nobr |

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

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

See also
--------

* `white-space`
* `overflow`


<ul>: The Unordered List element - HTML: HyperText Markup Language

<ul>: The Unordered List element
================================

The **`<ul>`** HTML element represents an unordered list of items, typically rendered as a bulleted list.

Try it
------

Attributes
----------

This element includes the global attributes.

`compact`
Deprecated

Non-standard

This Boolean attribute hints that the list should be rendered in a compact style. The interpretation of this attribute depends on the user agent, and it doesn't work in all browsers.

**Warning:** Do not use this attribute, as it has been deprecated: use CSS instead. To give a similar effect as the `compact` attribute, the CSS property `line-height` can be used with a value of `80%`.

`type`
Deprecated

Non-standard

This attribute sets the bullet style for the list. The values defined under HTML3.2 and the transitional version of HTML 4.0/4.01 are:

* `circle`
* `disc`
* `square`

A fourth bullet type has been defined in the WebTV interface, but not all browsers support it: `triangle`.

If not present and if no CSS `list-style-type` property applies to the element, the user agent selects a bullet type depending on the nesting level of the list.

**Warning:** Do not use this attribute, as it has been deprecated; use the CSS `list-style-type` property instead.

Usage notes
-----------

* The `<ul>` element is for grouping a collection of items that do not have a numerical ordering, and their order in the list is meaningless. Typically, unordered-list items are displayed with a bullet, which can be of several forms, like a dot, a circle, or a square. The bullet style is not defined in the HTML description of the page, but in its associated CSS, using the `list-style-type` property.
* The `<ul>` and `<ol>` elements may be nested as deeply as desired. Moreover, the nested lists may alternate between `<ol>` and `<ul>` without restriction.
* The `<ol>` and `<ul>` elements both represent a list of items. They differ in that, with the `<ol>` element, the order is meaningful. To determine which one to use, try changing the order of the list items; if the meaning is changed, the `<ol>` element should be used, otherwise you can use `<ul>`.
Examples
--------

### Simple example

```html
<ul>
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
</ul>
```

#### Result

### Nesting a list

```html
<ul>
  <li>first item</li>
  <li>
    second item
    <!-- Look, the closing </li> tag is not placed here! -->
    <ul>
      <li>second item first subitem</li>
      <li>
        second item second subitem
        <!-- Same for the second nested unordered list! -->
        <ul>
          <li>second item second subitem first sub-subitem</li>
          <li>second item second subitem second sub-subitem</li>
          <li>second item second subitem third sub-subitem</li>
        </ul>
      </li>
      <!-- Closing </li> tag for the li that
 contains the third unordered list -->
      <li>second item third subitem</li>
    </ul>
    <!-- Here is the closing </li> tag -->
  </li>
  <li>third item</li>
</ul>
```

#### Result

### Ordered list inside unordered list

```html
<ul>
  <li>first item</li>
  <li>
    second item
    <!-- Look, the closing </li> tag is not placed here! -->
    <ol>
      <li>second item first subitem</li>
      <li>second item second subitem</li>
      <li>second item third subitem</li>
    </ol>
    <!-- Here is the closing </li> tag -->
  </li>
  <li>third item</li>
</ul>
```

#### Result

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

|  |  |
| --- | --- |
| Content categories | Flow content, and if the `<ul>` element's children include at least
 one `<li>` element,
 palpable content.
  |
| Permitted content |
 Zero or more `<li>`,
 `<script>` and
 `<template>` elements.
  |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents |
 Any element that accepts
 flow content.
  |
| Implicit ARIA role | `list` |
| Permitted ARIA roles | `directory`, `group`,
 `listbox`, `menu`,
 `menubar`, `none`,
 `presentation`,
 `radiogroup`, `tablist`,
 `toolbar`, `tree` |
| DOM Interface | `HTMLUListElement` |

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

| Specification |
| --- |
| HTML Standard # the-ul-element |

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

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

See also
--------

* Other list-related HTML Elements: `<ol>`, `<li>`, `<menu>`
* CSS properties that may be specially useful to style the `<ul>` element:
    + the `list-style` property, to choose the way the ordinal displays.
    + CSS counters, to handle complex nested lists.
    + the `line-height` property, to simulate the deprecated `compact` attribute.
    + the `margin` property, to control the list indentation.


Standard metadata names - HTML: HyperText Markup Language

Standard metadata names
=======================

The `<meta>` element can be used to provide document metadata in terms of name-value pairs, with the `name` attribute giving the metadata name, and the `content` attribute giving the value.

### Standard metadata names defined in the HTML specification

The HTML specification defines the following set of standard metadata names:

* `application-name`: the name of the application running in the web page.

**Note:**

    + Browsers may use this to identify the application. It is different from the `<title>` element, which usually contain the application name, but may also contain information like the document name or a status.
    + Simple web pages shouldn't define an application-name.
* `author`: the name of the document's author.
* `description`: a short and accurate summary of the content of the page. Several browsers, like Firefox and Opera, use this as the default description of bookmarked pages.
* `generator`: the identifier of the software that generated the page.
* `keywords`: words relevant to the page's content separated by commas.
* `referrer`: controls the HTTP `Referer` header of requests sent from the document:

 Values for the
 `content`
 attribute of
 `<meta name="referrer">`
| `no-referrer` | Do not send a HTTP `Referer` header. |
| `origin` | Send the origin of the document. |
| `no-referrer-when-downgrade` |
 Send the full URL when the destination is at least as secure as the
 current page (HTTP(S)→HTTPS), but send no referrer when it's less secure
 (HTTPS→HTTP). This is the default behavior.
  |
| `origin-when-cross-origin` |
 Send the full URL (stripped of parameters) for same-origin requests, but
 only send the origin for other cases.
  |
| `same-origin` |
 Send the full URL (stripped of parameters) for same-origin requests.
 Cross-origin requests will contain no referrer header.
  |
| `strict-origin` |
 Send the origin when the destination is at least as secure as the
 current page (HTTP(S)→HTTPS), but send no referrer when it's less secure
 (HTTPS→HTTP).
  |
| `strict-origin-when-cross-origin` |
 Send the full URL (stripped of parameters) for same-origin requests.
 Send the origin when the destination is at least as secure as the
 current page (HTTP(S)→HTTPS). Otherwise, send no referrer.
  |
| `unsafe-URL` |
 Send the full URL (stripped of parameters) for same-origin or
 cross-origin requests.
  |

**Note:**

    + Dynamically inserting `<meta name="referrer">` (with `document.write()` or `appendChild()`) makes the referrer behavior unpredictable.
    + When several conflicting policies are defined, the `no-referrer` policy is applied.
* `theme-color`: indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. The `content` attribute contains a valid CSS `<color>`. The `media` attribute with a valid media query list can be included to set the media the theme color metadata applies to.
* `color-scheme`: specifies one or more color schemes with which the document is compatible.
 The browser will use this information in tandem with the user's browser or device settings to determine what colors to use for everything from background and foregrounds to form controls and scrollbars. The primary use for `<meta name="color-scheme">` is to indicate compatibility with—and order of preference for—light and dark color modes.
 The value of the `content` property for `color-scheme` may be one of the following:

`normal`

The document is unaware of color schemes and should be rendered using the default color palette.

[`light` | `dark`]+

One or more color schemes supported by the document. Specifying the same color scheme more than once has the same effect as specifying it only once. Indicating multiple color schemes indicates that the first scheme is preferred by the document, but that the second specified scheme is acceptable if the user prefers it.

`only light`

Indicates that the document *only* supports light mode, with a light background and dark foreground colors. By specification, `only dark` *is not valid*, because forcing a document to render in dark mode when it isn't truly compatible with it can result in unreadable content; all major browsers default to light mode if not otherwise configured.

For example, to indicate that a document prefers dark mode but does render functionally in light mode as well:

```html
<meta name="color-scheme" content="dark light" />
```

This works at the document level in the same way that the CSS `color-scheme` property lets individual elements specify their preferred and accepted color schemes. Your styles can adapt to the current color scheme using the `prefers-color-scheme` CSS media feature.
### Standard metadata names defined in other specifications

The CSS Device Adaptation specification defines the following metadata name:

* `viewport`: gives hints about the size of the initial size of the viewport.

 Values for the content of
 `<meta name="viewport">`
| Value | Possible subvalues | Description |
| --- | --- | --- |
| `width` | A positive integer number, or the text `device-width` |
 Defines the pixel width of the viewport that you want the website to be
 rendered at.
  |
| `height` | A positive integer, or the text `device-height` | Defines the height of the viewport. Not used by any browser. |
| `initial-scale` | A positive number between `0.0` and `10.0` |
 Defines the ratio between the device width (`device-width` in
 portrait mode or `device-height` in landscape mode) and the
 viewport size.
  |
| `maximum-scale` | A positive number between `0.0` and `10.0` |
 Defines the maximum amount to zoom in. It must be greater or equal to
 the `minimum-scale` or the behavior is undefined. Browser
 settings can ignore this rule and iOS10+ ignores it by default.
  |
| `minimum-scale` | A positive number between `0.0` and `10.0` |
 Defines the minimum zoom level. It must be smaller or equal to the
 `maximum-scale` or the behavior is undefined. Browser
 settings can ignore this rule and iOS10+ ignores it by default.
  |
| `user-scalable` | `yes` or `no` |
 If set to `no`, the user is not able to zoom in the webpage.
 The default is `yes`. Browser settings can ignore this rule,
 and iOS10+ ignores it by default.
  |
| `viewport-fit` | `auto`, `contain` or `cover` |
 The `auto` value doesn't affect the initial layout
 viewport, and the whole web page is viewable.

 The `contain` value means that the viewport is scaled to
 fit the largest rectangle inscribed within the display.

 The `cover` value means that the viewport is scaled to fill
 the device display. It is highly recommended to make use of the
 safe area inset variables to
 ensure that important content doesn't end up outside the display.
  |

**Warning:**

Disabling zooming capabilities by setting `user-scalable` to a value of `no` prevents people experiencing low vision conditions from being able to read and understand page content.

    + MDN Understanding WCAG, Guideline 1.4 explanations
    + Understanding Success Criterion 1.4.4 | W3C Understanding WCAG 2.0
### Other metadata names

The WHATWG Wiki MetaExtensions page contains a large set of non-standard metadata names that have not been formally accepted yet; however, some of the names included there are already used quite commonly in practice — including the following:

* `creator`: the name of the creator of the document, such as an organization or institution. If there are more than one, several `<meta>` elements should be used.
* `googlebot`, a synonym of `robots`, is only followed by Googlebot (the indexing crawler for Google).
* `publisher`: the name of the document's publisher.
* `robots`: the behavior that cooperative crawlers, or "robots", should use with the page. It is a comma-separated list of the values below:

| Value | Description | Used by |
| --- | --- | --- |
| `index` | Allows the robot to index the page (default). | All |
| `noindex` | Requests the robot to not index the page. | All |
| `follow` | Allows the robot to follow the links on the page (default). | All |
| `nofollow` | Requests the robot to not follow the links on the page. | All |
| `all` | Equivalent to `index, follow` | Google |
| `none` | Equivalent to `noindex, nofollow` | Google |
| `noarchive` | Requests the search engine not to cache the page content. | Google, Yahoo, Bing |
| `nosnippet` | Prevents displaying any description of the page in search engine results. | Google, Bing |
| `noimageindex` | Requests this page not to appear as the referring page of an indexed image. | Google |
| `nocache` | Synonym of `noarchive`. | Bing |

**Note:**

    + Only cooperative robots follow these rules. Do not expect to prevent email harvesters with them.
    + The robot still needs to access the page in order to read these rules. To prevent bandwidth consumption, use a *robots.txt* file.
    + If you want to remove a page, `noindex` will work, but only after the robot visits the page again. Ensure that the `robots.txt` file is not preventing revisits.
    + Some values are mutually exclusive, like `index` and `noindex`, or `follow` and `nofollow`. In these cases the robot's behavior is undefined and may vary between them.
    + Some crawler robots, like Google, Yahoo and Bing, support the same values for the HTTP header `X-Robots-Tag`; this allows non-HTML documents like images to use these rules.

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

| Specification |
| --- |
| HTML Standard # standard-metadata-names |
| Referrer Policy # referrer-policy-delivery-meta |

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

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

See also
--------

* Viewport `<meta>` tag
* Metadata: the `<meta>` element in What's in the head? Metadata in HTML


theme-color - HTML: HyperText Markup Language

theme-color
===========

The **`theme-color`** value for the `name` attribute of the `<meta>` element indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. If specified, the `content` attribute must contain a valid CSS `<color>`.

Example
-------

```html
<meta name="theme-color" content="#4285f4" />
```

The following image shows the effect that the `<meta>` element above will have on a document displayed in Chrome running on an Android mobile device.

![Image showing the effect of using theme-color](/en-US/docs/Web/HTML/Element/meta/name/theme-color/theme-color.png)

*Image credit: from Icons & Browser Colors, created and shared by Google and used according to terms described in the Creative Commons 4.0 Attribution License.*

You can provide a media type or query inside the `media` attribute; the color will then only be set if the media condition is true. For example:

```html
<meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" />
```

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

| Specification |
| --- |
| HTML Standard # meta-theme-color |

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

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

See also
--------

* `color-scheme` CSS property
* `prefers-color-scheme` media query


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

<input type="time">
===================

`<input>` elements of type **`time`** create input fields designed to let the user easily enter a time (hours and minutes, and optionally seconds).

The control's user interface varies from browser to browser; see Browser compatibility for further details. In unsupported browsers, the control degrades gracefully to `<input type="text">`.

Try it
------

Appearance
----------

### Chrome and Opera

In Chrome/Opera the `time` control is simple, with slots to enter hours and minutes in 12 or 24-hour format depending on operating system locale, and up and down arrows to increment and decrement the currently selected component. In some versions, an "X" button is provided to clear the control's value.

![12-hour Chrome time input](/en-US/docs/Web/HTML/Element/input/time/chrome_time.png) 12-hour

![24-hour Chrome time input](/en-US/docs/Web/HTML/Element/input/time/chrome-time.png) 24-hour

### Firefox

Firefox's `time` control is very similar to Chrome's, except that it doesn't have the up and down arrows. It also uses a 12- or 24-hour format for inputting times, based on system locale. An "X" button is provided to clear the control's value.

![12-hour Firefox time input](/en-US/docs/Web/HTML/Element/input/time/firefox-time.png) 12-hour

![24-hour Firefox time input](/en-US/docs/Web/HTML/Element/input/time/firefox-time-24.png) 24-hour

### Edge

The Edge `time` control is somewhat more elaborate, opening up an hour and minute picker with sliding reels. It, like Chrome, uses a 12- or 24-hour format for inputting times, based on system locale:

![12-hour Edge time input](/en-US/docs/Web/HTML/Element/input/time/edge_time.png) 12-hour

![24-hour Edge time input](/en-US/docs/Web/HTML/Element/input/time/edge-time.png) 24-hour

Value
-----

A string containing the value of the time entered into the input.

### Setting the value attribute

You can set a default value for the input by including a valid time in the `value` attribute when creating the `<input>` element, like so:

```html
<label for="appt-time">Choose an appointment time: </label>
<input id="appt-time" type="time" name="appt-time" value="13:30" />
```

### Setting the value using JavaScript

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

```js
const timeControl = document.querySelector('input[type="time"]');
timeControl.value = "15:30";
```

### Time value format

The `value` of the `time` input is always in 24-hour format that includes leading zeros: `hh:mm`, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent). If the time includes seconds (see Using the step attribute), the format is always `hh:mm:ss`. You can learn more about the format of the time value used by this input type in Time strings.

In this example, you can see the time input's value by entering a time and seeing how it changes afterward.

First, a look at the HTML. This is simple enough, with the label and input as we've seen before, but with the addition of a `<p>` element with a `<span>` to display the value of the `time` input:

```html
<form>
  <label for="startTime">Start time: </label>
  <input type="time" id="startTime" />
  <p>
    Value of the <code>time</code> input:
    <code> "<span id="value">n/a</span>"</code>.
  </p>
</form>
```

The JavaScript code adds code to the time input to watch for the `input` event, which is triggered every time the contents of an input element change. When this happens, the contents of the `<span>` are replaced with the new value of the input element.

```js
const startTime = document.getElementById("startTime");
const valueSpan = document.getElementById("value");

startTime.addEventListener(
  "input",
  () => {
    valueSpan.innerText = startTime.value;
  },
  false,
);
```

When a form including a `time` input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form `name=hh%3Amm`, or `name=hh%3Amm%3Ass` if seconds are included (see Using the step attribute).

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

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

**Note:** Unlike many data types, time values have a **periodic domain**, meaning that the values reach the highest possible value, then wrap back around to the beginning again. For example, specifying a `min` of `14:00` and a `max` of `2:00` means that the permitted time values start at 2:00 PM, run through midnight to the next day, ending at 2:00 AM. See more in the making min and max cross midnight section of this article.

### 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

A string indicating the latest time to accept, specified in the same time value format as described above. If the specified string isn't a valid time, no maximum value is set.

### min

A string specifying the earliest time to accept, given in the time value format described previously. If the value specified isn't a valid time string, no minimum value is set.

### 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.

For `time` inputs, the value of `step` is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of `step` is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds).

*At this time, it's unclear what a value of `any` means for `step` when used with `time` inputs. This will be updated as soon as that information is determined.*

Using time inputs
-----------------

### Basic uses of time

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

```html
<form>
  <label for="appt-time">Choose an appointment time: </label>
  <input id="appt-time" type="time" name="appt-time" />
</form>
```

### Controlling input size

`<input type="time">` doesn't support form sizing attributes such as `size`, since times are always about the same number of characters long. You'll have to resort to CSS for sizing needs.

### Using the step attribute

You can use the `step` attribute to vary the amount of time jumped whenever the time is incremented or decremented (for example, so the time moves by 10 minutes at a time when clicking the little arrow widgets).

**Note:** This property has some strange effects across browsers, so is not completely reliable.

It takes an integer value that equates to the number of seconds you want to increment by; the default value is 60 seconds, or one minute. If you specify a value of less than 60 seconds (1 minute), the `time` input will show a seconds input area alongside the hours and minutes:

```html
<form>
  <label for="appt-time">Choose an appointment time: </label>
  <input id="appt-time" type="time" name="appt-time" step="2" />
</form>
```

In Chrome and Opera, which are the only browsers to show up/down iteration arrows, clicking the arrows changes the seconds value by two seconds, but doesn't affect the hours or minutes. Minutes (or hours) can only be used for stepping when you specify a number of minutes (or hours) in seconds, such as 120 for 2 minutes, or 7200 for 2 hours).

In Firefox, there are no arrows, so the `step` value isn't used. However, providing it *does* add the seconds input area adjacent to the minutes section.

The steps value seems to have no effect in Edge.

**Note:** Using `step` seems to cause validation to not work properly (as seen in the next section).

Validation
----------

By default, `<input type="time">` does not apply any validation to entered values, other than the user agent's interface generally not allowing you to enter anything other than a time value. This is helpful (assuming the `time` input is fully supported by the user agent), but you can't entirely rely on the value to be a proper time string, since it might be an empty string (`""`), which is allowed. It's also possible for the value to look roughly like a valid time but not be correct, such as `25:05`.

### Setting maximum and minimum times

You can use the `min` and `max` attributes to restrict the valid times that can be chosen by the user. In the following example we are setting a minimum time of `12:00` and a maximum time of `18:00`:

```html
<form>
  <label for="appt-time">
    Choose an appointment time (opening hours 12:00 to 18:00):
  </label>
  <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" />
  <span class="validity"></span>
</form>
```

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

The result here is that:

* Only times between 12:00 and 18:00 will be seen as valid; times outside that range will be denoted as invalid.
* Depending on what browser you're using, you might find that times outside the specified range might not even be selectable in the time picker (e.g. Edge).

#### Making min and max cross midnight

By setting a `min` attribute greater than the `max` attribute, the valid time range will wrap around midnight to produce a valid time range which crosses midnight. This functionality is not supported by any other input types. While this feature is in the HTML spec, it is not yet universally supported. Chrome-based browsers support it starting in version 82 and Firefox added it in version 76. Safari as of version 14.1 does not support this. Be prepared for this situation to arise:

```js
const input = document.createElement("input");
input.type = "time";
input.min = "23:00";
input.max = "01:00";
input.value = "23:59";

if (input.validity.valid && input.type === "time") {
  // <input type=time> reversed range supported
} else {
  // <input type=time> reversed range unsupported
}
```

### Making times required

In addition, you can use the `required` attribute to make filling in the time mandatory. As a result, supporting browsers will display an error if you try to submit a time that is outside the set bounds, or an empty time field.

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

```html
<form>
  <div>
    <label for="appt-time">
      Choose an appointment time (opening hours 12:00 to 18:00):
    </label>
    <input
 id="appt-time"
 type="time"
 name="appt-time"
 min="12:00"
 max="18:00"
 required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>
```

If you try to submit the form with an incomplete time (or with a time outside the set bounds), the browser displays an error. Try playing with the example now:

**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, older versions of Safari and a few other, less common, browsers don't support time inputs natively. In general, otherwise, support is good — especially on mobile platforms, which tend to have very nice user interfaces for specifying a time value. For example, the `time` picker on Chrome for Android looks like this:

![Phone screen showing modal dialog with 10:21 as a header. The 10 is fully opaque. The 21 is not. The main area has a circle with the numbers 1 - 12 in a ring, and the number 13 -24 on an inner ring. The number 10 is highlighted with a blue circle. The buttons at the bottom are clear, cancel, and set.](/en-US/docs/Web/HTML/Element/input/time/chrome-android-time.png)

Browsers that don't support time inputs 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; as mentioned previously, `time` inputs' values are always normalized to the format `hh:mm` or `hh:mm:ss`. With a text input, on the other hand, by default the browser has no idea of what format the time should be in, and there are multiple ways in which people write times, such as:

* `3.00 pm`
* `3:00pm`
* `15:00`
* `3 o'clock in the afternoon`
* etc.

One way around this is to put a `pattern` attribute on your `time` input. Even though the `time` input doesn't use it, the `text` input fallback will. For example, try viewing the following demo in a browser that doesn't support time inputs:

```html
<form>
  <div>
    <label for="appt-time">
      Choose an appointment time (opening hours 12:00 to 18:00):
    </label>
    <input
 id="appt-time"
 type="time"
 name="appt-time"
 min="12:00"
 max="18:00"
 required
 pattern="[0-9]{2}:[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 non-supporting browsers now display an error message (and highlight the input as invalid) if your entry doesn't match the pattern `nn:nn`, where `n` is a number from 0 to 9. Of course, this doesn't stop people from entering invalid times, or incorrectly formatted times that follow the pattern.

Then there's the problem of the user having no idea exactly what format the time is expected to be in.
```

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 times in forms in a cross-browser way, for the time being, is to get the user to enter the hours and minutes (and seconds if required) in separate controls (`<select>` elements are popular; see below for an example), or use JavaScript libraries such as the jQuery timepicker plugin.

Examples
--------

In this example, we create two sets of interface elements for choosing times: a native picker created with `<input type="time">`, and a set of two `<select>` elements for choosing hours/minutes in older browsers that don't support the native input.

The HTML looks like so:

```html
<form>
  <div class="nativeTimePicker">
    <label for="appt-time">
      Choose an appointment time (opening hours 12:00 to 18:00):
    </label>
    <input
 id="appt-time"
 type="time"
 name="appt-time"
 min="12:00"
 max="18:00"
 required />
    <span class="validity"></span>
  </div>
  <p class="fallbackLabel">
    Choose an appointment time (opening hours 12:00 to 18:00):
  </p>
  <div class="fallbackTimePicker">
    <div>
      <span>
        <label for="hour">Hour:</label>
        <select id="hour" name="hour"></select>
      </span>
      <span>
        <label for="minute">Minute:</label>
        <select id="minute" name="minute"></select>
      </span>
    </div>
  </div>
</form>
```

The hour and minutes values for their `<select>` elements are dynamically generated.
```

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 other part of the code that may be of interest is the feature detection code — to detect whether the browser supports `<input type="time">`, we create a new `<input>` element, try setting its `type` to `time`, then immediately check what its type is set to — non-supporting browsers will return `text`, because the `time` type falls back to type `text`. If `<input type="time">` is not supported, we hide the native picker and show the fallback picker UI (`<select>`s) instead.

```js
// Define variables
const nativePicker = document.querySelector(".nativeTimePicker");
const fallbackPicker = document.querySelector(".fallbackTimePicker");
const fallbackLabel = document.querySelector(".fallbackLabel");

const hourSelect = document.querySelector("#hour");
const minuteSelect = document.querySelector("#minute");

// Hide fallback initially
fallbackPicker.style.display = "none";
fallbackLabel.style.display = "none";

// Test whether a new time input falls back to a text input or not
const test = document.createElement("input");

try {
  test.type = "time";
} 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 hours and minutes dynamically
  populateHours();
  populateMinutes();
}

function populateHours() {
  // Populate the hours <select> with the 6 open hours of the day
  for (let i = 12; i <= 18; i++) {
    const option = document.createElement("option");
    option.textContent = i;
    hourSelect.appendChild(option);
  }
}

function populateMinutes() {
  // populate the minutes <select> with the 60 hours of each minute
  for (let i = 0; i <= 59; i++) {
    const option = document.createElement("option");
    option.textContent = i < 10 ? `0${i}` : i;
    minuteSelect.appendChild(option);
  }
}

// make it so that if the hour is 18, the minutes value is set to 00
// — you can't select times past 18:00
function setMinutesToZero() {
  if (hourSelect.value === "18") {
    minuteSelect.value = "00";
  }
}

hourSelect.onchange = setMinutesToZero;
minuteSelect.onchange = setMinutesToZero;
```

Technical Summary
-----------------

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

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

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

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="week">`, and `<input type="month">`
* Compatibility of CSS properties


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

<input type="submit">
=====================

`<input>` elements of type **`submit`** are rendered as buttons. When the `click` event occurs (typically because the user clicked the button), the user agent attempts to submit the form to the server.

Value
-----

An `<input type="submit">` element's `value` attribute contains a string which is displayed as the button's label. Buttons do not have a true value otherwise. The `value` provides the accessible description for the button.

### Setting the value attribute

```html
<input type="submit" value="Send Request" />
```

### Omitting the value attribute

If you don't specify a `value`, the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of "Submit" or "Submit Query." Here's an example of a submit button with a default label in your browser:

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

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

In addition to the attributes shared by all `<input>` elements, `submit` button inputs support the following attributes.

### formaction

A string indicating the URL to which to submit the data. This takes precedence over the `action` attribute on the `<form>` element that owns the `<input>`.

This attribute is also available on `<input type="image">` and `<button>` elements.

### formenctype

A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values:

`application/x-www-form-urlencoded`

This, the default value, sends the form data as a string after URL encoding the text using an algorithm such as `encodeURI()`.

`multipart/form-data`

Uses the `FormData` API to manage the data, allowing for files to be submitted to the server. You *must* use this encoding type if your form includes any `<input>` elements of `type` `file` (`<input type="file">`).

`text/plain`

Plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted.

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

This attribute is also available on `<input type="image">` and `<button>` elements.

### formmethod

A string indicating the HTTP method to use when submitting the form's data; this value overrides any `method` attribute given on the owning form. Permitted values are:

`get`

A URL is constructed by starting with the URL given by the `formaction` or `action` attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by `formenctype` or the form's `enctype` attribute. This URL is then sent to the server using an HTTP `get` request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value.

`post`

The form's data is included in the body of the request that is sent to the URL given by the `formaction` or `action` attribute using an HTTP `post` method. This method supports complex data and file attachments.

`dialog`

This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all.

This attribute is also available on `<input type="image">` and `<button>` elements.

### formnovalidate

A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the `novalidate` attribute on the element's owning form.

This attribute is also available on `<input type="image">` and `<button>` elements.

### formtarget

A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a **browsing context** (that is, a tab, window, or `<iframe>`). A value specified here overrides any target given by the `target` attribute on the `<form>` that owns this input.

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

`_self`

Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified.

`_blank`

Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.

`_parent`

Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as `_self`.

`_top`

Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as `_self`.

This attribute is also available on `<input type="image">` and `<button>` elements.

Using submit buttons
--------------------

`<input type="submit">` buttons are used to submit forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use `<input type="button">`, or better still, a `<button>` element.

If you choose to use `<button>` elements to create the buttons in your form, keep this in mind: If the `<button>` is inside a `<form>`, that button will be treated as the "submit" button. So you should be in the habit of expressly specifying which button is the submit button.

### A simple submit button

We'll begin by creating a form with a simple submit button:

```html
<form>
  <div>
    <label for="example">Let's submit some text</label>
    <input id="example" type="text" name="text" />
  </div>
  <div>
    <input type="submit" value="Send" />
  </div>
</form>
```

This renders like so:

Try entering some text into the text field, and then submitting the form.

Upon submitting, the data name/value pair gets sent to the server. In this instance, the string will be `text=usertext`, where "usertext" is the text entered by the user, encoded to preserve special characters. Where and how the data is submitted depends on the configuration of the `<form>`; see Sending form data for more details.

### Adding a keyboard shortcut to a submit button

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 submit 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). In order to avoid conflicts with the user agent's own keyboard shortcuts, different modifier keys are used for access keys than for other shortcuts on the host computer. See `accesskey` for further details.

Here's the previous example with the `s` access key added:

```html
<form>
  <div>
    <label for="example">Let's submit some text</label>
    <input id="example" type="text" name="text" />
  </div>
  <div>
    <input type="submit" value="Send" accesskey="s" />
  </div>
</form>
```

For example, in Firefox for Mac, pressing `Control`-`Option`-`S` triggers the Send button, while Chrome on Windows uses `Alt`+`S`.

The problem with the above example is that the user will not know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure 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 access keys are). Adding a tooltip to the button (using the `title` attribute) can also help, although it's not a complete solution for accessibility purposes.

### Disabling and enabling a submit button

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

```html
<input type="submit" value="Send" disabled />
```

You can enable and disable buttons at run time by setting `disabled` to `true` or `false`; in JavaScript this looks like `btn.disabled = true` or `btn.disabled = false`.

**Note:** See the `<input type="button">` page for more ideas about enabling and disabling buttons.

Validation
----------

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

Examples
--------

We've included simple examples above. There isn't really anything more to say about submit buttons. There's a reason this kind of control is sometimes called a "simple button."

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 # submit-button-state-(type=submit) |

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.
* Forms and buttons
* HTML forms
* The `<button>` element
* Compatibility of CSS properties


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

<input type="week">
===================

`<input>` elements of type **`week`** create input fields allowing easy entry of a year plus the ISO 8601 week number during that year (i.e., week 1 to 52 or 53).

Try it
------

The control's user interface varies from browser to browser; cross-browser support is currently a bit limited, with only Chrome/Opera and Microsoft Edge supporting it at this time. In non-supporting browsers, the control degrades gracefully to function identically to `<input type="text">`.

![An input reading 'week 01, 2017'. The background of the 2017 is the same blue as the focus ring. There are 3 icons in the input: x or clear, a spinner with small up and down arrows, and a larger down arrow. A calendar is a pop-up below the input set to January 2017. The first column of the calendar is the week: 52, 1, 2, 3, 4, 5. the full month calendar is to the right of that. The row with Week 1 and January 2 to 8 is highlighted. On the same line as the month, there are buttons to move right and left for the next and previous months.](/en-US/docs/Web/HTML/Element/input/week/week-control-chrome.png)

Value
-----

A string representing the value of the week/year entered into the input. The format of the date and time value used by this input type is described in Week strings.

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

```html
<label for="week">What week would you like to start?</label>
<input id="week" type="week" name="week" value="2017-W01" />
```

One thing to note is that the displayed format may differ from the actual `value`, which is always formatted `yyyy-Www`. When the above value is submitted to the server, for example, browsers may display it as `Week 01, 2017`, but the submitted value will always look like `week=2017-W01`.

You can also get and set the value in JavaScript using the input element's `value` property, for example:

```js
const weekControl = document.querySelector('input[type="week"]');
weekControl.value = "2017-W45";
```

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

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

### max

The latest (time-wise) year and week number, 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 week string, then the element has no maximum value.

This value must be greater than or equal to the year and week specified by the `min` attribute.

### min

The earliest year and week to accept. 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 week string, the input has no minimum value.

This value must be less than or equal to the value of 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 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.

For `week` inputs, the value of `step` is given in weeks, with a scaling factor of 604,800,000 (since the underlying numeric value is in milliseconds). The default value of `step` is 1, indicating 1week. The default stepping base is -259,200,000, which is the beginning of the first week of 1970 (`"1970-W01"`).

*At this time, it's unclear what a value of `"any"` means for `step` when used with `week` inputs. This will be updated as soon as that information is determined.*

Using week inputs
-----------------

Week inputs sound convenient at first glance, since they provide an easy UI for choosing weeks, and they normalize the data format sent to the server, regardless of the user's browser or locale. However, there are issues with `<input type="week">` because browser support is not guaranteed across all browsers.

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

### Basic uses of week

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

```html
<form>
  <label for="week">What week would you like to start?</label>
  <input id="week" type="week" name="week" />
</form>
```

### Controlling input size

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

### Using the step attribute

You should be able to use the `step` attribute to vary the number of weeks jumped whenever they are incremented or decremented, however it doesn't seem to have any effect on supporting browsers.

Validation
----------

By default, `<input type="week">` does not apply any validation to entered values. The UI implementations generally don't let you specify anything that isn't a valid week/year, which is helpful, but it's still possible to submit with the field empty, and you might want to restrict the range of choosable weeks.

### Setting maximum and minimum weeks

You can use the `min` and `max` attributes to restrict the valid weeks that can be chosen by the user. In the following example we are setting a minimum value of `Week 01, 2017` and a maximum value of `Week 52, 2017`:

```html
<form>
  <label for="week">What week would you like to start?</label>
  <input id="week" type="week" name="week" min="2017-W01" max="2017-W52" />
  <span class="validity"></span>
</form>
```

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

The result here is that only weeks between W01 and W52 in 2017 will be seen as valid and be selectable in supporting browsers.

### Making week values required

In addition you can use the `required` attribute to make filling in the week mandatory. As a result, supporting browsers will display an error if you try to submit an empty week field.

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

```html
<form>
  <div>
    <label for="week">What week would you like to start?</label>
    <input
 id="week"
 type="week"
 name="week"
 min="2017-W01"
 max="2017-W52"
 required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>
```

If you try to submit the form with no value, the browser displays an error. Try playing with the example now:

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

![The week form control has two dashes where the week number should be. A popup with a yellow warning symbol and a 'Please fill out this field' is emanating from the two dashes, which are highlighted in blue, the same blue as the input's focus ring.](/en-US/docs/Web/HTML/Element/input/week/week-validation-chrome.png)

**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 week inputs right now is browser support: Safari and Firefox don't support it on desktop, and old versions of IE don't support it.

Mobile platforms such as Android and iOS make perfect use of such input types, providing specialist UI controls that make it really easy to select values in a touchscreen environment. For example, the `week` picker on Chrome for Android looks like this:

![A modal popup. The header reads 'set week'. There are two columns: the left has 36 in the middle at full opacity, with 35 above it and 37 below being semi-opaque. On the right side, 2017 is fully opaque. There are no other options. Three text links or buttons on the bottom include 'clear' on the 'left' and 'cancel' and 'set' on the right.](/en-US/docs/Web/HTML/Element/input/week/week-chrome-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. As mentioned earlier, with a `week` input the actual value is always normalized to the format `yyyy-Www`. When the browser falls back to a generic text input, there's nothing to guide the user toward correctly formatting the input (and it's certainly not intuitive). There are multiple ways in which people could write week values; for example:

* `Week 1 2017`
* `Jan 2-8 2017`
* `2017-W01`
* etc.

The best way to deal with week/years in forms in a cross-browser way at the moment is to get the user to enter the week number and year in separate controls (`<select>` elements being popular; see below for an example), or use JavaScript libraries such as jQuery date picker.

Examples
--------

In this example we create two sets of UI elements for choosing weeks: a native picker created using `<input type="week">`, and a set of two `<select>` elements for choosing weeks/years in older browsers that don't support the `week` input type.

The HTML looks like so:

```html
<form>
  <div class="nativeWeekPicker">
    <label for="week">What week would you like to start?</label>
    <input
 id="week"
 type="week"
 name="week"
 min="2017-W01"
 max="2018-W52"
 required />
    <span class="validity"></span>
  </div>
  <p class="fallbackLabel">What week would you like to start?</p>
  <div class="fallbackWeekPicker">
    <div>
      <span>
        <label for="week">Week:</label>
        <select id="fallbackWeek" name="week"></select>
      </span>
      <span>
        <label for="year">Year:</label>
        <select id="year" name="year">
          <option value="2017" selected>2017</option>
          <option value="2018">2018</option>
        </select>
      </span>
    </div>
  </div>
</form>
```

The week values are dynamically generated by the JavaScript code below.
```

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 other part of the code that may be of interest is the feature detection code. To detect whether the browser supports `<input type="week">`, we create a new `<input>` element, try setting its `type` to `week`, then immediately check what its `type` is set to. Non-supporting browsers will return `text`, because the `week` type falls back to type `text`. If `<input type="week">` is not supported, we hide the native picker and show the fallback picker UI (`<select>`s) instead.

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

const yearSelect = document.querySelector("#year");
const weekSelect = document.querySelector("#fallbackWeek");

// 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 = "week";
} 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 weeks dynamically
  populateWeeks();
}

function populateWeeks() {
  // Populate the week select with 52 weeks
  for (let i = 1; i <= 52; i++) {
    const option = document.createElement("option");
    option.textContent = i < 10 ? `0${i}` : i;
    weekSelect.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 week and year, or
 empty
  |
| **Events** | `change` and
 `input` |
| **Supported common attributes** | `autocomplete`,
 `list`,
 `readonly`, and
 `step` |
| **IDL attributes** | `value`, `valueAsDate`,
 `valueAsNumber`, and `list`.
  |
| **DOM interface** | `HTMLInputElement` |
| **Methods** | `select()`,
 `stepDown()`,
 and `stepUp()` |
| **Implicit ARIA Role** | `no corresponding role` |

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

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

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
* `<input type="datetime-local">`, `<input type="date">`, `<input type="time">`, and `<input type="month">`
* Compatibility of CSS properties


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

<input type="reset">
====================

`<input>` elements of type **`reset`** are rendered as buttons, with a default `click` event handler that resets all inputs in the form to their initial values.

Try it
------

**Note:** You should usually avoid including reset buttons in your forms. They're rarely useful, and are instead more likely to frustrate users who click them by mistake (often while trying to click the submit button).

Value
-----

An `<input type="reset">` element's `value` attribute contains a string that is used as the button's label providing the button with an accessible description. Buttons such as `reset` don't have a value otherwise.

### Setting the value attribute

```html
<input type="reset" value="Reset the form" />
```

### Omitting the value attribute

If you don't specify a `value`, you get a button with the default label (typically "Reset," but this will vary depending on the user agent):

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

Using reset buttons
-------------------

`<input type="reset">` buttons are used to reset forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use `<input type="button">`, or better still, a `<button>` element.

### A simple reset button

We'll begin by creating a simple reset button:

```html
<form>
  <div>
    <label for="example">Type in some sample text</label>
    <input id="example" type="text" />
  </div>
  <div>
    <input type="reset" value="Reset the form" />
  </div>
</form>
```

This renders like so:

Try entering some text into the text field, and then pressing the reset button.

### Adding a reset keyboard shortcut

To add a keyboard shortcut to a reset button — just as you would with any `<input>` for which it makes sense — you use the `accesskey` global attribute.

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

```html
<form>
  <div>
    <label for="example">Type in some sample text</label>
    <input id="example" type="text" />
  </div>
  <div>
    <input type="reset" value="Reset the form" accesskey="r" />
  </div>
</form>
```

The problem with the above example is that there's no way for the user to know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure 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 access keys are). Adding a tooltip to the button (using the `title` attribute) can also help, although it's not a complete solution for accessibility purposes.

### Disabling and enabling a reset button

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

```html
<input type="reset" value="Disabled" disabled />
```

You can enable and disable buttons at run time by setting `disabled` to `true` or `false`; in JavaScript this looks like `btn.disabled = true` or `btn.disabled = false`.

**Note:** See the `<input type="button">` page for more ideas about enabling and disabling buttons.

Validation
----------

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

Examples
--------

We've included simple examples above. There isn't really anything more to say about reset buttons.

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 # reset-button-state-(type=reset) |

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.
* Forms and buttons
* HTML forms
* The `<button>` element
* Compatibility of CSS properties


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

<input type="url">
==================

`<input>` elements of type **`url`** are used to let the user enter and edit a URL.

Try it
------

The input value is automatically validated to ensure that it's either empty or a properly-formatted URL 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 URL or not.

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

Value
-----

The `<input>` element's `value` attribute contains a string which is automatically validated as conforming to URL syntax. More specifically, there are two 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 absolute URL. This doesn't necessarily mean the URL address exists, but it is at least formatted correctly. In simple terms, this means `urlscheme://restofurl`.

See Validation for details on how URLs 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, `url` 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 `url` input. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `url` 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 `url` 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 `url` 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 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.

### 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 URL inputs
----------------

When you create a URL input with the proper `type` value, `url`, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mistypes their website's address, or provides an invalid one.

It's important, however, to note that this is not enough to ensure that the specified text is a URL 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 a URL.

**Note:** 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 URL on the server-side of any transaction in which the provided text may have any security implications of any kind.

### A simple URL input

Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. In its most basic form, a URL input can be implemented like this:

```html
<input id="myURL" name="myURL" type="url" />
```

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

There is nothing magical going on here. Submitting this form would cause the following data to be sent to the server: `myURL=http%3A%2F%2Fwww.example.com`. Note how characters are escaped as necessary.

### 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 a `url` input with the placeholder `http://www.example.com`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

```html
<input
 id="myURL"
 name="myURL"
 type="url"
 placeholder="http://www.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, for instance, the `url` edit box is 30 characters wide:

```html
<input id="myURL" name="myURL" type="url" size="30" />
```

#### Element value length

The `size` is separate from the length limitation on the entered URL itself. You can specify a minimum length, in characters, for the entered URL using the `minlength` attribute; similarly, use `maxlength` to set the maximum length of the entered URL. If `maxLength` exceeds `size`, the input box's contents will scroll as needed to show the current selection or insertion point as the content is manipulated.

The example below creates a 30-character wide URL address entry box, requiring that the contents be no shorter than 10 characters and no longer than 80 characters.

```html
<input
 id="myURL"
 name="myURL"
 type="url"
 size="30"
 minlength="10"
 maxlength="80" />
```

**Note:** These attributes also affect validation; a value shorter or longer than the specified minimum/maximum lengths will be classified as invalid; in addition most browsers will refuse to let the user enter a value longer than the specified maximum length.

### Providing default options

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

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

```html
<input id="myURL" name="myURL" type="url" value="http://www.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 URLs 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 URL entry box.

```html
<input id="myURL" name="myURL" type="url" list="defaultURLs" />

<datalist id="defaultURLs">
  <option value="https://developer.mozilla.org/"></option>
  <option value="http://www.google.com/"></option>
  <option value="http://www.microsoft.com/"></option>
  <option value="https://www.mozilla.org/"></option>
  <option value="http://w3.org/"></option>
</datalist>
```

With the `<datalist>` element and its `<option>`s in place, the browser will offer the specified values as potential values for the URL; 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 URLs. Then, as the user types, the list is adjusted to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

#### Using labels for suggested values

You can opt to include the `label` attribute on one or all of your `<option>` elements to provide textual labels. Some browsers may display only the labels, while others may display both the label and the URL.

```html
<input id="myURL" name="myURL" type="url" list="defaultURLs" />

<datalist id="defaultURLs">
  <option value="https://developer.mozilla.org/" label="MDN Web Docs"></option>
  <option value="http://www.google.com/" label="Google"></option>
  <option value="http://www.microsoft.com/" label="Microsoft"></option>
  <option value="https://www.mozilla.org/" label="Mozilla"></option>
  <option value="http://w3.org/" label="W3C"></option>
</datalist>
```

Validation
----------

There are two levels of content validation available for `url` 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 URL. 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 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.

### Basic validation

Browsers that support the `url` input type automatically provide validation to ensure that only text that matches the standard format for URLs is entered into the input box.

The syntax of a URL is fairly intricate. It's defined by WHATWG's URL Living Standard and is described for newcomers in our article What is a URL?

### Making a URL required

As mentioned earlier, to make a URL entry required before the form can be submitted (you can't leave the field blank), you just need to include the `required` attribute on the input.

```html
<form>
  <input id="myURL" name="myURL" type="url" required />
  <button>Submit</button>
</form>
```

Try submitting the above form with no value entered to see what happens.

### Pattern validation

If you need the entered URL to be restricted further than just "any string that looks like a URL," you can use the `pattern` attribute to specify a regular expression the value must match for the value to be valid.

For example, let's say you're building a support page for employees of Myco, Inc. which will let them contact their IT department for help if one of their pages has a problem. In our simplified form, the user needs to enter the URL of the page that has a problem, and a message describing what is wrong. But we want the URL to only successfully validate if the entered URL is in a Myco domain.

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

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

```html
<form>
  <div>
    <label for="myURL">Enter the problem website address:</label>
    <input
 id="myURL"
 name="myURL"
 type="url"
 required
 pattern=".\*\.myco\..\*"
 title="The URL must be in a Myco domain" />
    <span class="validity"></span>
  </div>
  <div>
    <label for="myComment">What is the problem?</label>
    <input id="myComment" name="myComment" type="text" required />
    <span class="validity"></span>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

First of all, the `required` attribute is specified, making it mandatory that a valid URL be provided.

Second, in the `url` input we set `pattern` to `".*\.myco\..*"`. This simple regular expression requests a string that has any number of characters, followed by a dot, followed by "myco", followed by a dot, followed by any number of characters. And because the browser runs both the standard URL filter *and* our custom pattern against the specified text, we wind up with a validation which says "make sure this is a valid URL, and also in a Myco domain."

This isn't perfect, but it is good enough for this simple demo's requirements.

It's advisable to use the `title` attribute along with `pattern`. If you do, the `title` *must* describe the pattern; 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 "URL", the result would be the message "The entered text doesn't match the required pattern. URL", which is not a good user experience.

That's why, instead, we specify the string "The URL must be in a myco domain". By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. The URL should be in a myco domain."

**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
--------

There's not much else to say about `url` type inputs; check the Pattern validation and Using URL inputs sections for numerous examples.

You can also find our pattern validation example on GitHub (see it running live also).

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

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

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

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

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="email">`
* Compatibility of CSS properties