Инпут (богиня)

Attributes

This element can have any of the global attributes in addition to the following:


This Boolean attribute indicates that the user cannot interact with the button. If this attribute is not specified, the button inherits its setting from the containing element, for example ; if there is no containing element with the attribute set, then the button is enabled. The disabled control’s value isn’t submitted with the form and the  event on disabled controls.

Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a across page loads. Use the attribute to control this feature.

HTML5
This Boolean attribute lets you specify that the button should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified.
The use of this attribute on a is nonstandard and Firefox-specific. By default, unlike other browsers, Firefox persists the dynamic disabled state of a across page loads. Setting the value of this attribute to (i.e., ) disables this feature.
HTML5
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendent of a form element. This attribute enables you to place elements anywhere within a document, not just as descendents of their elements.
Since the input element is a submit button, the attribute specifies the type of content that is used to submit the form to the server. Possible values are:
  • : The default value if the attribute is not specified.
  • : This value is used if an element is used with the attribute set to .

If this attribute is specified, it overrides the attribute of the element’s form owner.

HTML5
The URI of a program that processes the information submitted by the button. If specified, it overrides the attribute of the button’s form owner.
Since the input element is a submit button, the attribute specifies the HTTP method that the browser uses to submit the form. Possible values are:
  • : The data from the form is included in the body of the form and is sent to the server.
  • : The data from the form is appended to the form attribute URI, with a ‘?’ as a separator, and the resulting URI is sent to the server. Use this method when the form has no side-effects and contains only ASCII characters.

If specified, this attribute overrides the attribute of the element’s form owner.

Since the input element is a submit button, the attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the attribute of the element’s form owner. This is a Boolean attribute.
Since the input element is a submit button, the attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the attribute of the element’s form owner. The following keywords have special meanings:
  • _: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • : Load the response into a new unnamed browsing context.
  • : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as .
  • : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as .
The name of the button, which is submitted with the form data.
The type of the button. Possible values are:
  • : The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
  • : The button resets all the controls to their initial values.
  • : The button has no default behavior. It can have client-side scripts associated with the element’s events, which are triggered when the events occur.
The initial value of the button.

Сумісність з оглядачами

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 20 Edge Full support 12 Firefox Full support 57 IE No support No Opera Full support 11 Safari No support No Notes WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 57 Opera Android Full support 11 Safari iOS Full support 5 Samsung Internet Android Full support Yes

Notes

File inputs

  1. Starting in Gecko 2.0, calling the method on an element of type opens the file picker and lets the user select files. See Using files from web applications for an example and more details.

  2. You cannot set the value of a file picker from a script — doing something like the following has no effect:

    var e = getElementById("someFileInputElement");
    e.value = "foo";
    
  3. When a file is chosen using an , the real path to the source file is not shown in the input’s attribute for obvious security reasons. Instead, the filename is shown, with appended to the beginning of it. There are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is .

Error messages

If you want Firefox to present a custom error message when a field fails to validate, you can use the attribute to do so:

<input type="email"
 x-moz-errormessage="Please specify a valid email address.">

Note, however, that this is not standard and will not have an effect on other browsers.

Localization

The allowed inputs for certain <input> types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.


Firefox uses the following heuristics to determine the locale to validate the user’s input (at least for ):

  • Try the language specified by a / attribute on the element or any of its parents.
  • Try the language specified by any Content-Language HTTP header or
  • If none specified, use the browser’s locale.

Using mozactionhint on Firefox mobile

You can use the attribute to specify the text for the label of the enter key on the virtual keyboard when your form is rendered on Firefox mobile. For example, to have a «Next» label, you can do this:

<input type="text" mozactionhint="next">

The result is:

Browser compatibility

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 20 Edge Full support 12 Firefox Full support 57 IE No support No Opera Full support 10 Safari No support No Notes WebView Android Full support Yes Chrome Android Full support 25 Firefox Android Full support 57 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support 1.5

Value

A containing the value of the time entered into the input. You can set a default value for the input by including a valid time in the attribute when creating the element, like so:

<label for="appt-time">Choose an appointment time: </label>
<input id="appt-time" type="time" name="appt-time" value="13:30">
var timeControl = document.querySelector('input');
timeControl.value = '15:30';

Time value format

The of the input is always in 24-hour format: , 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 ), the format is always . You can learn more about the format of the time value used by this input type in in Date and time formats used in HTML.

在此示例中,您可以通过输入时间并查看之后如何更改来查看时间输入的值。

首先,看一下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 event, which is triggered every time the contents of an input element change. When this happens, the contents of the are replaced with the new value of the input element.

var startTime = document.getElementById("startTime");
var valueSpan = document.getElementById("value");

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

When a form including a 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 , or if seconds are included (see ).

Handling browser support

As mentioned above, Safari and a few other, less common, browsers don’t yet 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 picker on Chrome for Android looks like this:


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, inputs’ values are always normalized to the format or . 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 multiple ways in which people write times, such as:

  • etc.

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

<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="{2}:{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 , where 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 {
  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 ( elements are popular; see below for an example), or use JavaScript libraries such as the jQuery timepicker plugin.

Валідація

За замовчуванням,  не додає жодної валідації на введення значення. UI реалізація загалом не дозволяє уведення будь чого що не є датою — що є добре — але ви всеодно можете лишати поле пустим чи (в оглядачах де інпут відображається простим типом ) ввести неправильну дату (наприклад 32ге Квітня).

Якщо ви використовуєте і для обмеження введення дат (дивіться ), підтримуючі оглядачі відобразять помилку якщо ви спробуєте відправити дату поза меж вказаних в атрибутах. Однак, перевірте результат щоб запевнитись що значення всередені цих дат, тому що вони можуть не підтримуватись пристрієм користувача.

В додаток, ви можете використовувати  атрибут щоб зробити заповнення дати обьв’язковим — знову ж, буде відображена помилка якщо користувач захоче відправити пусте поле. Принаймні, це буде працювати у більшості оглядачів.

Давайте розглянемо приклад — ми встановили мінімальну і максимальну дату, і також зробили його обов’язковим:

<form>
  <div>
    <label for="party">Choose your preferred party date (required, April 1st to 20th):</label>
    <input type="date" id="party" name="party" min="2017-04-01" max="2017-04-20" required>
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit">
  </div>
</form>

Якщо ви спробуєте відправити форму з незаповненою датою(або з датою поза межами), оглядач відобразить помилку. Спробуйте це самі зробити для перевірки:


Це скріншот приклади оглядача без підтримки віджету дати:

div {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}

label {
  display: inline-block;
  width: 300px;
}

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

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

Важливо: HTML валідація форми не замінює скрипти які перевіряють чи буле введена інформація у коректному форматі. Це достатньо простий метод щоб додати корекцію до HTML, їх можливо обійти , чи видалити зовсім. Якщо ваша серверна сторона не перевірить відправлені данні, це може бути катастрофа (данні можуть бути дуже великого розміру, або неправильного типу, вам можуть завантажити скрипт взлому і так далі).

运用文本输入框

基础例子

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

如下所示:

提交后,发送到服务器的键值对数据将为 (如果在提交之前输入了 «Chris» 作为输入值). 您必须记住在  元素上包含  属性,否则文本字段的值将不包含在提交的数据中。

设置占位符

您可以在文本输入中提供一个有用的占位符,通过使用 属性,可以提示输入内容。 看下面的例子

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

您可以在下面看到占位符的呈现方式:

占位符通常以比元素的前景色更浅的颜色呈现,并且在用户开始向字段中输入文本时(或者每当字段通过设置其属性以编程方式设置的值时)就自动消失。

输入框元素大小

可以使用 属性来控制输入框的尺寸。 使用它,您可以指定文本输入一次可以显示的字符数。 这会影响元素的宽度,使您可以按字符而不是像素指定宽度。 例如,在此示例中,输入为30个字符宽:

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

HTML Tutorial

HTML HOMEHTML IntroductionHTML EditorsHTML BasicHTML ElementsHTML AttributesHTML HeadingsHTML ParagraphsHTML StylesHTML FormattingHTML QuotationsHTML CommentsHTML Colors Colors RGB HEX HSL

HTML CSSHTML Links Links Link Colors Link Bookmarks

HTML Images Images Image Map Background Images The Picture Element

HTML TablesHTML Lists Lists Unordered Lists Ordered Lists Other Lists

HTML Block & InlineHTML ClassesHTML IdHTML IframesHTML JavaScriptHTML File PathsHTML HeadHTML LayoutHTML ResponsiveHTML ComputercodeHTML SemanticsHTML Style GuideHTML EntitiesHTML SymbolsHTML EmojisHTML CharsetHTML URL EncodeHTML vs. XHTML

浏览器支持

此页面上的兼容性表是根据结构化数据生成的。 如果您想贡献数据,请查看 https://github.com/mdn/browser-compat-data 并向我们发送拉取请求。

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support Yes Opera Full support Yes Safari Full support 1 WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes

Browser compatibility

The compatibility table in this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Chrome Full support 20 Edge Full support 12 Firefox No support No Notes IE No support No Opera Full support 11 Safari No support No Notes WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support Yes Opera Android Full support 11 Safari iOS Full support Yes Samsung Internet Android Full support Yes

С этим читают