From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- files/ru/web/html/element/input/button/index.html | 345 ++++++++++++ files/ru/web/html/element/input/color/index.html | 221 ++++++++ files/ru/web/html/element/input/date/index.html | 510 +++++++++++++++++ .../html/element/input/datetime-local/index.html | 586 ++++++++++++++++++++ .../ru/web/html/element/input/datetime/index.html | 29 + files/ru/web/html/element/input/file/index.html | 439 +++++++++++++++ files/ru/web/html/element/input/image/index.html | 205 +++++++ files/ru/web/html/element/input/index.html | 311 +++++++++++ files/ru/web/html/element/input/number/index.html | 420 ++++++++++++++ .../ru/web/html/element/input/password/index.html | 614 +++++++++++++++++++++ files/ru/web/html/element/input/radio/index.html | 377 +++++++++++++ files/ru/web/html/element/input/range/index.html | 480 ++++++++++++++++ files/ru/web/html/element/input/search/index.html | 467 ++++++++++++++++ files/ru/web/html/element/input/tel/index.html | 523 ++++++++++++++++++ 14 files changed, 5527 insertions(+) create mode 100644 files/ru/web/html/element/input/button/index.html create mode 100644 files/ru/web/html/element/input/color/index.html create mode 100644 files/ru/web/html/element/input/date/index.html create mode 100644 files/ru/web/html/element/input/datetime-local/index.html create mode 100644 files/ru/web/html/element/input/datetime/index.html create mode 100644 files/ru/web/html/element/input/file/index.html create mode 100644 files/ru/web/html/element/input/image/index.html create mode 100644 files/ru/web/html/element/input/index.html create mode 100644 files/ru/web/html/element/input/number/index.html create mode 100644 files/ru/web/html/element/input/password/index.html create mode 100644 files/ru/web/html/element/input/radio/index.html create mode 100644 files/ru/web/html/element/input/range/index.html create mode 100644 files/ru/web/html/element/input/search/index.html create mode 100644 files/ru/web/html/element/input/tel/index.html (limited to 'files/ru/web/html/element/input') diff --git a/files/ru/web/html/element/input/button/index.html b/files/ru/web/html/element/input/button/index.html new file mode 100644 index 0000000000..984fa13988 --- /dev/null +++ b/files/ru/web/html/element/input/button/index.html @@ -0,0 +1,345 @@ +--- +title: +slug: Web/HTML/Element/Input/button +tags: + - HTML формы + - Формы + - Элемент Input +translation_of: Web/HTML/Element/input/button +--- +
{{HTMLRef}}
+ +

Элемент {{HTMLElement("input")}} с типом button отображаются как простые кнопки, которые можно запрограммировать для управления пользовательскими функциями в любом месте веб-страницы, например, назначить функцию обработки события (обычно для события {{event("click")}}).

+ +
{{EmbedInteractiveExample("pages/tabbed/input-button.html", "tabbed-shorter")}}
+ + + +
+

Заметка: Хотя элементы <input> с типом button по-прежнему являются абсолютно корректными в HTML, новый элемент {{HTMLElement("button")}} теперь является предпочтительным способом создания кнопок. Учитывая, что текст элемента {{HTMLElement("button")}} вставлен между открывающим и закрывающим тегами, вы можете включить в тег HTML, даже изображения.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Значение")}}{{domxref("DOMString")}} используется в качестве метки кнопки
Событие{{event("click")}}
Поддерживаемые общие атрибуты{{htmlattrxref("type", "input")}} и {{htmlattrxref("value", "input")}}
Атрибуты IDLvalue
МетодыNone
+ +

Значение

+ +

Атрибут значения элементов <input type="button"> elements' {{htmlattrxref("value", "input")}} содержит строку {{domxref("DOMString")}} , которая используется в качестве метки кнопки.

+ +
+
<input type="button" value="Нажми на меня">
+
+ +

{{EmbedLiveSample("summary-example3", 650, 30)}}

+ +

Если вы не укажете value, вы получите пустую кнопку:

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

{{EmbedLiveSample("summary-example1", 650, 30)}}

+ +

Использование кнопок

+ +

Элементы <input type="button"> не имеют поведения по умолчанию (их двоюродные братья, <input type="submit"> и <input type="reset"> используются для отправки и сброса форм соответственно). Чтобы кнопки делали что-либо, вы должны написать код JavaScript для выполнения работы.

+ +

Простая кнопка

+ +

Мы начнем с создания простой кнопки с обработчиком события {{event("click")}} , который запускает наш компьютер (ну, он переключает value кнопки и текстовое содержимое следующего абзаца):

+ +
<form>
+  <input type="button" value="Запустить ПК">
+</form>
+<p>ПК выключен.</p>
+ +
const button = document.querySelector('input');
+const paragraph = document.querySelector('p');
+
+button.addEventListener('click', updateButton);
+
+function updateButton() {
+  if (button.value === 'Запустить ПК') {
+    button.value = 'Выключить ПК';
+    paragraph.textContent = 'ПК запущен!';
+  } else {
+    button.value = 'Запустить ПК';
+    paragraph.textContent = 'ПК выключен.';
+  }
+}
+ +

Сценарий получает ссылку на объект {{domxref("HTMLInputElement")}}, представляющий <input> в DOM, сохраняя этот параметр в переменной button. Затем {{domxref("EventTarget.addEventListener", "addEventListener()")}} используется для установки функции, которая будет запускаться, когда на кнопке происходят события {{event("click")}}.

+ +

{{EmbedLiveSample("Простая_кнопка", 650, 100)}}

+ +

Добавление сочетаний клавиш на кнопки

+ +

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

+ +

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

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

{{EmbedLiveSample("Adding_keyboard_shortcuts_to_buttons", 650, 100)}}

+ +
+

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

+
+ +

Disabling and enabling a button

+ +

To disable a button, simply specify the {{htmlattrxref("disabled")}} global attribute on it, like so:

+ +
+
<input type="button" value="Disable me" disabled>
+
+ +

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

+ + + +

{{EmbedLiveSample("Hidden_code_1", 650, 60)}}

+ +

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

+ +

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

+ + + +

{{EmbedLiveSample("Hidden_code_2", 650, 60)}}

+ +
+

Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a {{HTMLElement("button")}} across page loads. Use the {{htmlattrxref("autocomplete","button")}} attribute to control this feature.

+
+ +

Validation

+ +

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

+ +

Examples

+ +

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

+ +
<div class="toolbar">
+  <input type="color" aria-label="select pen color">
+  <input type="range" min="2" max="50" value="30" aria-label="select pen size"><span class="output">30</span>
+  <input type="button" value="Clear canvas">
+</div>
+
+<canvas class="myCanvas">
+  <p>Add suitable fallback here.</p>
+</canvas>
+ + + +
var canvas = document.querySelector('.myCanvas');
+var width = canvas.width = window.innerWidth;
+var height = canvas.height = window.innerHeight-85;
+var ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'rgb(0,0,0)';
+ctx.fillRect(0,0,width,height);
+
+var colorPicker = document.querySelector('input[type="color"]');
+var sizePicker = document.querySelector('input[type="range"]');
+var output = document.querySelector('.output');
+var clearBtn = document.querySelector('input[type="button"]');
+
+// covert degrees to radians
+function degToRad(degrees) {
+  return degrees * Math.PI / 180;
+};
+
+// update sizepicker output value
+
+sizePicker.oninput = function() {
+  output.textContent = sizePicker.value;
+}
+
+// store mouse pointer coordinates, and whether the button is pressed
+var curX;
+var curY;
+var pressed = false;
+
+// update mouse pointer coordinates
+document.onmousemove = function(e) {
+  curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
+  curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
+}
+
+canvas.onmousedown = function() {
+  pressed = true;
+};
+
+canvas.onmouseup = function() {
+  pressed = false;
+}
+
+clearBtn.onclick = function() {
+  ctx.fillStyle = 'rgb(0,0,0)';
+  ctx.fillRect(0,0,width,height);
+}
+
+function draw() {
+  if(pressed) {
+    ctx.fillStyle = colorPicker.value;
+    ctx.beginPath();
+    ctx.arc(curX, curY-85, sizePicker.value, degToRad(0), degToRad(360), false);
+    ctx.fill();
+  }
+
+  requestAnimationFrame(draw);
+}
+
+draw();
+ +

{{EmbedLiveSample("Examples", '100%', 600)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{SpecName('HTML WHATWG', 'forms.html#button-state-(type=button)', '<input type="button">')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#button-state-(type=button)', '<input type="button">')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.input.input-button")}}

+ +

See also

+ + diff --git a/files/ru/web/html/element/input/color/index.html b/files/ru/web/html/element/input/color/index.html new file mode 100644 index 0000000000..0dcdf05619 --- /dev/null +++ b/files/ru/web/html/element/input/color/index.html @@ -0,0 +1,221 @@ +--- +title: +slug: Web/HTML/Element/Input/color +tags: + - Color Picker + - Element + - Form input + - Forms + - HTML + - HTML forms + - HTML input + - Input + - Reference + - color +translation_of: Web/HTML/Element/input/color +--- +
{{HTMLRef}}
+ +

{{HTMLElement("input")}} элементы типа color предоставляют элемент пользовательского интерфейса, который позволяет пользователю указать цвет либо с помощью визуального интерфейса выбора цвета, либо путем ввода цвета в текстовое поле в шестнадцатеричном формате #rrggbb. Разрешены только простые цвета (без альфа-канала), хотя CSS colors имеет больше форматов, например названия цветов, функциональные обозначения и шестнадцатеричный формат с альфа-каналом.

+ +

Представление элемента может существенно отличаться от одного браузера и/или платформы к другой — это может быть простой текстовый ввод, который автоматически проверяет правильность ввода информации о цвете в соответствующем формате, или стандартный для платформы выбор цвета, или какое-то пользовательское окно выбора цвета.

+ +
{{EmbedInteractiveExample("pages/tabbed/input-color.html", "tabbed-standard")}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}7-значная {{domxref("DOMString")}} , указывающая {{cssxref("<color>")}} в строчной шестнадцатеричной системе счисления
События{{domxref("HTMLElement/change_event", "change")}} и {{domxref("HTMLElement/input_event", "input")}}
Поддерживаемые общие атрибуты{{htmlattrxref("autocomplete", "input")}} и {{htmlattrxref("list", "input")}}
IDL атрибутыlist и value
Методы{{domxref("HTMLInputElement.select", "select()")}}
+ +

Value

+ +

{{Htmlattrxref ("value","input")}} элемента {{HTMLElement ("input")}} типа color всегда является {{domxref ("DOMString")}}, который содержит 7-символьную строку, задающую цвет RGB в шестнадцатеричном формате. Хотя вы можете ввести цвет в верхнем или нижнем регистре, он будет сохранен в виде нижнего регистра. Value никогда не бывает в какой-либо другой форме и никогда не бывает пустым.

+ +
+

Примечание: установка значения на всё, что не является допустимым, полностью непрозрачным цветом RGB в шестнадцатеричной системе счисления, приведет к тому, что значение будет установлено на #000000. В частности, вы не можете использовать стандартные имена цветов CSS или любой синтаксис функций CSS для установки значения. Это имеет смысл, если иметь в виду, что HTML и CSS-это отдельные языки и спецификации. Кроме того, цвета с альфа-каналом не поддерживаются; указание цвета в 9-символьной шестнадцатеричной системе счисления (например, #009900aa) также приведет к тому, что цвет будет установлен на #000000.

+
+ +

Использование настроек цвета

+ +

Входные данные типа color просты из-за ограниченного числа атрибутов, которые они поддерживают.

+ +

Предоставление цвета по умолчанию

+ +

Вы можете обновить простой пример выше, чтобы установить значение по умолчанию, так что цветовая заливка будет предварительно заполнена цветом по умолчанию, и палитра цветов (если таковая имеется) также будет по умолчанию использовать этот цвет:

+ +
<input type="color" value="#ff0000">
+ +

{{EmbedLiveSample("Providing_a_default_color", 700, 30)}}

+ +

Если вы не зададите значение, то по умолчанию будет #000000, то есть черный цвет. Значение должно быть в семизначной шестнадцатеричной системе счисления, то есть символ"#", за которым следуют две цифры, каждая из которых представляет красный, зеленый и синий цвета, например: #rrggbb. Если у вас есть цвета в любом другом формате (например, имена цветов CSS или цветовые функции CSS, такие как rgb () или rgba ()), вам придется преобразовать их в шестнадцатеричные перед установкой значения.

+ +

Отслеживание изменений цвета

+ +

Как и в случае с другими типами {{HTMLElement("input")}}, есть два события, которые могут быть использованы для обнаружения изменения цвета значения: {{domxref("HTMLElement/input_event", "input")}} и {{domxref("HTMLElement/change_event", "change")}}. input запускается на элементе <input> каждый раз, когда меняется цвет. change событие запускается, когда пользователь отклоняет средство выбора цвета. В обоих случаях вы можете определить новое значение элемента, посмотрев на его {{domxref("HTMLInputElement.value", "value")}}.

+ +

Вот пример, который наблюдает за изменениями со временем значения цвета:

+ +
colorPicker.addEventListener("input", updateFirst, false);
+colorPicker.addEventListener("change", watchColorPicker, false);
+
+function watchColorPicker(event) {
+  document.querySelectorAll("p").forEach(function(p) {
+    p.style.color = event.target.value;
+  });
+}
+
+ +

Выбор значения

+ +

Если реализация элемента {{HTMLElement("input")}} типа color в браузере пользователя не поддерживается правильно, а вместо этого является текстовым полем для непосредственного ввода строки цвета, вы можете использовать {{domxref("HTMLInputElement.select", " select ()")}} метод выбора текста, находящегося в данный момент в поле редактирования. Если браузер вместо этого верно использует color, select () ничего не делает. Вы должны знать об этом, чтобы ваш код мог адекватно реагировать в любом случае.

+ +
colorWell.select();
+ +

Вариации внешнего вида

+ +

Как уже упоминалось ранее, когда браузер не поддерживает интерфейс выбора цвета, его реализация цветовых входов будет представлять собой текстовое поле, которое автоматически проверяет содержимое, чтобы убедиться, что значение находится в правильном формате. Например, в Safari 10.1 вы увидите что-то похожее на это:Screenshot of the example taken in Safari.

+ +

То же самое можно увидеть и в Firefox 55:Screenshot of the example taken in Firefox 55 for macOS

+ +

В этом случае при нажатии на цветовой колодец отображается палитра цветов платформы, из которой вы можете выбрать нужный цвет (в данном случае это палитра macOS):

+ +

Screenshot of the element with the color picker open in Firefox Mac.

+ +

Validation

+ +

Значение цветового ввода считается недопустимым, если {{Glossary("user agent")}} не может преобразовать пользовательский ввод в семизначную строчную шестнадцатеричную нотацию. В этом случае к элементу применяется псевдокласс {{cssxref(":invalid")}}.

+ +

Пример

+ +

Давайте создадим пример, который делает немного больше с цветом входного сигнала путем отслеживания {{domxref("HTMLElement/change_event", "change")}} и {{domxref("HTMLElement/input_event", "input")}} событий, чтобы взять новый цвет и применить его к каждому {{HTMLElement("Р")}} элемента в документе.

+ +

HTML

+ +

HTML довольно прост — пара абзацев описательного материала с {{HTMLElement ("input")}} типа color с идентификатором colorWell, который мы будем использовать для изменения цвета текста абзацев.

+ +
<p>An example demonstrating the use of the <code>&lt;input type="color"&gt;</code>
+   control.</p>
+
+<label for="colorWell">Color:</label>
+<input type="color" value="#ff0000" id="colorWell">
+
+<p>Watch the paragraph colors change when you adjust the color picker.
+   As you make changes in the color picker, the first paragraph's
+   color changes, as a preview (this uses the <code>input</code>
+   event). When you close the color picker, the <code>change</code>
+   event fires, and we detect that to change every paragraph to
+   the selected color.</p>
+ +

JavaScript

+ +

Во-первых, есть некоторые настройки. Здесь мы объявляем некоторые переменные. Объявляя переменную, содержащую цвет, который мы установим, когда загрузим страницу, а затем устанавливаем обработчик {{domxref("Window/load_event", "load")}} для выполнения основной работы запуска, как только страница будет полностью загружена.

+ +
var colorWell;
+var defaultColor = "#0000ff";
+
+window.addEventListener("load", startup, false);
+
+ +

Инициализация

+ +

Как только страница загружена, вызывается наш обработчик событий загрузки startup():

+ +
function startup() {
+  colorWell = document.querySelector("#colorWell");
+  colorWell.value = defaultColor;
+  colorWell.addEventListener("input", updateFirst, false);
+  colorWell.addEventListener("change", updateAll, false);
+  colorWell.select();
+}
+
+ +

Это возвращает ссылку на элемент color <input> в переменной colorWell, а затем устанавливает значение входного цвета в значение defaultColor. То цвет входное {{domxref("HTMLElement/input_event", "input")}} событие настроено, чтобы вызвать updateFirst() функцию и {{domxref("HTMLElement/change_event", "change")}} событие, вызывается updateAll(). Они оба видны ниже.

+ +

Наконец, мы вызываем {{domxref ("HTMLInputElement.select", " select ()")}} для выбора текстового содержимого цветового ввода, если элемент управления реализован в виде текстового поля (это не имеет никакого эффекта, если вместо него предусмотрен интерфейс выбора цвета).

+ +

Реакция на изменение цвета

+ +

Мы предоставляем две функции, которые имеют дело с изменением цвета. Функция updateFirst() вызывается в ответ на input событие. Он изменяет цвет первого элемента абзаца в документе, чтобы соответствовать новому значению входного цвета. Поскольку input события запускаются каждый раз, когда производится корректировка значения (например, если яркость цвета увеличивается), они будут происходить повторно при использовании средства выбора цвета.

+ +
function updateFirst(event) {
+  var p = document.querySelector("p");
+
+  if (p) {
+    p.style.color = event.target.value;
+  }
+}
+ +

Когда средство выбора цвета закрывается, указывая, что значение больше не будет меняться (если пользователь повторно не откроет средство выбора цвета), в элемент отправляется событие change. Мы обрабатываем это событие с помощью функции updateAll(), используя {{domxref("HTMLInputElement.value", "Event.target.value")}} для получения окончательного выбранного цвета:

+ +
function updateAll(event) {
+  document.querySelectorAll("p").forEach(function(p) {
+    p.style.color = event.target.value;
+  });
+}
+
+ +

Это устанавливает цвет каждого элемента {{HTMLElement("p")}} таким образом, чтобы его атрибут {{cssxref("color")}} соответствовал текущему значению входного цвета, на которое ссылаются с помощью {{domxref("Event.target", "event.target")}}.

+ +

Результат

+ +

Финальный результат выглядит так:

+ +

{{EmbedLiveSample("Example", 700, 200)}}

+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + +
СпецификацияСтатусКомментарий
{{SpecName('HTML WHATWG', '#color-state-(type=color)')}}{{Spec2('HTML WHATWG')}}Первоначальное определение
{{SpecName('HTML5 W3C', 'forms.html#the-input-element')}}{{Spec2('HTML5 W3C')}}Первоначальное определение
+ +

Браузерная совместимость

+ + + +

{{Compat("html.elements.input.input-color")}}

+ +

Изучите также

+ + diff --git a/files/ru/web/html/element/input/date/index.html b/files/ru/web/html/element/input/date/index.html new file mode 100644 index 0000000000..5fb53a1437 --- /dev/null +++ b/files/ru/web/html/element/input/date/index.html @@ -0,0 +1,510 @@ +--- +title: +slug: Web/HTML/Element/Input/date +translation_of: Web/HTML/Element/input/date +--- +
{{HTMLRef}}
+ +

Элементы {{htmlelement("input")}} типа date создают поля ввода и позволяют пользователю ввести дату, либо использовать text box для автоматической проверки контента или использовать специальный интерфейс date picker. Возвращаемое значение включает год, месяц, день, но не время. Используйте поля ввода {{HTMLElement("input/time", "time")}} или {{HTMLElement("input/datetime-local", "datetime-local")}}, чтобы вводить время или дату+время соответственно.

+ +

Отображение date различается в зависимости от браузера, кроме того не все браузеры поддерживают date. Подробнее см. {{anch("Browser compatibility")}}. В неподдерживаемых браузерах элемент будет отображаться как обычный <input type="text">.

+ +
{{EmbedInteractiveExample("pages/tabbed/input-date.html", "tabbed-standard")}}
+ + + +

Среди браузеров со своим интерфейсом для выбора даты, есть интерфейс браузеров Chrome и Opera, который выглядит так:

+ +

+ +

В Edge он выглядит так:

+ +

+ +

А в Firefox выглядит так:

+ +

Datepicker UI in firefox

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}Возвращает {{domxref("DOMString")}}, с датой в формате гггг-мм-дд, или пустую строку
События{{event("change")}} и {{event("input")}}
Поддерживаемые атрибуты{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("readonly", "input")}}, and {{htmlattrxref("step", "input")}}
IDL attributeslist, value, valueAsDate, valueAsNumber.
Методы{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}
+ +

Значение

+ +

Возвращает {{domxref("DOMString")}}, представляющий значение даты введенной в input. Вы можете установить значение по умолчанию для элемента с помощью добавления атрибута в {{htmlattrxref("value", "input")}}, например:

+ +
<input id="date" type="date" value="2017-06-01">
+ +

{{EmbedLiveSample('Значение', 600, 40)}}

+ +
+

Помните, что отображаемый формат даты отличается от настоящего значения value – отображаемый формат даты будет выбран, базируясь на региональных параметрах браузера пользователя, тогда как значение value всегда имеет формат гггг-мм-дд.

+
+ +

Вы также можете получить или установить значение даты в JavaScript с помощью свойств {{domxref("HTMLInputElement.value", "value")}} и {{domxref("HTMLInputElement.valueAsNumber", "valueAsNumber")}} элемента input. Например:

+ +
var dateControl = document.querySelector('input[type="date"]');
+dateControl.value = '2017-06-01';
+console.log(dateControl.value); // prints "2017-06-01"
+console.log(dateControl.valueAsNumber); // prints 1496275200000, a JavaScript timestamp (ms)
+
+ +

Этот код выбирает первый элемент {{HTMLElement("input")}}, type которого date и устанавливает значение даты в 2017-06-01 (1 Июня 2017). Затем он считывает это значение обратно в строковом и числовом форматах.

+ +

Дополнительные атрибуты

+ +

В дополнение к общим атрибутам для всех элементов {{HTMLElement("input")}}, у "date" есть следующие дополнительные атрибуты:

+ + + + + + + + + + + + + + + + + + + + + + +
АтрибутОписание
{{anch("max")}}Максимально возможная дата для установки
{{anch("min")}}Минимально возможная дата для установки
{{anch("step")}}Шаг (в днях), с которым будет изменяться дата при нажатии кнопок вниз или вверх данного элемента
+ +

{{htmlattrdef("max")}}

+ +

Максимально возможная дата для установки. Если {{htmlattrxref("value", "input")}} является более поздней датой, чем дата, указанная в атрибуте {{anch("max")}}, элемент отобразит ошибку при помощи constraint validation. Если в атрибуте max указано значение, не удовлетворяющее формату yyyy-MM-dd, значит элемент не будет иметь максимальной даты.

+ +

В атрибуте max должна быть указана строка с датой, которая больше или равна дате, указанной в атрибуте min.

+ +

{{htmlattrdef("min")}}

+ +

Минимально возможная дата для установки. Если {{htmlattrxref("value", "input")}} является более ранней датой, чем дата, указанная в атрибуте {{anch("min")}}, элемент отобразит ошибку при помощи constraint validation. Если в атрибуте min указано значение, не удовлетворяющее формату yyyy-MM-dd, значит элемент не будет иметь минимальной даты.

+ +

В атрибуте min должна быть указана строка с датой, которая меньше или равна дате, указанной в атрибуте max.

+ +

{{htmlattrdef("step")}}

+ +

{{page("/ru/docs/Web/HTML/Element/input/number", "step-include")}}

+ +

Для полей ввода date значение step задаётся в днях; и является количеством миллисекунд, равное 86 400 000 умножить на значение step (получаемое числовое значение хранится в миллисекундах). Стандартное значение step равно 1, что означает 1 день.

+ +
+

Для полей ввода date указание для step значения any даёт такой же эффект, что и значение 1.

+
+ +

Использование полей ввода c типом date

+ +

На первый взгляд, элемент <input type="date"> выглядит заманчиво — он предоставляет легкий графический интерфейс для выбора даты, нормализует формат даты, отправляемой на сервер независимо от локальных настроек пользователя. Тем не менее, есть проблемы с <input type="date"> в связи с ограниченой поддержкой браузеров.

+ +

В этом разделе мы посмотрим на простые, а затем и более сложные способы использования <input type="date">, и позже дадим советы по уменьшению влияния поддержки браузерами (смотрите {{anch("Handling browser support")}}).

+ +
+

Надеемся, со временем поддержка браузерами станет повсеместной, и эта проблема исчезнет.

+
+ +

Как использовать date?

+ +

Самый простой способ использовать <input type="date"> - это использовать его с элементами <input> и label, как показано ниже:

+ +
<form>
+  <div>
+    <label for="bday">Введите дату вашего рождения:</label>
+    <input type="date" id="bday" name="bday">
+  </div>
+</form>
+ +

{{EmbedLiveSample('Как_использовать_date', 600, 40)}}

+ +

Установка максимальной и минимальной даты

+ +

Вы можете использовать атрибуты {{htmlattrxref("min", "input")}} и {{htmlattrxref("max", "input")}}, чтобы ограничить дату, которую может выбрать пользователь. В следующем примере мы устанавливаем минимальную дату 2017-04-01 и максимальную дату 2017-04-30. Пользователь сможет выбрать дату только из этого диапазона:

+ +
<form>
+  <div>
+    <label for="party">Укажите предпочтительную дату события:</label>
+    <input type="date" id="party" name="party" min="2017-04-01" max="2017-04-30">
+  </div>
+</form>
+ +

{{EmbedLiveSample('Установка_максимальной_и_минимальной_даты', 600, 40)}}

+ +

В результате выполнения кода, пользователь сможет выбрать любой день апреля 2017 года, но не сможет выбрать и даже просмотреть дни других месяцев и годов, в том числе через виджет date picker.

+ +
+

Примечание: Вы должны уметь использовать аттрибут {{htmlattrxref("step", "input")}}, чтобы менять количество дней, на которое будет происходить шаг при изменении даты (например, чтобы сделать выбираемыми только субботы). Однако, не похоже, что это где-то применялось на данный момент.

+
+ +

Controlling input size

+ +

<input type="date"> doesn't support form sizing attributes such as {{htmlattrxref("size", "input")}}. You'll have to resort to CSS for sizing needs.

+ +

Validation

+ +

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

+ +

If you use {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} to restrict the available dates (see {{anch("Setting maximum and minimum dates")}}), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you'll have to check the results to be sure the value is within these dates, since they're only enforced if the date picker is fully supported on the user's device.

+ +

In addition, you can use the {{htmlattrxref("required", "input")}} attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.

+ +

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

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

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

+ +

{{ EmbedLiveSample('Validation', 600, 100) }}

+ +

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

+ +

+ +

Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a {{htmlelement("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.

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

Important: 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 simply 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, is of the wrong type, and so forth).

+
+ +

Handling browser support

+ +

As mentioned above, the major problem with using date inputs at the time of writing is {{anch("Browser compatibility", "browser support")}}. As an example, the date picker on Firefox for Android looks like this:

+ +

+ +

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

+ +

The second problem is the more serious of the two; as we mentioned earlier, with a date input, the actual value is always normalized to the format yyyy-mm-dd. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates, for example:

+ + + +

One way around this is to put a {{htmlattrxref("pattern", "input")}} attribute on your date input. Even though the date input doesn't use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:

+ +
<form>
+  <div>
+    <label for="bday">Enter your birthday:</label>
+    <input type="date" id="bday" name="bday" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">
+    <span class="validity"></span>
+  </div>
+  <div>
+    <input type="submit">
+  </div>
+</form>
+ +

{{ EmbedLiveSample('Handling_browser_support', 600, 100) }}

+ +

If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern nnnn-nn-nn, where n is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates, such as yyyy-dd-mm (whereas we want yyyy-mm-dd). So we still have a problem.

+ + + +

The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls ({{htmlelement("select")}} elements being popular; see below for an implementation), or to use a JavaScript library such as jQuery date picker.

+ +

Examples

+ +

In this example we create two sets of UI elements for choosing dates: a native <input type="date"> picker and a set of three {{htmlelement("select")}} elements for choosing dates in older browsers that don't support the native input.

+ +

{{ EmbedLiveSample('Examples', 600, 100) }}

+ +

HTML

+ +

The HTML looks like so:

+ +
<form>
+    <div class="nativeDatePicker">
+      <label for="bday">Enter your birthday:</label>
+      <input type="date" id="bday" name="bday">
+      <span class="validity"></span>
+    </div>
+    <p class="fallbackLabel">Enter your birthday:</p>
+    <div class="fallbackDatePicker">
+      <span>
+        <label for="day">Day:</label>
+        <select id="day" name="day">
+        </select>
+      </span>
+      <span>
+        <label for="month">Month:</label>
+        <select id="month" name="month">
+          <option selected>January</option>
+          <option>February</option>
+          <option>March</option>
+          <option>April</option>
+          <option>May</option>
+          <option>June</option>
+          <option>July</option>
+          <option>August</option>
+          <option>September</option>
+          <option>October</option>
+          <option>November</option>
+          <option>December</option>
+        </select>
+      </span>
+      <span>
+        <label for="year">Year:</label>
+        <select id="year" name="year">
+        </select>
+      </span>
+    </div>
+</form>
+ +

The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)

+ + + +

JavaScript

+ +

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

+ +
// define variables
+var nativePicker = document.querySelector('.nativeDatePicker');
+var fallbackPicker = document.querySelector('.fallbackDatePicker');
+var fallbackLabel = document.querySelector('.fallbackLabel');
+
+var yearSelect = document.querySelector('#year');
+var monthSelect = document.querySelector('#month');
+var daySelect = document.querySelector('#day');
+
+// 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
+var test = document.createElement('input');
+test.type = 'date';
+
+// 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 days and years dynamically
+  // (the months are always the same, therefore hardcoded)
+  populateDays(monthSelect.value);
+  populateYears();
+}
+
+function populateDays(month) {
+  // delete the current set of <option> elements out of the
+  // day <select>, ready for the next set to be injected
+  while(daySelect.firstChild){
+    daySelect.removeChild(daySelect.firstChild);
+  }
+
+  // Create variable to hold new number of days to inject
+  var dayNum;
+
+  // 31 or 30 days?
+  if(month === 'January' || month === 'March' || month === 'May' || month === 'July' || month === 'August' || month === 'October' || month === 'December') {
+    dayNum = 31;
+  } else if(month === 'April' || month === 'June' || month === 'September' || month === 'November') {
+    dayNum = 30;
+  } else {
+  // If month is February, calculate whether it is a leap year or not
+    var year = yearSelect.value;
+    var leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
+    dayNum = leap ? 29 : 28;
+  }
+
+  // inject the right number of new <option> elements into the day <select>
+  for(i = 1; i <= dayNum; i++) {
+    var option = document.createElement('option');
+    option.textContent = i;
+    daySelect.appendChild(option);
+  }
+
+  // if previous day has already been set, set daySelect's value
+  // to that day, to avoid the day jumping back to 1 when you
+  // change the year
+  if(previousDay) {
+    daySelect.value = previousDay;
+
+    // If the previous day was set to a high number, say 31, and then
+    // you chose a month with less total days in it (e.g. February),
+    // this part of the code ensures that the highest day available
+    // is selected, rather than showing a blank daySelect
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 1;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 2;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 3;
+    }
+  }
+}
+
+function populateYears() {
+  // get this year as a number
+  var date = new Date();
+  var year = date.getFullYear();
+
+  // Make this year, and the 100 years before it available in the year <select>
+  for(var i = 0; i <= 100; i++) {
+    var option = document.createElement('option');
+    option.textContent = year-i;
+    yearSelect.appendChild(option);
+  }
+}
+
+// when the month or year <select> values are changed, rerun populateDays()
+// in case the change affected the number of available days
+yearSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+monthSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+//preserve day selection
+var previousDay;
+
+// update what day has been set to previously
+// see end of populateDays() for usage
+daySelect.onchange = function() {
+  previousDay = daySelect.value;
+}
+ +
+

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.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{SpecName('HTML WHATWG', 'forms.html#date-state-(type=date)', '<input type="date">')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#date-state-(type=date)', '<input type="date">')}}{{Spec2('HTML5 W3C')}}
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.input.input-date")}}

+ +

See also

+ + diff --git a/files/ru/web/html/element/input/datetime-local/index.html b/files/ru/web/html/element/input/datetime-local/index.html new file mode 100644 index 0000000000..99ddddd6bd --- /dev/null +++ b/files/ru/web/html/element/input/datetime-local/index.html @@ -0,0 +1,586 @@ +--- +title: +slug: Web/HTML/Element/Input/datetime-local +translation_of: Web/HTML/Element/input/datetime-local +--- +

{{HTMLRef}}

+ +

{{htmlelement("input")}} элемент типа datetime-local создает поля ввода, позволяющие легко ввести дату и время —  год, месяц, день, часы и минуты.

+ +

Интерфейс управления варьируется от браузера к браузеру, на данный момент поддержка носит фрагментарный характер, только с Chrome/Opera  и EDGE на рабочем столе — и большинство современных мобильных версиях браузера — наличие полезной реализации. В других браузерах элемент управления сводиться до простого <input type="text">.

+ +
+
<input id="datetime" type="datetime-local">
+ +

{{ EmbedLiveSample('Basic_example', 600, 40) }}

+
+ +

Для тех из вас, кто не использует поддерживающий браузер, Chrome/Opera datetime-local control выглядит как скриншот ниже. Нажатие на стрелку вниз с правой стороны приводит к выбору даты, чтобы вы могли выбрать дату; вы должны ввести время вручную.

+ +

+ +

В Edge datetime-local элемент управления выглядит как на скриншоте ниже. Клик на дате и времени отобразит два отдельных поля выбора, чтобы Вы могли легко установить дату и время. То есть, по сути, получаем два элемента date и time, объединенных в один:

+ +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}A {{domxref("DOMString")}} representing a date and time, or empty.
события{{event("change")}} и {{event("input")}}.
Supported Common Attributes{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("readonly", "input")}}, and {{htmlattrxref("step", "input")}}.
IDL attributeslist, value, valueAsNumber.
методы{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}.
+ +

Значение

+ +

 {{domxref("DOMString")}} представление значения даты, введенной во входные данные. Вы можете установить значение по умолчанию для ввода, включая дату внутри {{htmlattrxref("value", "input")}} атрибута, как:

+ +
<label for="party">Enter a date and time for your party booking:</label>
+<input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30">
+ +

{{ EmbedLiveSample('Value', 600, 60) }}

+ +

Одна вещь, чтобы отметить, что отображаемый формат даты отличается от фактического значения — отображаемый формат даты будет выбран на основе установленного языкового стандарта операционной системы пользователя, в то время как датазначение всегда форматируется yyyy-MM-ddThh:mm. Когда значение передается на сервер, например, это будет выглядеть partydate=2017-06-01T08:30.

+ +
+

Примечание: также имейте в виду, что если такие данные поступают через http-запрос Get, двоеточие нужно экранировать для включения в параметры URL, например partydate=2017-06-01T08%3A30.

+
+ +

Вы также можете получить и установить значение даты в JavaScript, используя {{domxref("HTMLInputElement.value")}} свойство, например:

+ +
var dateControl = document.querySelector('input[type="datetime-local"]');
+dateControl.value = '2017-06-01T08:30';
+ +

Использование локальных входных данных datetime

+ +

Ввод даты и времени выглядит удобно на первый взгляд — он обеспечивает простой пользовательский интерфейс для выбора даты и времени, и они нормализуют формат данных, отправляемых на сервер, независимо от локали пользователя. Тем не менее, есть проблемы с <input type="datetime-local"> из-за ограниченной поддержки браузера.

+ +

Мы рассмотрим основные и более сложные способы использования <input type="datetime-local">, затем предложим советы по устранению проблемы поддержки браузера позже (see {{anch("Handling browser support")}}).

+ +

Базовое использование локальных полей ввода datetime

+ +

Самое простои использование <input type="datetime-local"> включает комбинацию базового <input> и {{htmlelement("label")}} элемента, как в примере ниже:

+ +
<form>
+    <label for="party">Enter a date and time for your party booking:</label>
+    <input id="party" type="datetime-local" name="partydate">
+</form>
+ +

{{ EmbedLiveSample('Basic_uses_of_datetime-local', 600, 40) }}

+ +

Установка максимума и минимума даты и времени

+ +

Вы можете использовать {{htmlattrxref("min", "input")}} и {{htmlattrxref("max", "input")}} аттрибуты чтобы ограничить дату/время, которое может выбрать пользователь. В примере ниже мы устанавливает минимальные дату и время в 2017-06-01T08:30 и максимальные в 2017-06-30T16:30:

+ +
  <form>
+    <label for="party">Enter a date and time for your party booking:</label>
+    <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30">
+  </form>
+ +

{{ EmbedLiveSample('Setting_maximum_and_minimum_dates_and_times', 600, 40) }}

+ +

Как результат:

+ + + +
+

Примечание: Существует возможность использовать {{htmlattrxref("step", "input")}} аттрибут для того, чтобы установить количество дней, которые будут пропущены каждый раз, когда дата увеличивается (например, если Вы хотите сделать доступными для выбора только Субботы). Однако, на момент написание этой статьи это нет эффективной реализации этой функции.

+
+ +

Controlling input size

+ +

<input type="datetime-local"> doesn't support form sizing attributes such as {{htmlattrxref("size", "input")}}. You'll have to resort to CSS for sizing needs.

+ +

Setting timezones

+ +

One thing the datetime-local input type doesn't provide is a way to set the timezone/locale of the datetime. This was available in the datetime input type, but this type is now obsolete, having been removed from the spec. The main reasons why this was removed are a lack of implementation in browsers, and concerns over the user interface/experience. It is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control.

+ +

For example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in a hidden input type. For example:

+ +
<input type="hidden" id="timezone" name="timezone" value="-08:00">
+ +

On the other hand, if you were required to allow the user to enter a timezone along with a datetime entry, you could provide a means of inputting a timezone, such as a {{htmlelement("select")}} element:

+ +
<select name="timezone_offset" id="timezone-offset" class="span5">
+    <option value="-12:00">(GMT -12:00) Eniwetok, Kwajalein</option>
+    <option value="-11:00">(GMT -11:00) Midway Island, Samoa</option>
+    <option value="-10:00">(GMT -10:00) Hawaii</option>
+    <option value="-09:50">(GMT -9:30) Taiohae</option>
+    <option value="-09:00">(GMT -9:00) Alaska</option>
+    <option value="-08:00">(GMT -8:00) Pacific Time (US &amp; Canada)</option>
+
+  ...
+
+</select>
+ +

In either case, the timedate and timezone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side.

+ +
+

Note: The above code snippet is taken from All world timezones in an HTML select element.

+
+ +

Validation

+ +

By default, <input type="datetime-local"> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a datetime — which is helpful — but you can still fill in no value and submit, or enter an invalid datetime (e.g. the 32th of April).

+ +

You can use {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} to restrict the available dates (see anch("Setting maximum and minimum dates")), and in addition use the {{htmlattrxref("required", "input")}} attribute to make filling in the date mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field.

+ +

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

+ +
<form>
+    <div>
+        <label for="party">Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm):</label>
+        <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30" required>
+        <span class="validity"></span>
+    </div>
+    <div>
+        <input type="submit" value="Book party!">
+    </div>
+</form>
+ +

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

+ +

{{ EmbedLiveSample('Validation', 600, 120) }}

+ +

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

+ +

+ +

Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a {{htmlelement("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.

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

Important: 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 simply 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, is of the wrong type, and so forth).

+
+ +

Handling browser support

+ +

As mentioned above, the major problem with using date inputs at the time of writing is browser support — only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile. As an example, the datetime-local picker on Firefox for Android looks like this:

+ +

+ +

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 most serious — as we mentioned earlier, with a datetime-local input the actual value is always normalized to the format yyyy-mm-ddThh:mm. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates and times, for example:

+ + + +

One way around this is to put a {{htmlattrxref("pattern", "input")}} attribute on your datetime-local input. Even though the datetime-local input doesn't use it, the text input fallback will. For example, try viewing the following demo in a non-supporting browser:

+ +
<form>
+  <div>
+    <label for="party">Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm):</label>
+    <input id="party" type="datetime-local" name="partydate"
+           min="2017-06-01T08:30" max="2017-06-30T16:30"
+           pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" required>
+    <span class="validity"></span>
+  </div>
+  <div>
+    <input type="submit" value="Book party!">
+  </div>
+  <input type="hidden" id="timezone" name="timezone" value="-08:00">
+</form>
+ +

{{ EmbedLiveSample('Handling_browser_support', 600, 100) }}

+ +

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

+ +

And what user is going to understand the pattern they need to enter the time and date in?

+ +

We still have a problem.

+ + + +

The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, year, and time in separate controls ({{htmlelement("select")}} elements being popular — see below for an implementation), or use JavaScript libraries such as jQuery date picker, and the jQuery timepicker plugin.

+ +

Examples

+ +

In this example we create two sets of UI elements for choosing datetimes — a native <input type="datetime-local"> picker, and a set of five {{htmlelement("select")}} elements for choosing dates and times in older browsers that don't support the native input.

+ +

{{ EmbedLiveSample('Examples', 600, 140) }}

+ +

The HTML looks like so:

+ +
<form>
+  <div class="nativeDateTimePicker">
+    <label for="party">Choose a date and time for your party:</label>
+    <input type="datetime-local" id="party" name="bday">
+    <span class="validity"></span>
+  </div>
+  <p class="fallbackLabel">Choose a date and time for your party:</p>
+  <div class="fallbackDateTimePicker">
+    <div>
+      <span>
+        <label for="day">Day:</label>
+        <select id="day" name="day">
+        </select>
+      </span>
+      <span>
+        <label for="month">Month:</label>
+        <select id="month" name="month">
+          <option selected>January</option>
+          <option>February</option>
+          <option>March</option>
+          <option>April</option>
+          <option>May</option>
+          <option>June</option>
+          <option>July</option>
+          <option>August</option>
+          <option>September</option>
+          <option>October</option>
+          <option>November</option>
+          <option>December</option>
+        </select>
+      </span>
+      <span>
+        <label for="year">Year:</label>
+        <select id="year" name="year">
+        </select>
+      </span>
+    </div>
+    <div>
+      <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 months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year respectively (see the code comments below for detailed explanations of how these functions work.) We also decided to dynamically generate the hours and months, as there are so many of them!

+ + + +

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

+ +
// define variables
+var nativePicker = document.querySelector('.nativeDateTimePicker');
+var fallbackPicker = document.querySelector('.fallbackDateTimePicker');
+var fallbackLabel = document.querySelector('.fallbackLabel');
+
+var yearSelect = document.querySelector('#year');
+var monthSelect = document.querySelector('#month');
+var daySelect = document.querySelector('#day');
+var hourSelect = document.querySelector('#hour');
+var minuteSelect = document.querySelector('#minute');
+
+// 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
+var test = document.createElement('input');
+test.type = 'date';
+// 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 days and years dynamically
+  // (the months are always the same, therefore hardcoded)
+  populateDays(monthSelect.value);
+  populateYears();
+  populateHours();
+  populateMinutes();
+}
+
+function populateDays(month) {
+  // delete the current set of <option> elements out of the
+  // day <select>, ready for the next set to be injected
+  while(daySelect.firstChild){
+    daySelect.removeChild(daySelect.firstChild);
+  }
+
+  // Create variable to hold new number of days to inject
+  var dayNum;
+
+  // 31 or 30 days?
+  if(month === 'January' | month === 'March' | month === 'May' | month === 'July' | month === 'August' | month === 'October' | month === 'December') {
+    dayNum = 31;
+  } else if(month === 'April' | month === 'June' | month === 'September' | month === 'November') {
+    dayNum = 30;
+  } else {
+  // If month is February, calculate whether it is a leap year or not
+    var year = yearSelect.value;
+    (year - 2016) % 4 === 0 ? dayNum = 29 : dayNum = 28;
+  }
+
+  // inject the right number of new <option> elements into the day <select>
+  for(i = 1; i <= dayNum; i++) {
+    var option = document.createElement('option');
+    option.textContent = i;
+    daySelect.appendChild(option);
+  }
+
+  // if previous day has already been set, set daySelect's value
+  // to that day, to avoid the day jumping back to 1 when you
+  // change the year
+  if(previousDay) {
+    daySelect.value = previousDay;
+
+    // If the previous day was set to a high number, say 31, and then
+    // you chose a month with less total days in it (e.g. February),
+    // this part of the code ensures that the highest day available
+    // is selected, rather than showing a blank daySelect
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 1;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 2;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 3;
+    }
+  }
+}
+
+function populateYears() {
+  // get this year as a number
+  var date = new Date();
+  var year = date.getFullYear();
+
+  // Make this year, and the 100 years before it available in the year <select>
+  for(var i = 0; i <= 100; i++) {
+    var option = document.createElement('option');
+    option.textContent = year-i;
+    yearSelect.appendChild(option);
+  }
+}
+
+function populateHours() {
+  // populate the hours <select> with the 24 hours of the day
+  for(var i = 0; i <= 23; i++) {
+    var option = document.createElement('option');
+    option.textContent = (i < 10) ? ("0" + i) : i;
+    hourSelect.appendChild(option);
+  }
+}
+
+function populateMinutes() {
+  // populate the minutes <select> with the 60 hours of each minute
+  for(var i = 0; i <= 59; i++) {
+    var option = document.createElement('option');
+    option.textContent = (i < 10) ? ("0" + i) : i;
+    minuteSelect.appendChild(option);
+  }
+}
+
+// when the month or year <select> values are changed, rerun populateDays()
+// in case the change affected the number of available days
+yearSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+monthSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+//preserve day selection
+var previousDay;
+
+// update what day has been set to previously
+// see end of populateDays() for usage
+daySelect.onchange = function() {
+  previousDay = daySelect.value;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{SpecName('HTML WHATWG', 'forms.html#local-date-and-time-state-(type=datetime-local)', '<input type="datetime-local">')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'forms.html##local-date-and-time-state-(type=datetime-local)', '<input type="datetime-local">')}}{{Spec2('HTML5 W3C')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2012{{CompatNo}}[1]{{CompatNo}}10.62{{CompatNo}}[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] This feature is not implemented yet. See {{bug("888320")}} and TPE DOM/Date time input types.

+ +

[2] It is recognized but there is no UI.

+ +

See also

+ + diff --git a/files/ru/web/html/element/input/datetime/index.html b/files/ru/web/html/element/input/datetime/index.html new file mode 100644 index 0000000000..6b6b0a2292 --- /dev/null +++ b/files/ru/web/html/element/input/datetime/index.html @@ -0,0 +1,29 @@ +--- +title: +slug: Web/HTML/Element/Input/datetime +tags: + - Element + - HTML + - HTML формы + - Reference + - datetime + - Устаревший + - Формы + - Элемент + - Элемент ввода +translation_of: Web/HTML/Element/input/datetime +--- +
{{HTMLRef}}{{obsolete_header}}
+ +

HTML <input type="datetime">  был элементом для ввода даты и времени (час, минута, секунда и доля секунды), а также часовой пояс. Эта функция была удалена из WHATWG HTML и больше не поддерживается в браузерах.

+ +

Вместо этого, браузеры реализуют (и разработчикам рекомендуется использовать)  <input type="datetime-local">.

+ +

Формат значений даты и времени, использумый этим типом описан в {{SectionOnPage("/ru/docs/Web/HTML/Date_and_time_formats", "Строки глобальной даты и времени")}}.

+ +

Смотрите также

+ + diff --git a/files/ru/web/html/element/input/file/index.html b/files/ru/web/html/element/input/file/index.html new file mode 100644 index 0000000000..7e47d3be03 --- /dev/null +++ b/files/ru/web/html/element/input/file/index.html @@ -0,0 +1,439 @@ +--- +title: +slug: Web/HTML/Element/Input/file +translation_of: Web/HTML/Element/input/file +--- +
{{HTMLRef}}
+ +

{{HTMLElement("input")}} элемент с атрибутом type="file" позволяет пользователю выбрать один файл или более из файлового хранилища своего устройства. После выбора эти файлы могут быть загружены на сервер при помощи формы, или обработаны JavaScript и File API.

+ +
+
<input name="myFile" type="file">
+
+
+ +

{{EmbedLiveSample('file-example', 650, 40)}}

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}{{domxref("DOMString")}} представляет собой путь до выбранного файла.
Действия{{event("change")}} и{{event("input")}}
Поддерживаемые атрибуты{{htmlattrxref("accept", "input")}}, {{htmlattrxref("multiple", "input")}}, {{htmlattrxref("required", "input")}}
IDL атрибутыfiles and value
Методы{{domxref("HTMLInputElement.select", "select()")}}
+ +

Value

+ +

Атрибут {{htmlattrxref("value", "input")}} элемента input содержит {{domxref("DOMString")}}, который представляет путь к выбранным файлам. Если пользователь выбрал несколько файлов, value представляет первый файл из списка. Отстальные файлы можно определить используя {{domxref("HTMLInputElement.files")}} свойство элемента input.

+ +
Note: + +
    +
  1. Если выбрано несколько файлов, строка представляет собой первый выбранный файл. JavaScript предоставляет доступ к остальным файлам через свойство FileList.
  2. +
  3. Если не выбрано ни одного файла, .строка равна "" (пустая).
  4. +
  5. Строка начинается с  C:\fakepath\,  для предотвращения определения файловой структуры пользователя вредоносным ПО.
  6. +
+
+ +

Additional attributes

+ +

In addition to the common attributes shared by all {{HTMLElement("input")}} elements, inputs of type file also support:

+ +
+
files
+
A {{domxref("FileList")}} object that lists every selected file. This list has no more than one member unless the {{htmlattrxref("multiple", "input")}} attribute is specified.
+
+ +

Using file inputs

+ +

A basic example

+ +
<form method="post" enctype="multipart/form-data">
+ <div>
+   <label for="file">Choose file to upload</label>
+   <input type="file" id="file" name="file" multiple>
+ </div>
+ <div>
+   <button>Submit</button>
+ </div>
+</form>
+ + + +

This produces the following output:

+ +

{{EmbedLiveSample('A_basic_example', 650, 60)}}

+ +
+

Note: You can find this example on GitHub too — see the source code, and also see it running live.

+
+ +

Regardless of the user's device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file.

+ +

Including the {{htmlattrxref("multiple", "input")}} attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down Shift or Control, and then clicking). If you only want the user to choose a single file per <input>, omit the multiple attribute.

+ +

When the form is submitted, each selected file's name will be added to URL parameters in the following fashion: ?file=file1.txt&file=file2.txt

+ +

Getting information on selected files

+ +

The selected files' are returned by the element's {{domxref("HTMLElement.files", "files")}} property, which is a {{domxref("FileList")}} object containing a list of {{domxref("File")}} objects. The FileList behaves like an array, so you can check its length property to get the number of selected files.

+ +

Each File object contains the following information:

+ +
+
name
+
The file's name.
+
lastModified
+
A number specifying the date and time at which the file was last modified, in milliseconds since the UNIX epoch (January 1, 1970 at midnight).
+
lastModifiedDate {{deprecated_inline}}
+
A {{jsxref("Date")}} object representing the date and time at which the file was last modified. This is deprecated and should not be used. Use lastModified instead.
+
size
+
The size of the file in bytes.
+
type
+
The file's MIME type.
+
webkitRelativePath {{non-standard_inline}}
+
A string specifying the file's path relative to the base directory selected in a directory picker (that is, a file picker in which the {{htmlattrxref("webkitdirectory", "input")}} attribute is set). This is non-standard and should be used with caution.
+
+ +
+

Note: You can set as well as get the value of HTMLInputElement.files in all modern browsers; this was most recently added to Firefox, in version 57 (see {{bug(1384030)}}).

+
+ +

Limiting accepted file types

+ +

Often you won't want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as JPEG or PNG.

+ +

Acceptable file types can be specified with the {{htmlattrxref("accept","input")}} attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples:

+ + + +

Let's look like a more complete example:

+ +
<form method="post" enctype="multipart/form-data">
+  <div>
+    <label for="profile_pic">Choose file to upload</label>
+    <input type="file" id="profile_pic" name="profile_pic"
+          accept=".jpg, .jpeg, .png">
+  </div>
+  <div>
+    <button>Submit</button>
+  </div>
+</form>
+ + + +

This produces a similar-looking output to the previous example:

+ +

{{EmbedLiveSample('Limiting_accepted_file_types', 650, 60)}}

+ +
+

Note: You can find this example on GitHub too — see the source code, and also see it running live.

+
+ +

It may look similar, but if you try selecting a file with this input, you'll see that the file picker only lets you select the file types specified in the accept value (the exact nature differs across browsers and operating systems).

+ +

Screenshot of a macOS file picker dialog. Files other than JPEG are grayed-out and unselectable.

+ +

The accept attribute doesn't validate the types of the selected files; it simply provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.

+ +

Because of this, you should make sure that the accept attribute is backed up by appropriate server-side validation.

+ +

Examples

+ +

In this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the {{domxref("HTMLInputElement.files")}} property, as well as showing off a few clever tricks.

+ +
+

Note: You can see the complete source code for this example on GitHub — file-example.html (see it live also). We won't explain the CSS; the JavaScript is the main focus.

+
+ +

First of all, let's look at the HTML:

+ +
<form method="post" enctype="multipart/form-data">
+  <div>
+    <label for="image_uploads">Choose images to upload (PNG, JPG)</label>
+    <input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple>
+  </div>
+  <div class="preview">
+    <p>No files currently selected for upload</p>
+  </div>
+  <div>
+    <button>Submit</button>
+  </div>
+</form>
+ + + +

This is similar to what we've seen before — nothing special to comment on.

+ +

Next, let's walk through the JavaScript.

+ +

In the first lines of script, we get references to the form input itself, and the {{htmlelement("div")}} element with the class of .preview. Next, we hide the {{htmlelement("input")}} element — we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. You can activate the input element by clicking its {{htmlelement("label")}}, so it is better to visually hide the input and style the label like a button, so the user will know to interact with it if they want to upload files.

+ +
var input = document.querySelector('input');
+var preview = document.querySelector('.preview');
+
+input.style.opacity = 0;
+ +
+

Note: opacity is used to hide the file input instead of visibility: hidden or display: none, because assistive technology interprets the latter two styles to mean the file input isn't interactive.

+
+ +

Next, we add an event listener to the input to listen for changes to its selected value changes (in this case, when files are selected). The event listener invokes our custom updateImageDisplay() function.

+ +
input.addEventListener('change', updateImageDisplay);
+ +

Whenever the updateImageDisplay() function is invoked, we:

+ + + +
function updateImageDisplay() {
+  while(preview.firstChild) {
+    preview.removeChild(preview.firstChild);
+  }
+
+  var curFiles = input.files;
+  if(curFiles.length === 0) {
+    var para = document.createElement('p');
+    para.textContent = 'No files currently selected for upload';
+    preview.appendChild(para);
+  } else {
+    var list = document.createElement('ol');
+    preview.appendChild(list);
+    for(var i = 0; i < curFiles.length; i++) {
+      var listItem = document.createElement('li');
+      var para = document.createElement('p');
+      if(validFileType(curFiles[i])) {
+        para.textContent = 'File name ' + curFiles[i].name + ', file size ' + returnFileSize(curFiles[i].size) + '.';
+        var image = document.createElement('img');
+        image.src = window.URL.createObjectURL(curFiles[i]);
+
+        listItem.appendChild(image);
+        listItem.appendChild(para);
+
+      } else {
+        para.textContent = 'File name ' + curFiles[i].name + ': Not a valid file type. Update your selection.';
+        listItem.appendChild(para);
+      }
+
+      list.appendChild(listItem);
+    }
+  }
+}
+ +

The custom validFileType() function takes a {{domxref("File")}} object as a parameter, then loops through the list of allowed file types, checking if any matches the file's type property. If a match is found, the function returns true. If no match is found, it returns false.

+ +
var fileTypes = [
+  'image/jpeg',
+  'image/pjpeg',
+  'image/png'
+]
+
+function validFileType(file) {
+  for(var i = 0; i < fileTypes.length; i++) {
+    if(file.type === fileTypes[i]) {
+      return true;
+    }
+  }
+
+  return false;
+}
+ +

The returnFileSize() function takes a number (of bytes, taken from the current file's size property), and turns it into a nicely formatted size in bytes/KB/MB.

+ +
function returnFileSize(number) {
+  if(number < 1024) {
+    return number + 'bytes';
+  } else if(number > 1024 && number < 1048576) {
+    return (number/1024).toFixed(1) + 'KB';
+  } else if(number > 1048576) {
+    return (number/1048576).toFixed(1) + 'MB';
+  }
+}
+ +

The example looks like this; have a play:

+ +

{{EmbedLiveSample('Examples', '100%', 200)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'input.html#file-upload-state-(type=file)', '<input type="file">')}}{{Spec2('HTML WHATWG')}}Initial definition
{{SpecName('HTML5.1', 'sec-forms.html#file-upload-state-typefile', '<input type="file">')}}{{Spec2('HTML5.1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}1.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileiOS WebKit
+ (Safari/Chrome/Firefox/etc)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(4.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ru/web/html/element/input/image/index.html b/files/ru/web/html/element/input/image/index.html new file mode 100644 index 0000000000..08b69b943a --- /dev/null +++ b/files/ru/web/html/element/input/image/index.html @@ -0,0 +1,205 @@ +--- +title: +slug: Web/HTML/Element/Input/image +translation_of: Web/HTML/Element/input/image +--- +

<input type="image"> - это кнопка отправки в виде изображения. Вы можете использовать атрибут src, чтобы выбрать источник изображения и атрибут alt, чтобы добавить альтернативный текст. Атрибутами width и height можно указать размер изображения в пикселях.

+ + + + + + + + + + + + + + + + + + + + +
Разрешенное содержимоеНету, это пустой элемент.
Необязательный закрывающийся тегОбязательно должен быть открывающийся тег, и обязательно отсутствует закрывающий.
Разрешенные родительские элементыЛюбой элемент, которому доступен фразообразующий контент (phrasing content).
DOM-интерфейс {{domxref("HTMLInputElement")}}
+ +

Атрибуты

+ +

Этому элементу доступны глобальные атрибуты (global attributes).

+ +

{{htmlattrdef("type")}}

+ +
+
{{htmlattrdef("formaction")}} {{HTMLVersionInline("5")}}
+
The URI of a program that processes the information submitted by the input element, here image if specified, it overrides the {{htmlattrxref("action","form")}} attribute of the element's form owner.
+
+ +
+
{{htmlattrdef("formenctype")}} {{HTMLVersionInline("5")}}
+
If the input element is an image, this attribute specifies the type of content that is used to submit the form to the server. Possible values are: +
    +
  • application/x-www-form-urlencoded: The default value if the attribute is not specified.
  • +
  • multipart/form-data: Use this value if you are using an {{HTMLElement("input")}} element with the {{htmlattrxref("type","input")}} attribute set to file.
  • +
  • text/plain
  • +
+ +

If this attribute is specified, it overrides the {{htmlattrxref("enctype","form")}} attribute of the element's form owner.

+
+
{{htmlattrdef("formmethod")}} {{HTMLVersionInline("5")}}
+
In image input element, this attribute specifies the HTTP method that the browser uses to submit the form. Possible values are: +
    +
  • post: The data from the form is included in the body of the form and is sent to the server.
  • +
  • get: 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 {{htmlattrxref("method","form")}} attribute of the element's form owner.

+
+
{{htmlattrdef("formnovalidate")}} {{HTMLVersionInline("5")}}
+
This Boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the {{htmlattrxref("novalidate","form")}} attribute of the element's form owner.
+
{{htmlattrdef("formtarget")}} {{HTMLVersionInline("5")}}
+
This 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 {{htmlattrxref("target", "form")}} attribute of the element's form owner. The following keywords have special meanings: +
    +
  • _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • +
  • _blank: Load the response into a new unnamed browsing context.
  • +
  • _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • +
  • _top: 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 _self.
  • +
+
+
{{htmlattrdef("height")}} {{HTMLVersionInline("5")}}
+
This attribute defines the height of the image displayed for the button.
+
{{htmlattrdef("required")}} {{HTMLVersionInline("5")}}
+
This attribute specifies that the user must fill in a value before submitting a form but it cannot be used when the type attribute is image type (submit, reset, or button). The {{cssxref(":optional")}} and {{cssxref(":required")}} CSS pseudo-classes will be applied to the field as appropriate.
+
{{htmlattrdef("src")}}
+
This attribute specifies a URI for the location of an image to display on the graphical submit button; otherwise it is ignored.
+
{{htmlattrdef("usemap")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline", "HTML5")}}
+
The name of a {{HTMLElement("map")}} element as an image map.
+
{{htmlattrdef("width")}} {{HTMLVersionInline("5")}}
+
This attribute defines the width of the image displayed for the button.
+
+

Примеры

+
+
+ +

Поле в виде логотипа Firefox 

+ +
<input type="image" name="image" src="https://mdn.mozillademos.org/files/2917/fxlogo.png" width="50">
+ +

Результат

+ +

{{ EmbedLiveSample('simple_input_image_example') }}

+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + +
СпецификацияСтатус
{{SpecName('HTML WHATWG', 'forms.html#image-button-state-(type=image)', '<input type="image">')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#image-button-state-%28type=image%29', '<input type="image">')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'interact/forms.html#h-17.4', '<form>')}}{{Spec2('HTML4.01')}}
+ +

Браузерная совместимость

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка1.0{{CompatGeckoDesktop("1.7 or earlier")}}2 или ранее1.01.0
type1.0{{CompatGeckoDesktop("1.7 or earlier")}}21.01.0
type=image1.0Gecko 2.0 only sends x and y coordinates when clicked, not longer the name/value of the element21.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
type{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
type=image{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +
+
+

Смотри также

+
+
diff --git a/files/ru/web/html/element/input/index.html b/files/ru/web/html/element/input/index.html new file mode 100644 index 0000000000..7899ede12e --- /dev/null +++ b/files/ru/web/html/element/input/index.html @@ -0,0 +1,311 @@ +--- +title: +slug: Web/HTML/Element/Input +translation_of: Web/HTML/Element/input +--- +

Описание

+ +

Элемент HTML <input> используется для создания интерактивных элементов управления в веб-формах для получения данных от пользователя; в зависимости от устройства и {{Glossary("user agent")}}, доступен широкий выбор типов входных данных и виджетов управления. Из-за огромного количества возможных сочетаний типов ввода и атрибутов это один из самых мощных и сложных элементов HTML.

+ + + +

Атрибуты

+ +

Этот элемент содержит глобальные атрибуты.

+ + + +
+
{{htmlattrdef("type")}}
+
Тип элемента для отображения. Если этот атрибут не указан, по умолчанию используется text. Возможными значениями являются: +
    +
  • button: Кнопка без предопределенного поведения.
  • +
  • checkbox: Флажок («чекбокс»). Следует использовать атрибут value для определения значения, которое будет отдано этим элементом. Используйте атрибут checked, чтобы указать, должен ли флажок быть выставлен. Можно также использовать атрибут indeterminate, чтобы указать, что флажок находится в неопределённом состоянии (на большинстве платформ при этом рисуется горизонтальная линия поперёк флажка).
  • +
  • color: {{HTMLVersionInline("5")}} Элемент управления цветом. Пользовательский интерфейс выбора цвета не имеет никаких других функций, кроме принятия простых цветов в виде текста (больше информации).
  • +
  • date: {{HTMLVersionInline("5")}} Элемент управления для ввода даты (год, месяц и день, без времени).
  • +
  • datetime: {{HTMLVersionInline("5")}} Элемент управления для ввода даты и времени (час, минута, секунда и доля секунды) в соответствии с часовым поясом UTC.
  • +
  • datetime-local: {{HTMLVersionInline("5")}} Элемент управления для ввода даты и времени без часового пояса.
  • +
  • email: {{HTMLVersionInline("5")}} Поле для редактирования адреса электронной почты. Перед отправкой проверяется, что входное значение содержит либо пустую строку, либо один действительный адрес электронной почты. Соответствуют CSS псевдо-классам {{cssxref(":valid")}} and {{cssxref(":invalid")}}.
  • +
  • file: Элемент управления, который позволяет пользователю выбрать файл. Используйте атрибут accept, чтобы определить типы файлов, которые могут быть выбраны.
  • +
  • hidden: Элемент управления, которые не отображается, но чье значение отправлено на сервер.
  • +
  • image: Кнопка вставки изображения. Вы должны использовать атрибут src, чтобы определить путь к изображению и атрибут alt - для определения альтернативного текста. Вы можете использовать атрибуты height и width, чтобы определить размер вставки изображения в пикселях.
  • +
  • month: {{HTMLVersionInline("5")}} Элемент управления для ввода месяца и года без часового пояса.
  • +
  • number: {{HTMLVersionInline("5")}} Элемент управления ввода числа(тип float).
  • +
  • password: Однострочное текстовое поле, чье значение скрыто символом "звездочка". Используйте атрибуты minlength и maxlength, чтобы указать минимальную и максимальную длину значения, которое может быть введено. +
    Любые формы, в которых присутствует важная информация(например, пароль), должны быть обработаны через HTTPS; в настоящий момент Firefox реализует составной механизм предупреждения, направленные против небезопасных форм для входа в систему - смотрите Небезопасные пароли.
    +
  • +
  • radio: Кнопка-переключатель, позволяет выбрать одно значение из множественного выбора.
  • +
  • range: {{HTMLVersionInline("5")}}Элемент управления для ввода числа, точное значение которого не имеет значения. Этот тип управления использует следующие значения по умолчанию, если соответствующие атрибуты не указаны: +
      +
    • min: 0
    • +
    • max: 100
    • +
    • value: min + (max-min)/2, or min if max is less than min
    • +
    • step: 1
    • +
    +
  • +
  • reset: Кнопка сброса содержимого формы в состояние по умолчанию.
  • +
  • search: {{HTMLVersionInline("5")}}Однострочное текстовое поле для ввода строк поиска; разрывы строк автоматически удаляются из входного значения.
  • +
  • submit: Кнопка для отправления формы.
  • +
  • tel: {{HTMLVersionInline("5")}} Элемент управления для ввода номера телефона; разрывы строк автоматически удаляются из входного значения, но никакой другой синтаксис не применяется. Можно использовать такие атрибуты как pattern и maxlength, чтобы ограничить вводимое значение.
    + Псевдоклассы CSS {{cssxref(":valid")}} and {{cssxref(":invalid")}} применяются при необходимости..
  • +
  • text: Однострочное текстовое поле. Переносы строк автоматически удаляются из входного значения.
  • +
  • time: {{HTMLVersionInline("5")}} Элемент управления для ввода значения времени без часового пояса.
  • +
  • url: {{HTMLVersionInline("5")}} Поле для редактирования URI. Введенное значение должно содержать либо пустую строку, либо допустимый абсолютный URL. В противном случае значение не будет принято. Переводы строк, лидирующие и завершающие пробельные символы будут автоматически удалены из введенного значения. Можно использовать такие атрибуты как pattern или maxlength, чтобы ограничить вводимые значения. Псевдоклассы CSS {{cssxref(":valid")}} and {{cssxref(":invalid")}} применяются при необходимости.
  • +
  • week: {{HTMLVersionInline("5")}} Элемент управления для ввода даты, содержащей число неделя-год и номер недели без часового пояса.
  • +
+
+
{{htmlattrdef("accept")}}
+
В случае, если значением атрибута type является file, данный атрибут определяет типы файлов, которые сервер может принять. В противном случае файл игнорируется. Значение должно быть списком уникальных спецификаторов типов содержания, разделенным запятыми:
+
{{htmlattrdef("accesskey")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline", "HTML5")}}
+
Одиночный символ, который пользователь может нажать, чтобы переключить фокус на элемент управления.
+
{{htmlattrdef("mozactionhint")}} {{non-standard_inline}}
+
Определяет "действие-подсказку", которая используется для определения того, как будет обозначаться клавиша enter на мобильных устройствах с виртуальной клавиатурой. Поддерживаемые значения: go, done, next, search, и send; они автоматически сопоставляются с необходимой строкой (являются чувствительными к регистру).
+
{{htmlattrdef("autocomplete")}} {{HTMLVersionInline("5")}}
+
Этот атрибут указывает, разрешено ли автоматическое заполнение поля браузером. Разрешено по умолчанию, даже если не указано. Данный атрибут игнорируется, если атрибут type равен hidden, password, checkbox, radio, file, или type кнопка (button, submit, reset, image). Возможные значения: +
    +
  • off: Пользователь должен каждый раз полностью вводить значение в поле или документ предусматривает свой собственный метод автозаполнения; браузер не делает автоматического заполнения записи.
  • +
  • on: Браузер автоматически заканчивает значение поля, основываясь на значениях, которые вводились пользователем ранее.
  • +
+ +

Если не атрибут autocomplete не указан в <input>, тогда браузер использует атрибут autocomplete формы, которая является родительской для данной формы. The form owner is either the form element that this <input> element is a descendant of or the form element whose id is specified by the form attribute of the input element. For more information, see the {{htmlattrxref("autocomplete", "form")}} attribute in {{HTMLElement("form")}}.

+
+
{{htmlattrdef("autofocus")}} {{HTMLVersionInline("5")}}
+
This Boolean attribute lets you specify that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the autofocus attribute, which is a Boolean. It cannot be applied if the type attribute is set to hidden (that is, you cannot automatically set focus to a hidden control).
+
{{htmlattrdef("autosave")}} {{HTMLVersionInline("5")}}
+
This attribute should be defined as a unique value. If the value of the type attribute is search, previous search term values will persist in the dropdown across page load.
+
{{htmlattrdef("checked")}}
+
When the value of the type attribute is radio or checkbox, the presence of this Boolean attribute indicates that the control is selected by default; otherwise it is ignored.
+
{{htmlattrdef("disabled")}}
+
This Boolean attribute indicates that the form control is not available for interaction. In particular, the click event will not be dispatched on disabled controls. Also, a disabled control's value isn't submitted with the form.
+
{{htmlattrdef("form")}} {{HTMLVersionInline("5")}}
+
The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a {{HTMLElement("form")}} element in the same document. If this attribute is not specified, this <input> element must be a descendant of a {{HTMLElement("form")}} element. This attribute enables you to place <input> elements anywhere within a document, not just as descendants of their form elements. An input can only be associated with one form.
+
{{htmlattrdef("formaction")}} {{HTMLVersionInline("5")}}
+
The URI of a program that processes the information submitted by the input element, if it is a submit button or image. If specified, it overrides the {{htmlattrxref("action","form")}} attribute of the element's form owner.
+
{{htmlattrdef("formenctype")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this attribute specifies the type of content that is used to submit the form to the server. Possible values are: +
    +
  • application/x-www-form-urlencoded: The default value if the attribute is not specified.
  • +
  • multipart/form-data: Use this value if you are using an {{HTMLElement("input")}} element with the {{htmlattrxref("type","input")}} attribute set to file.
  • +
  • text/plain
  • +
+ +

If this attribute is specified, it overrides the {{htmlattrxref("enctype","form")}} attribute of the element's form owner.

+
+
{{htmlattrdef("formmethod")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this attribute specifies the HTTP method that the browser uses to submit the form. Possible values are: +
    +
  • post: The data from the form is included in the body of the form and is sent to the server.
  • +
  • get: The data from the form are 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 {{htmlattrxref("method","form")}} attribute of the element's form owner.

+
+
{{htmlattrdef("formnovalidate")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this Boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the {{htmlattrxref("novalidate","form")}} attribute of the element's form owner.
+
{{htmlattrdef("formtarget")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this 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 {{htmlattrxref("target", "form")}} attribute of the elements's form owner. The following keywords have special meanings: +
    +
  • _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • +
  • _blank: Load the response into a new unnamed browsing context.
  • +
  • _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • +
  • _top: 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 _self.
  • +
+
+
{{htmlattrdef("height")}} {{HTMLVersionInline("5")}}
+
If the value of the type attribute is image, this attribute defines the height of the image displayed for the button.
+
{{htmlattrdef("inputmode")}} {{HTMLVersionInline("5")}}
+
A hint to the browser for which keyboard to display. This attribute applies when the value of the type attribute is text, password, email, or url. Possible values are: +
    +
  • verbatim: Alphanumeric, non-prose content such as usernames and passwords.
  • +
  • latin: Latin-script input in the user's preferred language with typing aids such as text prediction enabled. For human-to-computer communication such as search boxes.
  • +
  • latin-name: As latin, but for human names.
  • +
  • latin-prose: As latin, but with more aggressive typing aids. For human-to-human communication such as instant messaging for email.
  • +
  • full-width-latin: As latin-prose, but for the user's secondary languages.
  • +
  • kana: Kana or romaji input, typically hiragana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
  • +
  • katakana: Katakana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
  • +
  • numeric: Numeric input, including keys for the digits 0 to 9, the user's preferred thousands separator character, and the character for indicating negative numbers. Intended for numeric codes, e.g. credit card numbers. For actual numbers, prefer using <input type="number">
  • +
  • tel: Telephone input, including asterisk and pound key. Use <input type="tel"> if possible instead.
  • +
  • email: Email input. Use <input type="email"> if possible instead.
  • +
  • url: URL input. Use <input type="url"> if possible instead.
  • +
+
+
{{htmlattrdef("list")}} {{HTMLVersionInline("5")}}
+
В атрибуте указывает id элемента {{HTMLElement("datalist")}}, в котором находится список предопределенных значений для заполнения. Браузер отображает только те варианты, которые соответствуют введенным символами. Этот атрибут игнорируется, когда атрибут type принимает значения hidden, checkbox, radio, file, или type в качестве кнопки.
+
{{htmlattrdef("max")}} {{HTMLVersionInline("5")}}
+
The maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
+
{{htmlattrdef("maxlength")}}
+
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored. It can exceed the value of the size attribute. If it is not specified, the user can enter an unlimited number of characters. Specifying a negative number results in the default behavior; that is, the user can enter an unlimited number of characters. The constraint is evaluated only when the value of the attribute has been changed.
+
{{htmlattrdef("min")}} {{HTMLVersionInline("5")}}
+
The minimum (numeric or date-time) value for this item, which must not be greater than its maximum (max attribute) value.
+
{{htmlattrdef("minlength")}} {{HTMLVersionInline("5")}}
+
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the minimum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.
+
{{htmlattrdef("multiple")}} {{HTMLVersionInline("5")}}
+
Этот Boolean атрибут указывает, может ли пользователь вводить несколько значений. Этот атрибут применяется, если для атрибута type задано значение email или file; в противном случае он игнорируется. 
+
{{htmlattrdef("name")}}
+
The name of the control, which is submitted with the form data.
+
{{htmlattrdef("pattern")}} {{HTMLVersionInline("5")}}
+
A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.
+
{{htmlattrdef("placeholder")}} {{HTMLVersionInline("5")}}
+
A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. +
Note: Do not use the placeholder attribute instead of a {{HTMLElement("label")}} element. Their purposes are different: the {{HTMLElement("label")}} attribute describes the role of the form element; that is, it indicates what kind of information is expected, the placeholder attribute is a hint about the format the content should take. There are cases in which the placeholder attribute is never displayed to the user, so the form must be understandable without it.
+
+
{{htmlattrdef("readonly")}}
+
This Boolean attribute indicates that the user cannot modify the value of the control. +

{{HTMLVersionInline("5")}} This attribute is ignored if the value of the type attribute is hidden, range, color, checkbox, radio, file, or a button type.

+
+
{{htmlattrdef("required")}} {{HTMLVersionInline("5")}}
+
This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden, image, or a button type (submit, reset, or button). The {{cssxref(":optional")}} and {{cssxref(":required")}} CSS pseudo-classes will be applied to the field as appropriate.
+
{{htmlattrdef("selectionDirection")}} {{HTMLVersionInline("5")}}
+
The direction in which selection occurred. This is "forward" if the selection was made from left-to-right in an LTR locale or right-to-left in an RTL locale, or "backward" if the selection was made in the opposite direction. This can be "none" if the selection direction is unknown.
+
{{htmlattrdef("size")}}
+
The initial size of the control. This value is in pixels unless the value of the type attribute is text or password, in which case, it is an integer number of characters. Starting in HTML5, this attribute applies only when the type attribute is set to text, search, tel, url, email, or password; otherwise it is ignored. In addition, the size must be greater than zero. If you don't specify a size, a default value of 20 is used.
+
{{htmlattrdef("spellcheck")}} {{HTMLVersionInline("5")}}
+
Setting the value of this attribute to true indicates that the element needs to have its spelling and grammar checked. The value default indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck value. The value false indicates that the element should not be checked.
+
{{htmlattrdef("src")}}
+
If the value of the type attribute is image, this attribute specifies a URI for the location of an image to display on the graphical submit button; otherwise it is ignored.
+
{{htmlattrdef("step")}} {{HTMLVersionInline("5")}}
+
Works with the min and max attributes to limit the increments at which a numeric or date-time value can be set. It can be the string any or a positive floating point number. If this attribute is not set to any, the control accepts only values at multiples of the step value greater than the minimum.
+
{{htmlattrdef("tabindex")}} element-specific in {{HTMLVersionInline(4)}}, global in {{HTMLVersionInline("5")}}
+
The position of the element in the tabbing navigation order for the current document.
+
{{htmlattrdef("usemap")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline", "HTML5")}}
+
The name of a {{HTMLElement("map")}} element to as an image map.
+
{{htmlattrdef("value")}}
+
The initial value of the control. This attribute is optional except when the value of the type attribute is radio or checkbox.
+ Note that when reloading the page, Gecko and IE will ignore the value specified in the HTML source, if the value was changed before the reload.
+
{{htmlattrdef("width")}} {{HTMLVersionInline("5")}}
+
If the value of the type attribute is image, this attribute defines the width of the image displayed for the button.
+
{{htmlattrdef("x-moz-errormessage")}} {{non-standard_inline}}
+
This Mozilla extension allows you to specify the error message to display when a field doesn't successfully validate.
+
+ +

Notes

+ +

File inputs

+ +
+

Note: Starting in {{Gecko("2.0")}}, calling the click() method on an {{HTMLElement("input")}} element of type "file" opens the file picker and lets the user select files. See Using files from web applications for an example and more details.

+
+ +

You can't 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";
+
+ +

Error messages

+ +

If you want Firefox to present a custom error message when a field fails to validate, you can use the x-moz-errormessage 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.

+ +

Examples

+ +

A simple input box

+ +
<!-- A basic input -->
+<input type="text" name="input" value="Type here">
+
+ +

+ +

A common use-case scenario

+ +
<!-- A common form that includes input tags -->
+<form action="getform.php" method="get">
+    First name: <input type="text" name="first_name" /><br />
+     Last name: <input type="text" name="last_name" /><br />
+        E-mail: <input type="email" name="user_email" /><br />
+<input type="submit" value="Submit" />
+</form>
+
+ +

Using mozactionhint on Firefox mobile

+ +

You can use the {{htmlattrxref("mozactionhint", "input")}} attribute to specify the text for the label of the enter key on the virtual keyboard when your form is rendered on Firefox mobile. For example, to have a "Next" label, you can do this:

+ +
<input type="text" mozactionhint="next" name="sometext" />
+
+ +

The result is:

+ +

mozactionhint.png

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'the-input-element.html#the-input-element', '<input>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#the-input-element', '<input>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'interact/forms.html#h-17.4', '<form>')}}{{Spec2('HTML4.01')}}
+ +

Совместимость с браузерами

+ +

{{Compat("html.elements.input")}}

+ +

[1] Распознаётся, но UI отсутствует.

+ +

[2] Отсутствует для type="checkbox" и type="radio".

+ +

[3] В Safari autocapitalize="words" переводит в верхний регистр каждый второй символ слова.

+ +

[4] datetime был удалён из спецификации и браузеров в пользу datetime-local.

+ +

[5] См {{bug(1355389)}}

+ +

[6] Ещё не имплементировано. Наблюдать: {{bug("888320")}} и TPE DOM/Date time input types.

+ +

Gecko notes

+ +

Starting in Gecko 9.0 {{geckoRelease("9.0")}}, Firefox for Android lets users capture images using their camera and upload them, without having to leave the browser. Web developers can implement this feature by simply specifying setting the accept attribute's value to "image/*" on their file input, like this:

+ +

<input type="file" accept="image/*">

+ +

Firefox for Android sets a default {{ cssxref("background-image") }} gradient on all type="text", type="file", type="button", and type="submit" inputs. This can be disabled using background-image: none.

+ +

Firefox for Android also sets a default {{ cssxref("border") }} on all <input type="file"> elements.

+ +

See also

+ + + +

{{HTMLRef}}

diff --git a/files/ru/web/html/element/input/number/index.html b/files/ru/web/html/element/input/number/index.html new file mode 100644 index 0000000000..93f1fb2525 --- /dev/null +++ b/files/ru/web/html/element/input/number/index.html @@ -0,0 +1,420 @@ +--- +title: +slug: Web/HTML/Element/Input/number +translation_of: Web/HTML/Element/input/number +--- +
{{HTMLRef}}
+ +

{{HTMLElement("input")}} элементы типа number используются для того, чтобы дать возможность пользователю ввести число. У них есть встроенная валидация, запрещающая вводить нечисловые значения. Браузер может предоставить возможность увеличить или уменьшить значение специальными стрелками, используя мышь или просто двигая пальцем по экрану.

+ +
{{EmbedInteractiveExample("pages/tabbed/input-number.html", "tabbed-shorter")}}
+ + + +

В браузерах, которые не поддерживают тип number, тип number приводится к text.

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}A {{jsxref("Number")}} representing a number, or empty
Events{{event("change")}} and {{event("input")}}
Supported Common Attributes{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("placeholder", "input")}}, {{htmlattrxref("readonly", "input")}}
IDL attributeslist, value, valueAsNumber
Methods{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}
+ +

Value

+ +

{{jsxref("Number")}}, представляющий значение введенного числа. Вы можете установить значение по умолчанию, вставив значение в атрибут {{htmlattrxref("value", "input")}}, например:

+ +
<input id="number" type="number" value="42">
+ +

{{EmbedLiveSample('Value', 600, 40)}}

+ +

Additional attributes

+ +

In addition to the attributes commonly supported by all {{HTMLElement("input")}} types, inputs of type number support these attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescription
{{anch("max")}}The maximum value to accept for this input
{{anch("min")}}The minimum value to accept for this input
{{anch("placeholder")}}An example value to display inside the field when it's empty
{{anch("readonly")}}A Boolean attribute controlling whether or not the value is read-only
{{anch("step")}}A stepping interval to use when using up and down arrows to adjust the value, as well as for validation
+ +

{{htmlattrdef("max")}}

+ +

The maximum value to accept for this input. If the {{htmlattrxref("value", "input")}} entered into the element exceeds this, the element fails constraint validation. If the value of the max attribute isn't a number, then the element has no maximum value.

+ +

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

+ +

{{htmlattrdef("min")}}

+ +

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

+ +

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

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "placeholder", 0, 1, 2)}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "readonly", 0, 1, 2)}}

+ +

{{htmlattrdef("step")}}

+ +
+

Атрибут step – это число, которое определяет точность, с которой задаётся значение, или специальное значение any, описанное ниже. Только значения, кратные шагу ({{anch("min")}}, если задано, иначе {{htmlattrxref("value", "input")}}, или подходящее стандартное значение, если ни одно из двух не задано) будут корректными.

+ +

Строковое значение any означает, что никакое значение шага не задано и допустимо любое значение (в пределах других ограничений, таких как {{anch("min")}} и {{anch("max")}}).

+ +
+

Примечание: Когда значение, введённое пользователем, не подходит под заданное значение шага, {{Glossary("user agent")}} может округлить его до ближайшего допустимого значения с приоритетом в большую сторону в том случае, если значение находится ровно посередине шага.

+
+
+ +

Стандартное значение шага для поля ввода number – это 1, что позволяет вводить только целые числа, если только не задать значение шага нецелым числом.

+ +

Using number inputs

+ +

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

+ +
+

Important: Bear in mind that logically you should not be able to enter characters inside a number of input other than numbers. There seems to be some disagreement about this among browsers; see {{bug(1398528)}}.

+
+ +
+

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

+
+ +

Mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value. The following screenshot is taken from Firefox for Android:

+ +

+ +

A simple number input

+ +

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

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

{{EmbedLiveSample('A_simple_number_input', 600, 40)}}

+ +

A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the {{htmlattrxref("required", "input")}} attribute is used, the input is no longer considered valid when empty.

+ +
+

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

+
+ +

Placeholders

+ +

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

+ +

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

+ +
<input type="number" placeholder="Multiple of 10">
+ +

{{EmbedLiveSample('Placeholders', 600, 40)}}

+ +

Controlling step size

+ +

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

+ +
<input type="number" placeholder="multiple of 10" step="10">
+ +

{{EmbedLiveSample('Controlling_step_size', 600, 40)}}

+ +

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

+ +

Specifying minimum and maximum values

+ +

You can use the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes to specify a minimum and maximum value that the field can have. For example, let's give our example a minimum of 0, and a maximum of 100:

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

{{EmbedLiveSample('Specifying_minimum_and_maximum_values', 600, 40)}}

+ +

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

+ +

Allowing decimal values

+ +

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

+ +
<input type="number" placeholder="1.0" step="0.01" min="0" max="10">
+ +

{{EmbedLiveSample("Allowing_decimal_values", 600, 40)}}

+ +

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

+ +

Controlling input size

+ +

{{HTMLElement("input")}} elements of type number don't support form sizing attributes such as {{htmlattrxref("size", "input")}}. You'll have to resort to CSS to change the size of these controls.

+ +

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

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

Then we add some CSS to narrow the width of the element with the ID number:

+ +
#number {
+  width: 3em;
+}
+ +

The result looks like this:

+ +

{{EmbedLiveSample('Controlling_input_size', 600, 40)}}

+ +

Offering suggested values

+ +

You can provide a list of default options from which the user can select by specifying the {{htmlattrxref("list", "input")}} attribute, which contains as its value the ID of a {{HTMLElement("datalist")}}, which in turn contains one {{HTMLElement("option")}} element per suggested value; each option's value is the corresponding suggested value for the number entry box.

+ +
<input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers">
+<span class="validity"></span>
+
+<datalist id="defaultNumbers">
+  <option value="10045678">
+  <option value="103421">
+  <option value="11111111">
+  <option value="12345678">
+  <option value="12999922">
+</datalist>
+ +

{{EmbedLiveSample("Offering_suggested_values", 600, 40)}}

+ +
+

Use of the {{htmlattrxref("list", "input")}} attribute with number inputs is not supported in all browsers. It works in Chrome and Opera, for example, but not in Firefox.

+
+ +

Validation

+ +

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

+ + + +

The following example exhibits all of the above features, as well as using some CSS to display valid and invalid icons when the input value is valid/invalid:

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

{{EmbedLiveSample("Validation", 600, 80)}}

+ +

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

+ +

The CSS applied to this example is as follows:

+ +
div {
+  margin-bottom: 10px;
+}
+
+input:invalid+span:after {
+  content: '✖';
+  padding-left: 5px;
+}
+
+input:valid+span:after {
+  content: '✓';
+  padding-left: 5px;
+}
+ +

Here we use the {{cssxref(":invalid")}} and {{cssxref(":valid")}} pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent {{htmlelement("span")}} element, indicating if the current value is valid. We put it on a separate <span> element for added flexibility; some browsers don't display generated content very effectively on some types of form inputs (read for example the section on <input type="date"> validation).

+ +
+

Important: HTML form validation is not a substitute for server-side scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).

+
+ +

Pattern validation

+ +

<input type="number"> elements do not support use of the {{htmlattrxref("pattern", "input")}} attribute for making entered values conform to a specific regex pattern. The rationale for this is that number inputs won't be valid if they contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes, as explained above.

+ +

Examples

+ +

We've already covered the fact that by default, the increment is 1, and you can use the {{htmlattrxref("step", "input")}} attribute to allow decimal inputs. Let's take a closer look. In the following example we've set up a form for entering the user's height; it defaults to accepting a height in meters, but you can click the relevant button to change the form to accept feet and inches instead. The input for the height in meters accepts decimals to two places.

+ +

{{EmbedLiveSample("Examples", 600, 100)}}

+ +

The HTML looks like this:

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

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

+ +

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

+ +

Now on to the CSS — this looks very similar to the validation styling we saw before; nothing remarkable here:

+ +
div {
+  margin-bottom: 10px;
+  position: relative;
+}
+
+input[type="number"] {
+  width: 100px;
+}
+
+input + span {
+  padding-right: 30px;
+}
+
+input:invalid+span:after {
+  position: absolute;
+  content: '✖';
+  padding-left: 5px;
+}
+
+input:valid+span:after {
+  position: absolute;
+  content: '✓';
+  padding-left: 5px;
+}
+ +

And finally, the JavaScript:

+ +
var metersInputGroup = document.querySelector('.metersInputGroup');
+var feetInputGroup = document.querySelector('.feetInputGroup');
+var metersInput = document.querySelector('#meters');
+var feetInput = document.querySelector('#feet');
+var inchesInput = document.querySelector('#inches');
+var switchBtn = document.querySelector('input[type="button"]');
+
+switchBtn.addEventListener('click', function() {
+  if(switchBtn.getAttribute('class') === 'meters') {
+    switchBtn.setAttribute('class', 'feet');
+    switchBtn.value = 'Enter height in meters';
+
+    metersInputGroup.style.display = 'none';
+    feetInputGroup.style.display = 'block';
+
+    feetInput.setAttribute('required', '');
+    inchesInput.setAttribute('required', '');
+    metersInput.removeAttribute('required');
+
+    metersInput.value = '';
+  } else {
+    switchBtn.setAttribute('class', 'meters');
+    switchBtn.value = 'Enter height in feet and inches';
+
+    metersInputGroup.style.display = 'block';
+    feetInputGroup.style.display = 'none';
+
+    feetInput.removeAttribute('required');
+    inchesInput.removeAttribute('required');
+    metersInput.setAttribute('required', '');
+
+    feetInput.value = '';
+    inchesInput.value = '';
+  }
+});
+ +

After declaring a few variables, we add an event listener to the button to control the switching mechanism. This is pretty simple, mostly involving changing over the button class and label, and updating the display values of the two sets of inputs when the button is pressed. Note that we're not converting back and forth between meters and feet/inches here, which a real-life web application would probably do.

+ +
+

Note that when the user clicks the button, we remove the required attribute(s) from the input(s) we are hiding, and empty the value attribute(s). This is so that we can submit the form if both input sets aren't filled in, and won't submit data that we didn't mean to submit. If we didn't do this, you'd have to fill in both feet/inches and meters to submit the form!

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'forms.html#number-state-(type=number)', '<input type="number">')}}{{Spec2('HTML WHATWG')}}Initial definition
{{SpecName('HTML5.1', 'sec-forms.html#number-state-typenumber', '<input type="number">')}}{{Spec2('HTML5.1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.input.input-number")}}

+ +

See also

+ + diff --git a/files/ru/web/html/element/input/password/index.html b/files/ru/web/html/element/input/password/index.html new file mode 100644 index 0000000000..eb87000912 --- /dev/null +++ b/files/ru/web/html/element/input/password/index.html @@ -0,0 +1,614 @@ +--- +title: +slug: Web/HTML/Element/Input/password +tags: + - Element + - HTML + - Веб + - Пароль + - Формы +translation_of: Web/HTML/Element/input/password +--- +
{{HTMLRef}}
+ +

{{HTMLElement("input")}} элементы типа "password" предоставляют пользователю возможность безопасного ввода пароль. Элемент представлен как однострочный текстовый редактор, в котором текст затенен, чтобы его нельзя было прочитать, как правило, путем замены каждого символа другим символом, таким как звездочка ("*") или точка ("•"). Этот символ будет меняться в зависимости от {{Glossary("user agent")}} и {{Glossary("OS")}}.

+ +

Особенности работы процесса ввода могут отличаться от браузера к браузеру; мобильные устройства, например, часто отображают вводимый символ на мгновение, прежде чем закрывать его, чтобы позволить пользователю быть уверенным, что они нажали клавишу, которую они хотели нажать; это полезно, учитывая небольшой размер клавиш и легкость, с которой может быть нажата неправильная, особенно на виртуальных клавиатурах.

+ +
+

Любые формы, содержащие конфиденциальную информацию, такую ​​как пароли (например, формы входа), должны обслуживаться через HTTPS; В Firefox теперь реализованы несколько механизмов для предупреждения от небезопасных форм входа в систему - см. Небезопасные пароли. Другие браузеры также реализуют аналогичные механизмы.

+
+ +
+
<input id="userPassword" type="password">
+
+ +

{{EmbedLiveSample("Basic_example", 600, 40)}}

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}{{domxref("DOMString")}} представляет пароль или пустую строку
События{{event("change")}} и {{event("input")}}
Общие поддерживаемые атрибуты{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("inputmode", "input")}}, {{htmlattrxref("maxlength", "input")}}, {{htmlattrxref("minlength", "input")}}, {{htmlattrxref("pattern", "input")}}, {{htmlattrxref("placeholder", "input")}}, {{htmlattrxref("readonly", "input")}}, {{htmlattrxref("required", "input")}}, and {{htmlattrxref("size", "input")}}
IDL атрибутыselectionStart, selectionEnd, selectionDirection, и value
Методы{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}, и {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}
+ +

Значения

+ +

Атрибут {{htmlattrxref("value", "input")}} содержит {{domxref("DOMString")}} , значение которого является текущим содержимым элемента редактирования текста, используемого для ввода пароля. Если пользователь еще ничего не указал, это значение представляет собой пустую строку (""). Если указано свойство {{htmlattrxref("required")}}, то поле ввода пароля должно содержать значение, отличное от пустой строки, которое должно быть действительным.

+ +

Если указан атрибут {{htmlattrxref("pattern", "input")}}, содержимое элемента управления "password" считается действительным только в том случае, если значение проходит проверку; см. {{anch("Validation")}} для получения дополнительной информации.

+ +
+

Символы строки (U+000A) и возврата каретки(U+000D) недопустимы в значении поля "password". При вставке пароля, возвращаемые символы удаляются из значения.

+
+ +

Использование полей ввода пароля

+ +

Поля ввода пароля обычно работают так же, как и другие текстовые поля ввода; основное отличие состоит в том, чтобы скрывать введенный контент, чтобы люди, не знакомые с пользователем, не могли прочитать его пароль.

+ +

Простое поле ввода пароля

+ +

Здесь мы видим самый простое поле ввода пароля, с меткой, установленной с помощью элемента {{HTMLElement("label")}}.

+ +
<label for="userPassword">Пароль:</label>
+<input id="userPassword" type="password">
+ +

{{EmbedLiveSample("A_simple_password_input", 600, 40)}}

+ +

Поддержка автозаполнения

+ +

Чтобы менеджер паролей пользователя автоматически вводил пароль, укажите атрибут {{htmlattrxref("autocomplete", "input")}}. Для паролей должно быть одно из следующих значений:

+ +
+
"on"
+
Разрешить браузеру или менеджеру паролей автоматически заполнять поле пароля. Это не так информативно, как использование "current-password" или "new-password".
+
"off"
+
Запрещает браузеру или менеджеру паролей автоматически заполнять поле пароля.
+
"current-password"
+
Разрешить браузеру или менеджеру паролей вводить текущий пароль для сайта. Это дает больше информации, чем "on", так как позволяет браузеру или менеджеру паролей знать, что в настоящее время известен пароль для сайта в поле, а не используется новый.
+
"new-password"
+
Разрешить браузеру или менеджеру паролей автоматически вводить новый пароль для сайта. Он может быть автоматически сгенерирован на основе других атрибутов элемента управления или может просто указать браузеру представить виджет «предлагаемого нового пароля».
+
+ +
+
<label for="userPassword">Пароль:</label>
+<input id="userPassword" type="password" autocomplete="current-password">
+
+ +

{{EmbedLiveSample("Autocomplete_sample1", 600, 40)}}

+ +

Обязательное заполнение пароля

+ +

Чтобы сообщить браузеру пользователя, что поле пароля должно иметь действительное значение перед отправкой формы, просто укажите Boolean атрибут {{htmlattrxref("required", "input")}}.

+ +
<label for="userPassword">Пароль:</label>
+<input id="userPassword" type="password" required>
+ +

{{EmbedLiveSample("Making_the_password_mandatory", 600, 40)}}

+ +

Указание режима ввода

+ +

Если ваше приложение лучше обслуживается с использованием другого режима ввода, чем по умолчанию, вы можете использовать атрибут {{htmlattrxref("inputmode", "input")}} для определенного запроса. Наиболее очевидным вариантом использования является то, что ваше приложение использует в качестве пароля числовое значение (например, ПИН). Например, мобильные устройства с виртуальными клавиатурами могут переключаться на макет цифровой клавиатуры вместо полной клавиатуры, чтобы облегчить ввод пароля.

+ +
<label for="pin">ПИН:</label>
+<input id="pin" type="password" inputmode="numeric">
+ +

{{EmbedLiveSample("Specifying_an_input_mode", 600, 40)}}

+ +

Настройка длины пароля

+ +

Как обычно, вы можете использовать атрибуты {{htmlattrxref("minlength", "input")}} и {{htmlattrxref("maxlength", "input")}}, чтобы установить минимальную и максимальную допустимую длину пароля , Этот пример дополняет предыдущий, указав, что PIN-код пользователя должен быть не менее четырех и не более восьми цифр. Атрибут {{htmlattrxref("size", "input")}} используется для обеспечения того, чтобы элемент управления ввода пароля имел ширину в восемь символов.

+ +
<label for="pin">ПИН:</label>
+<input id="pin" type="password" inputmode="numeric" minlength="4"
+       maxlength="8" size="8">
+ +

{{EmbedLiveSample("Setting_length_requirements", 600, 40)}}

+ +

Выделение текста

+ +

Как и другие элементы управления текстовой записью, вы можете использовать метод {{domxref("HTMLInputElement.select", "select()")}} для выбора всего текста в поле пароля.

+ +

HTML

+ +
<label for="userPassword">Пароль</label>
+<input id="userPassword" type="password" size="12">
+<button id="selectAll">Выделить все</button>
+
+ +

JavaScript

+ +
document.getElementById("selectAll").onclick = function(event) {
+  document.getElementById("userPassword").select();
+}
+ +

Результат

+ +

{{EmbedLiveSample("Selecting_text", 600, 40)}}

+ +

Вы также можете использовать {{domxref("HTMLInputElement.selectionStart", "selectionStart")}} и {{domxref("HTMLInputElement.selectionEnd", "selectionEnd")}}, чтобы получить (или установить), какой диапазон символов в элементе управления, и {{domxref("HTMLInputElement.selectionDirection", "selectionDirection")}}, чтобы узнать, какой выбор направления произошел (или будет расширен в зависимости от вашей платформы, см. его документацию для объяснения) , Однако, учитывая, что текст затенен, их полезность несколько ограничена.

+ +

Валидация

+ +

Если ваше приложение имеет ограничения по набору символов или любые другие требования для фактического содержимого введенного пароля, вы можете использовать атрибут {{htmlattrxref("pattern", "input")}}, чтобы установить регулярное выражение, чтобы автоматически гарантировать, что ваши пароли соответствуют этим требованиям.

+ +

В этом примере допустимы только значения, состоящие как минимум из четырех и не более восьми шестнадцатеричных цифр.

+ +
+
<label for="hexId">Hex ID:</label>
+<input id="hexId" type="password" pattern="[0-9a-fA-F]{4,8}"
+       title="Enter an ID consisting of 4-8 hexadecimal digits">
+
+ +

{{EmbedLiveSample("Validation_sample1", 600, 40)}}

+ +
+
{{htmlattrdef("disabled")}}
+
+

Этот Boolean атрибут указывает, что поле пароля недоступно для взаимодействия. Кроме того, отключенные значения полей не отправляются с формой.

+
+
+ +

Примеры

+ +

Запрос номера социального страхования

+ +

В этом примере принимается только ввод, который соответствует формату действительного номера социального страхования Соединенных Штатов. Эти цифры, используемые для целей налогообложения и идентификации в США, представлены в форме «123-45-6789». Также существуют различные правила, для которых допустимы значения в каждой группе.

+ +

HTML

+ +
<label for="ssn">SSN:</label>
+<input type="password" id="ssn" inputmode="number" minlength="9" maxlength="12"
+    pattern="(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}"
+    required autocomplete="off">
+<br>
+<label for="ssn">Value:</label>
+<span id="current"></span>
+ +

Здесь используется {{htmlattrxref("pattern", "input")}} , который ограничивает введенное значение строками, представляющими номера юридической информации Социальной защиты. Очевидно, что это регулярное выражение не гарантирует действительный SSN, но гарантирует, что число может быть единым; он обычно избегает недопустимых значений. Кроме того, он позволяет разделять три группы цифр пробелом, тире ("-") или ничем.

+ +

В {{htmlattrxref("inputmode", "input")}} установлено значение "number", чтобы побудить устройства с виртуальными клавиатурами переключаться на макет цифровой клавиатуры для облегчения ввода. Для атрибутов {{htmlattrxref("minlength", "input")}} и {{htmlattrxref("maxlength", "input")}} установлено значение 9 и 12 соответственно, чтобы требовалось, чтобы значение было не менее девяти и не более 12 символов (первый не разделяет символы между группами цифр и последними с ними). Атрибут {{htmlattrxref("required", "input")}} используется для указания того, что этот элемент управления должен иметь значение. Наконец, {{htmlattrxref("autocomplete", "input")}} установлен "off", чтобы избежать попыток установить пароли менеджеров паролей.

+ +

JavaScript

+ +
var ssn = document.getElementById("ssn");
+var current = document.getElementById("current");
+
+ssn.oninput = function(event) {
+  current.innerHTML = ssn.value;
+}
+ +

Результат

+ +

{{EmbedLiveSample("Requesting_a_Social_Security_number", 600, 60)}}

+ +

Спецификация

+ + + + + + + + + + + + + + + + + + + + + +
СпецификацияСтатусКомментарий
{{SpecName('HTML WHATWG', 'forms.html#password-state-(type=password)', '<input type="password">')}}{{Spec2('HTML WHATWG')}}Начальное определение
{{SpecName('HTML5.1', 'forms.html#password-state-(type=password)', '<input type="password">')}}{{Spec2('HTML5.1')}}Начальное определение
+ +

Совместимость с браузером

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.7")}}21.01.0
accesskey1.0{{CompatVersionUnknown}}61.0{{CompatUnknown}}
autocomplete17.0{{CompatGeckoDesktop("2.0")}}59.65.2
autofocus5.0{{CompatGeckoDesktop("2.0")}}109.65.0
disabled1.0{{CompatGeckoDesktop("1.7")}}[4]61.01.0
form9.0{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}10.62{{CompatUnknown}}
formaction9.0{{CompatGeckoDesktop("2.0")}}1010.625.2
formenctype9.0{{CompatGeckoDesktop("2.0")}}1010.62{{CompatUnknown}}
formmethod9.0{{CompatGeckoDesktop("2.0")}}1010.625.2
formnovalidate5.0[1]{{CompatGeckoDesktop("2.0")}}1010.62{{CompatUnknown}}
formtarget9.0{{CompatGeckoDesktop("2.0")}}1010.625.2
inputmode{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
maxlength1.0{{CompatGeckoDesktop("1.7")}}21.01.0
minlength40.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
name1.0{{CompatGeckoDesktop("1.7")}}21.01.0
pattern5.0{{CompatGeckoDesktop("2.0")}}109.6{{CompatNo}}
placeholder10.0{{CompatGeckoDesktop("2.0")}}1011.005.0
readonly1.0{{CompatGeckoDesktop("1.7")}}6[2] 1.01.0
required5.0
+ 10[3]
{{CompatGeckoDesktop("2.0")}}109.6{{CompatNo}}
size1.0{{CompatGeckoDesktop("1.7")}}21.01.0
Crossed out lock in address bar to indicate insecure login pageImplementing something similar{{CompatGeckoDesktop("51")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Message displayed next to password field to indicate insecure login page, plus autofill disabled{{CompatNo}}{{CompatGeckoDesktop("52")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChrome mobileFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
accesskey{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
autocomplete{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autofocus3.2{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
disabled{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
form{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
formaction{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}10.625.0
formenctype{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
formmethod{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}10.625.0
formnovalidate{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}10.62{{CompatUnknown}}
formtarget{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}10.625.0
inputmode{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
maxlength{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
minlength{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}27.0{{CompatUnknown}}
name{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
pattern{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
placeholder2.3{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}11.104
required{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
size{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Crossed out lock in address bar to indicate insecure login pageImplementing something similar{{CompatGeckoMobile("51")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Message displayed next to password field to indicate insecure login page, plus autofill disabled{{CompatNo}}{{CompatGeckoMobile("52")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

 

+ +

[1] В версии 6.0 он работал только с типом документа HTML5, поддержка проверки в 7.0 была отключена и повторно включена в 10.0.

+ +

[2] Отсутствует для type="checkbox" и type="radio".

+ +

[3] Поддерживается для элемента {{HTMLElement("select")}}.

+ +

[4] Firefox, в отличие от других браузеров, по умолчанию pсохраняет состояние динамического отключения и (если применимо) динамическую проверку из <input> для загрузки страницы. Установка значения атрибута {{htmlattrxref("autocomplete","input")}} в off отключает эту функцию; это работает, даже если атрибут {{htmlattrxref("autocomplete","input")}} обычно не применяется к <input> в силу его {{htmlattrxref("type","input")}}. Смотри {{bug(654072)}}.

diff --git a/files/ru/web/html/element/input/radio/index.html b/files/ru/web/html/element/input/radio/index.html new file mode 100644 index 0000000000..dd2c1e384e --- /dev/null +++ b/files/ru/web/html/element/input/radio/index.html @@ -0,0 +1,377 @@ +--- +title: +slug: Web/HTML/Element/Input/radio +tags: + - HTML + - Input + - Reference + - form + - radio button + - Варианты + - Группа радиокнопок + - Радиокнопка + - Справка + - Ссылки +translation_of: Web/HTML/Element/input/radio +--- +
{{HTMLRef}}
+ +

Атрибут type тега <input> со значением radio обычно используется для создания группы радиокнопок (переключателей), описывающих набор взаимосвязанных параметров. Одновременно пользователь может выбрать лишь одну радиокнопку из предложенных. Радиокнопки обычно отображаются как небольшие кружки, которые заполняются или подсвечиваются при наведении.

+ +
+
<input type="radio" id="radioButton">
+ +

{{ EmbedLiveSample('Basic_example', 600, 30) }}

+ +

Исходный код к данному интерактивному примеру находиться на GitHub репозитории. Если вы желаете внести свой вклад в проект интерактивных примеров, то склонируйте удаленный репозиторий https://github.com/mdn/interactive-examples и отправьте нам запрос на включение сделанных вами изменений «pull request».

+ +

Радиокнопки называются так потому, что выглядят и функционируют в схожей манере с кнопками старомодных радиоприёмников, подобных представленному ниже. 

+ +

Shows what radio buttons looked like in the olden days.

+
+ +
+

Примечание: Чекбоксы похожи на радиокнопки, но с одним важным отличием: радиокнопки предназначены для выбора одного значения из предложенных, в то время как чекбоксы позволяют "включать" и "выключать"  значения. Если существует несколько элементов управления, то с помощью радиокнопок пользователь сможет выбрать лишь один из них, а чекбоксы позволят выбрать несколько значений одновременно.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}{{domxref("Строка DOM")}} отображающая значение радиокнопки
События{{event("change")}} и {{event("input")}}
Универсальные атрибуты{{htmlattrxref("checked", "input")}}
Атрибуты IDLchecked и value
Методы{{domxref("HTMLInputElement.select", "select()")}}
+ +

Атрибут value 

+ +

Атрибут value - это {{domxref("строка DOM")}}, содержащая значение радиокнопки. Это значение никогда не показывается пользователю его веб-браузером. Атрибут value используется для того, чтобы точно определить какая из радиокнопок была выбрана пользователем.

+ +

Создание группы радиокнопок

+ +

Группа радиокнопок определяется путём присвоения каждой радиокнопке в данной группе одного и того же значения атрибута ({{htmlattrxref("name", "input")}}). Выбор любой радиокнопки в этой группе автоматически отменяет выбор другой радиокнопки в той же группе. 

+ +

Вы можете создать любое количество групп радиокнопок, если каждой из этих групп будет присвоено своё уникальное значение атрибута name.

+ +

Например, если в Вашей форме необходимо запросить  предпочитаемый способ контакта с пользователем, то Вы можете создать три радиокнопки с name= "contact" , но с разными value = "email", value ="phone" и value =  "mail" соответственно. Пользователь не видит атрибуты name  и value (если только Вы не добавляете код для их отображения).

+ +

HTML будет выглядеть следующим образом:

+ +
<form>
+  <p>Please select your preferred contact method:</p>
+  <div>
+    <input type="radio" id="contactChoice1"
+     name="contact" value="email">
+    <label for="contactChoice1">Email</label>
+
+    <input type="radio" id="contactChoice2"
+     name="contact" value="phone">
+    <label for="contactChoice2">Phone</label>
+
+    <input type="radio" id="contactChoice3"
+     name="contact" value="mail">
+    <label for="contactChoice3">Mail</label>
+  </div>
+  <div>
+    <button type="submit">Submit</button>
+  </div>
+</form>
+ +

Здесь Вы видите три радиокнопки, каждая из которых имеет атрибут name  со значением "contact" и уникальный атрибут value, который однозначно идентифицирует эту радиокнопку в данной группе. Каждой радиокнопке присвоен уникальный {{domxref("Element.id", "id")}},  связанный с тегом {{HTMLElement("label")}} через атрибут {{htmlattrxref("for", "label")}}  для установления связи между конкретной меткой и конкретной радиокнопкой. 

+ +

Вы можете опробовать этот код здесь: 

+ +

{{ EmbedLiveSample('Defining_a_radio_group', 600, 130) }}

+ +

Представление данных группы радиокнопок

+ +

Когда представленная выше форма отправляется на сервер с информацией о выбранной радиокнопке,  то её данные  включают запись в виде "contact=name". Например, если пользователь кликает на радиокнопку "Phone", а затем отправляет форму на сервер, данные формы будут включать в себя строку "contact=phone".

+ +

Если Вы пренебрежёте атрибутом value в  Вашем HTML, то отправленные данные просто присвоят данной группе значение "on".  То есть, если пользователь кликнет на радиокнопку "Phone" и отправит форму, итоговые данные отобразятся как  "contact=on" и будут абсолютно бесполезны. Поэтому никогда не забывайте указывать атрибут value!

+ +
+

Примечание: Если в отправленной форме не была выбрана ни одна радиокнопка, то группа радиокнопок вообще не будет включать в себя никакие данные, так как отсутствуют значения для отправки.

+
+ +

Поскольку отправлять пустую форму в большинстве случаев не имеет никакого смысла, то разумно оставлять одну радиокнопку активированной по умолчанию с помощью атрибута "checked". Смотрите здесь {{anch("Selecting a radio button by default")}}.

+ +

Давайте добавим немного кода в наш пример для того, чтобы изучить данные, полученные из этой формы. HTML изменяется путём добавления блока {{HTMLElement("pre")}} для вывода данных формы. 

+ +
<form>
+  <p>Please select your preferred contact method:</p>
+  <div>
+    <input type="radio" id="contactChoice1"
+           name="contact" value="email">
+    <label for="contactChoice1">Email</label>
+    <input type="radio" id="contactChoice2"
+           name="contact" value="phone">
+    <label for="contactChoice2">Phone</label>
+    <input type="radio" id="contactChoice3"
+           name="contact" value="mail">
+    <label for="contactChoice3">Mail</label>
+  </div>
+  <div>
+    <button type="submit">Submit</button>
+  </div>
+</form>
+<pre id="log">
+</pre>
+
+ +

Затем добавим немного JavaScript. Установим слушателя для события {{event("submit")}}, которая будет отправляться при клике пользователя на кнопку "Отправить":

+ +
var form = document.querySelector("form");
+var log = document.querySelector("#log");
+
+form.addEventListener("submit", function(event) {
+  var data = new FormData(form);
+  var output = "";
+  for (const entry of data) {
+    output = entry[0] + "=" + entry[1] + "\r";
+  };
+  log.innerText = output;
+  event.preventDefault();
+}, false);
+ +

Опробуйте этот пример и убедитесь, что для группы радиокнопок  "contact"  будет только один результат.

+ +

{{EmbedLiveSample("Data_representation_of_a_radio_group", 600, 130)}}

+ +

Использование радиокнопок

+ +

Мы уже осветили основные моменты работы с радиокнопками выше. Давайте рассмотрим другие распространенные  функции и методы, связанные с использованием радиокнопок, о которых Вам нужно знать.

+ +

Выбор радиокнопки по умолчанию

+ +

Чтобы установить радиокнопку как выбранную по умолчанию, Вам необходимо подключить атрибут checked, как показано ниже в немного изменённой версии предыдущего примера.

+ +
<form>
+  <p>Please select your preferred contact method:</p>
+  <div>
+    <input type="radio" id="contactChoice1"
+     name="contact" value="email" checked>
+    <label for="contactChoice1">Email</label>
+
+    <input type="radio" id="contactChoice2"
+     name="contact" value="phone">
+    <label for="contactChoice2">Phone</label>
+
+    <input type="radio" id="contactChoice3"
+     name="contact" value="mail">
+    <label for="contactChoice3">Mail</label>
+  </div>
+  <div>
+    <button type="submit">Submit</button>
+  </div>
+</form>
+ +

{{ EmbedLiveSample('Selecting_a_radio_button_by_default', 600, 130) }}

+ +

В данном случае первая радиокнопка будет выбрана по умолчанию.

+ +
+

Примечание: Если Вы устанавливаете атрибут checked более чем на одну кнопку, то стоит иметь в виду, что каждый последующий атрибут checked отменяет предыдущий, то  есть как отмеченная будет выбрана последняя радиокнопка с атрибутом checked. Это происходит потому, что в каждой группе радиокнопок одновременно может быть выбрана только одна кнопка, и браузер автоматически отменяет другие выбранные до этого радиокнопки.

+
+ +

Providing a bigger hit area for your radio buttons

+ +

В примерах, представленных выше, Вы могли заметить, что можно выбрать радиокнопку, кликнув как на соединённый с ней элемент  {{htmlelement("label")}}, так и на саму кнопку. Это действительно полезная функция HTML-форм, которая облегчает пользователям выбор нужной опции, особенно на устройствах с небольшим экраном, таких как смартфоны.  Помимо специальных возможностей, это другая веская причина для правильного использования элементов  <label>  в Ваших формах.

+ +

Валидация формы

+ +

Радиокнопки не участвуют в проверке ограничений, так как у них нет реальных значений для ограничения.

+ +

Установка стилей радиокнопок

+ +

Следующий пример отображает немного более проработанную версию примера, который мы использовали на протяжении всей статьи,  с некоторыми дополнительными стилями и с лучшей семантикой, установленной с помощью специализированных элементов.

+ +

HTML будет выглядеть следующим образом:

+ +
<form>
+  <fieldset>
+    <legend>Please select your preferred contact method:</legend>
+    <div>
+      <input type="radio" id="contactChoice1"
+       name="contact" value="email" checked>
+      <label for="contactChoice1">Email</label>
+
+      <input type="radio" id="contactChoice2"
+       name="contact" value="phone">
+      <label for="contactChoice2">Phone</label>
+
+      <input type="radio" id="contactChoice3"
+       name="contact" value="mail">
+      <label for="contactChoice3">Mail</label>
+    </div>
+    <div>
+      <button type="submit">Submit</button>
+    </div>
+  </fieldset>
+</form>
+ +

Здесь не так много нового, кроме дополнения в виде элементов {{htmlelement("fieldset")}} и {{htmlelement("legend")}}, которые позволяют сгруппировать элементы форм между собой функционально и семантически.

+ +

CSS будет выглядеть так:

+ +
html {
+  font-family: sans-serif;
+}
+
+div:first-of-type {
+  display: flex;
+  align-items: flex-start;
+  margin-bottom: 5px;
+}
+
+label {
+  margin-right: 15px;
+  line-height: 32px;
+}
+
+input {
+  -webkit-appearance: none;
+  -moz-appearance: none;
+  appearance: none;
+
+  border-radius: 50%;
+  width: 16px;
+  height: 16px;
+
+  border: 2px solid #999;
+  transition: 0.2s all linear;
+  outline: none;
+  margin-right: 5px;
+
+  position: relative;
+  top: 4px;
+}
+
+input:checked {
+  border: 6px solid black;
+}
+
+button,
+legend {
+  color: white;
+  background-color: black;
+  padding: 5px 10px;
+  border-radius: 0;
+  border: 0;
+  font-size: 14px;
+}
+
+button:hover,
+button:focus {
+  color: #999;
+}
+
+button:active {
+  background-color: white;
+  color: black;
+  outline: 1px solid black;
+}
+ +

Самым примечательным здесь является использование свойства {{cssxref("appearance")}} с использованием префиксов некоторых браузеров. По умолчанию радиокнопки (и чекбоксы) уже имеют собственные стили в каждой операционной системе. Придав свойству appearance значение none, Вы можете отменить все "родные" настройки стилей операционной системы и создать свои собственные. Здесь мы использовали свойства {{cssxref("border")}} и  {{cssxref("border-radius")}}, а также свойство {{cssxref("transition")}} для создания хорошо анимированного выбора радиокнопок. Заметьте также, что псевдокласс {{cssxref(":checked")}} используется для указания стилей внешнего вида кнопок при их выборе.

+ +

Стоит иметь в виду, что свойство  appearance неплохо работает для создания простых стилей, но имеет тенденцию вести себя несколько непоследовательно в некоторых браузерах и полностью не работает в Internet Explorer. Тщательно проверяйте как работает Ваш сайт в каждом браузере! 

+ +

{{ EmbedLiveSample('Styling_radio_inputs', 600, 120) }}

+ +

Обратите внимание, что при клике на радиокнопку, на предыдущей выбранной кнопке появляется мягкий эффект угасания. Кроме того, стиль и окраска легенды и кнопки "Submit" имеет сильный контраст с остальным текстом. Возможно, это не совсем тот эффект, который Вы хотели бы видеть в своём реальном веб-приложении, но этот пример хорошо отображает возможности CSS.

+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', 'forms.html#radio-button-state-(type=radio)', '<input type="radio">')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#radio-button-state-(type=radio)', '<input type="radio">')}}{{Spec2('HTML5 W3C')}}
+ +

Совместимость с браузерами

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Смотрите также

+ + diff --git a/files/ru/web/html/element/input/range/index.html b/files/ru/web/html/element/input/range/index.html new file mode 100644 index 0000000000..b46af66650 --- /dev/null +++ b/files/ru/web/html/element/input/range/index.html @@ -0,0 +1,480 @@ +--- +title: +slug: Web/HTML/Element/Input/range +tags: + - контроллер + - слайдер +translation_of: Web/HTML/Element/input/range +--- +
{{HTMLRef("Input_types")}}
+ +

Элементы {{HTMLElement("input")}} с типом range позволяют пользователю определить числовое значение, которое должно быть в пределах указанного промежутка. Однако, точное значение должно быть не слишком важно. Обычно они представляет собой слайдер или контроллер, но не текстовое поле как {{HTMLElement('input/number', 'number')}}. Так как этот виджет неточен, его не следует использовать, в случае, если важно установить точное значение .

+ +
{{EmbedInteractiveExample("pages/tabbed/input-range.html", "tabbed-standard")}}
+ + + +

Если используемый браузер не поддерживает тип range, он будет отображаться как input{{HTMLElement('input/text', 'text')}}.

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}{{domxref("DOMString")}}, содержащий строковое представление выбранного числового значения; используйте {{domxref("HTMLInputElement.valueAsNumber", "valueAsNumber")}} чтобы получить значение {{jsxref("Number")}}.
События{{event("change")}} и {{event("input")}}
Поддерживаемые общие атрибуты{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("max", "input")}}, {{htmlattrxref("min", "input")}}, and {{htmlattrxref("step", "input")}}
IDL атрибутыlist, value, и valueAsNumber
Методы{{domxref("HTMLInputElement.stepDown", "stepDown()")}} и {{domxref("HTMLInputElement.stepUp", "stepUp()")}}
+ +

Валидация

+ +

Для этого поля нет доступного патерна валидации, но следующая валидация реализованны следующие проверки

+ + + +

+ +

Атрибут {{htmlattrxref("value", "input")}} содержит {{domxref("DOMString")}}, который содержит строковое представление выбранного числа. Значение никогда не является пустой строкой (""). Значение, по умолчанию, находится посередине, между указанными минимальным и максимальным значениями — если максимум оказывается меньше минимума, то значение по умолчанию приравнивается к значению атрибута min. Алгоритм определения значения по умолчанию:

+ +
defaultValue = (rangeElem.max < rangeElem.min) ? rangeElem.min
+               : rangeElem.min + (rangeElem.max - rangeElem.min)/2;
+ +

Если предпринята попытка установить значение меньше минимального, то оно примет значение атрибута min. Аналогично, попытка установить значение больше максимального, приведет к установлению значения равного атрибуту max.

+ +

Дополнительные атрибуты

+ +

В дополнение к атрибутам, общим для всех элементов {{HTMLElement("input")}}, range инпуты предлагают следующие атрибуты:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescription
{{anch("list")}}id элемента <datalist>, который сожержит предопределенные значение (не обязательно)
{{anch("max")}}Максимальное допустимое значение
{{anch("min")}}Минимальное допустимое значение
{{anch("step")}}Шаговый, используемый для пользовательского интерфейса и для проверки
+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "list", 0, 1, 2)}}

+ +

Смотрите управление диапазоном с помощью решетки ниже, для примера того, как параметры диапазона обозначаются в поддерживаемых браузерах.

+ +

{{htmlattrdef("max")}}

+ +

Это значение должно быть больше или равно значению атрибута  min.

+ +

{{htmlattrdef("min")}}

+ +

Наименьшее значение в диапазоне допустимых значений. Если {{htmlattrxref("value", "input")}}, введенный в элемент, меньше этого значения, то элемент не проходит  проверку ограничения. Если значение атрибута min не является числом, то элемент не имеет максимального значения.

+ +

Это значение должно быть меньше или равно значению атрибута max.

+ +

{{htmlattrdef("step")}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/number", "step-include")}}

+ +

По умолчанию шаг для инпута с типом range равен 1, допустим ввод только целых чисел, если  база шага не является целым; например, если вы установили min на -10 и value на 1.5, то step  1 позволит только такие значения как 1.5, 2.5, 3.5,... в положительном направлении и -0.5, -1.5, -2.5,... в отрицательном направлении.

+ +

Не стандартные атрибуты

+ + + + + + + + + + + + + + +
AttributeDescription
{{anch("orient")}}Устанавливает ориентацию слайдера. Firefox only.
+ +
+
{{htmlattrdef("orient")}} {{non-standard_inline}}
+
Похоже на  -moz-orient не стандартное CSS свойство влияющее на {{htmlelement('progress')}} и{{htmlelement('meter')}} элемены, orient атрибут определяем ориентацию слайдера. Значение horizontal, значет что слайдер быдет отображен горизонтально, а vertical- что вертикально .
+
+ +
+

Note: Следующие атрибуты не применимы: acceptaltcheckeddirnameformactionformenctypeformmethodformnovalidateformtargetheightmaxlengthminlengthmultiplepatternplaceholderreadonlyrequiredsizesrc, и width. Каждый из них будет проигнорирован в случаее употребления.

+
+ +

Examples

+ +

Пока тип number позволяет пользователям вводить число с дополнительными ограничениями, заставляя их значения находиться между максимальным и минимальным, он требует, чтобы они вводили определенное значение. Инпут с типом range позволяет вам запрашивать у пользователя значение в тех случаях, когда пользователь не может даже знать - каково выбранное конкретное числовое значение.

+ +

Несколько примеров основный ситуаций, в которых инпуты с range используются:

+ + + +

Как правило, если пользователь в большей степени интересуется процентным значением между минимумом и максимумом, нежели реальным значением, range инпут является отличным решением. Например, в случае с контролем громкости домашнего стерео, обычно пользователь думает "установить громкости наполовину максимума" вместо "установить громкость на 0.5".

+ +

Указание минимума и максимума

+ +

По умолчанию, минимум равен 0, а максимум равен 100. Если вас это не устраивает, вы можете с легкостью указать другие границы, изменив значения атрибутов {{htmlattrxref("min", "input")}} и/или {{htmlattrxref("max", "input")}}. Они могут быть принимать любые значения с плавающей точкой.

+ +

Например, указать диапазон значений между -10 и 10, вы можете, используя:

+ +
<input type="range" min="-10" max="10">
+ +

{{EmbedLiveSample("Specifying_the_minimum_and_maximum", 600, 40)}}

+ +

Настройка детализации значения

+ +

По умолчанию, степень детализации равна 1, тем самым показывая, что значение всегда является целым числом. Вы можете изменить атрибут {{htmlattrxref("step")}} контроля степени детализации. Например, если вам нужно значение между 5 и 10, с точностью до двух знаков после запятой, вы должны установить значение step на 0.01:

+ +
+
<input type="range" min="5" max="10" step="0.01">
+ +

{{EmbedLiveSample("Granularity_sample1", 600, 40)}}

+
+ +

Если вы хотите принять любое значение, независимо от разрядности, вы можете указать значение any для атрибута {{htmlattrxref("step", "input")}}:

+ +
+
<input type="range" min="0" max="3.14" step="any">
+ +

{{EmbedLiveSample("Granularity_sample2", 600, 40)}}

+ +

Этот пример позволяет пользователю выбрать любое значение между 0 и π без ограничений на разрядность.

+
+ +

Добавление хэш-меток и лейблов

+ +

Спецификация HTML дает браузерам некоторую гибкость при представлении диапазонных контроллеров. Нигде эта гибкость не проявляется больше, чем в области хэш-меток и, в меньшей степени, лейблов. Спецификация описывает как добавлять кастомные точки контроллера диапазона, используя атрибут {{htmlattrxref("list", "input")}} и элемент {{HTMLElement("datalist")}}, но не имеет требований или рекомендаций по стандартизации хэш-меток и лейблов по длине контроллера.

+ +

Макеты контроллера диапазона

+ +

Так как браузеры имеют эту гибкость, и на сегодняшний день ни один из них не поддерживает все возможности, определенные HTML, представляем несколько макетов, показывающих как вы можете получить на macOS в браузере, который их поддерживает.

+ +
Недекорированный контроллер даипазона
+ +

Этот результат вы получите, если не укажите атрибут {{htmlattrxref("list", "input")}}, или браузер не будет его поддерживать.

+ + + + + + + + + + + + +
HTMLScreenshot
+
+<input type="range">
+
Screenshot of a plain slider control on macOS
+ +
Контроллер диапазона с хэш-метками
+ +

Контроллер диапазона, использующий атрибут list, указывающий ID {{HTMLElement("datalist")}}, который определяет серию хэш-меток на контроллере. Их одиннадцать, одна на 0% и на каждой отметки 10%. Каждая точка представлена с помощью элемента {{HTMLElement("option")}} с его набором {{htmlattrxref("value", "option")}} значений диапазона, при котором должна быть нарисована метка.

+ + + + + + + + + + + + +
HTMLScreenshot
+
+<input type="range" list="tickmarks">
+
+<datalist id="tickmarks">
+  <option value="0">
+  <option value="10">
+  <option value="20">
+  <option value="30">
+  <option value="40">
+  <option value="50">
+  <option value="60">
+  <option value="70">
+  <option value="80">
+  <option value="90">
+  <option value="100">
+</datalist>
+
+
Screenshot of a plain slider control on macOS
+ +
Контроллер диапазона с хэш-метками и лейблами
+ +

Вы можете добавить лейблы в свой контроллер диапазонов, добавив атрибут {{htmlattrxref("label", "option")}} элементам {{HTMLElement("option")}}, соответствующим значениям, на которых вы бы хотели видеть лейблы.

+ + + + + + + + + + + + +
HTMLScreenshot
+
+<input type="range" list="tickmarks">
+
+<datalist id="tickmarks">
+  <option value="0" label="0%">
+  <option value="10">
+  <option value="20">
+  <option value="30">
+  <option value="40">
+  <option value="50" label="50%">
+  <option value="60">
+  <option value="70">
+  <option value="80">
+  <option value="90">
+  <option value="100" label="100%">
+</datalist>
+
+
Screenshot of a plain slider control on macOS
+ +
+

Примечание: В настоящее время ни один браузер полностью не поддерживает эти возможности. Firefox не поддрживает хэш-метки и лейблы, например, в то время как Chrome поддерживает хэш-метки, но не поддерживает лейблы. Версия 66 (66.0.3359.181) Chrome поддерживает лейблы, но тэг {{htmlelement("datalist")}} должен быть стилизован с помощью  CSS, так как его свойство {{cssxref("display")}} по умолчанию -  none, тем самым скрывая лейблы.

+
+ +

Изменение ориентации

+ +

По умолчанию, если браузер отображает инпут диапозона как слайдер, он отобразит его так чтоб ползунок ездил в право и в лево. Когда поддержка браузерами будет реализованно, можно будет делать слайдер вертикальным, так чтобы ползунок мог ездить вверх и вниз. Ниодин из наиболее используемых браузеров не имплементировал это пока. (Firefox {{bug(981916)}}, Chrome bug 341071). также, возможно, следующий баг под вопросом.

+ +

В реальности, мы можем сделать слайдер вертикальным используя CSS трансформации, или применяя уникальный метод для каждого браузера в отдельности, включая: настройки {{cssxref('appearance')}}  для slider-vertical, использование нестандартной ориентации orient в Firefox,или изменение text direction для Internet Explorer и Edge

+ +

Рассмотрим контроллер диапазона:

+ +
<input type="range" id="volume" min="0" max="11" value="7" step="1">
+ +

{{EmbedLiveSample("Orientation_sample1", 200, 200, "https://mdn.mozillademos.org/files/14983/Orientation_sample1.png")}}

+ +

Это горизонтальный контроллер (по крайне мере на большинстве основных браузеров, другие могут отличаться).

+ +

Standards

+ +

Следуюя спецификации, сделать его вертикальным также просто как добавить CSS, чтобы изменить размеры контроллера, чтобы его высота оказалась больше ширины:

+ +

CSS

+ +
#volume {
+  height: 150px;
+  width: 50px;
+}
+ +

HTML

+ +
<input type="range" id="volume" min="0" max="11" value="7" step="1">
+ +

Результат

+ +

{{EmbedLiveSample("Orientation_sample2", 200, 200, "https://mdn.mozillademos.org/files/14985/Orientation_sample2.png")}}

+ +

К сожалению, большенство браузеров сейчас не поддерживают вертикальные контроллы напрямую.

+ +

transform: rotate(-90deg)

+ +

Но вы, все же, можете сделать вертикльный контролл используя горизонтальный контролл. Самый простой способ - использовать CSS: применяя {{cssxref("transform")}} для поворото элемента на 90 градусов. Посмотрим:

+ +
+

HTML

+ +

В HTML нужно добавить обертку вокруг {{HTMLElement("input")}}  - {{HTMLElement("div")}}, что позволит нам исправить макет после выполнения трансформации (т.к. трансформация автоматически не влияет на макет страницы):

+ +
<div class="slider-wrapper">
+  <input type="range" min="0" max="11" value="7" step="1">
+</div>
+ +

CSS

+ +

Теперь нам нужно немного CSS. Во-первых, это CSS для самой обертки; это указание дисплея и размеров для правильного расположения на странице; по сути, он резервирует область страницы для слайдера, так, чтобы можно было поместить повернутый слайдер в зарезервированном пространстве, не создавая беспорядка.

+ +
.slider-wrapper {
+  display: inline-block;
+  width: 20px;
+  height: 150px;
+  padding: 0;
+}
+
+ +

Затем информация о стиле элемента <input> в зарезервированном пространстве:

+ +
.slider-wrapper input {
+  width: 150px;
+  height: 20px;
+  margin: 0;
+  transform-origin: 75px 75px;
+  transform: rotate(-90deg);
+}
+ +

Размеры контроллера это набор из 150 пикселей длины и 20 пикселей высоты. Маржинги установлены на  0 и {{cssxref("transform-origin")}} смещается в середину пространства, на котором вращается слайдер; поскольку слайдер имеет ширину 150 пикселей, он вращается через прямоугольник по 150 пикселей с каждой стороны. Смещение начала координат на 75px по каждой оси означает, что мы будем вращаться вокруг центра этого пространства. Наконец, мы поварачиваем против часовой стрелки на 90°. Результат: инпут range, который вращается таким образом, что максимальное значение находится сверху, а минимальное снизу.

+ +

{{EmbedLiveSample("Orientation_sample3", 200, 200, "https://mdn.mozillademos.org/files/14987/Orientation_sample3.png")}}

+ +

appearance property

+ +

Свойство {{cssxref('appearance')}} имеет нестандартное значение slider-vertical , которое делает слайдер вертикальным.

+ +

HTML

+ +

Используем тот же HTML что и в предыдущем примере:

+ +
<input type="range" min="0" max="11" value="7" step="1">
+
+ +

CSS

+ +

Берем только те инпуты что иеют тип range:

+ +
input[type="range"] {
+  -webkit-appearance: slider-vertical;
+}
+ +

{{EmbedLiveSample("appearance_property", 200, 200)}}

+ +

orient attribute

+ +

В Firefox, реализованно нестандартное свойство orient.

+ +

HTML

+ +

Используем тот же HTML что и в предыдущем примере и добавляем атрибут со значением vertical:

+ +
<input type="range" min="0" max="11" value="7" step="1" orient="vertical">
+
+ +

{{EmbedLiveSample("orient_attribute", 200, 200)}}

+ +

writing-mode: bt-lr;

+ +

Свойство {{cssxref('writing-mode')}} может быть использовано для специальных эфектов 

+ +

HTML

+ +

Используем тот же HTML что и в предыдущем примере:

+ +
<input type="range" min="0" max="11" value="7" step="1">
+
+ +

CSS

+ +

Берем только те инпуты что иеют тип range, меняем writing mode с default на bt-lr, или bottom-to-top и left-to-right:

+ +
input[type="range"] {
+  writing-mode: bt-lr;
+}
+ +

{{EmbedLiveSample("writing-mode_bt-lr", 200, 200)}}

+ +

Все вместе

+ +

Каждый из вышеперечисленных примеров работает в своем браузере, мы попробуем обьединить все вместе чтоб добится кроссбраузерности решения:

+ +

HTML

+ +

Оставим orient атрибут  со значением vertical для Firefox:

+ +
<input type="range" min="0" max="11" value="7" step="1" orient="vertical">
+
+ +

CSS

+ +

Берем только те инпуты что иеют тип range, меняем writing mode с default на bt-lr, или bottom-to-top и left-to-right, для Edge и Internet Explorer, и обавляем -webkit-appearance: slider-vertical для всех -webkit-based браузеров:

+ +
input[type="range"] {
+  writing-mode: bt-lr;
+  -webkit-appearance: slider-vertical;
+}
+ +

{{EmbedLiveSample("Putting_it_all_together", 200, 200)}}

+
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + +
СпецификацияСтатусКомментарий
{{SpecName('HTML WHATWG', 'forms.html#range-state-(type=range)', '<input type="range">')}}{{Spec2('HTML WHATWG')}}Первое определение
{{SpecName('HTML5.1', 'sec-forms.html#range-state-typerange', '<input type="range">')}}{{Spec2('HTML5.1')}}Первое определение
+ +

Поддержка браузерами

+ + + +

{{Compat("html.elements.input.input-range")}}

+ +

Смотрите также

+ + diff --git a/files/ru/web/html/element/input/search/index.html b/files/ru/web/html/element/input/search/index.html new file mode 100644 index 0000000000..a4307a573b --- /dev/null +++ b/files/ru/web/html/element/input/search/index.html @@ -0,0 +1,467 @@ +--- +title: +slug: Web/HTML/Element/Input/search +translation_of: Web/HTML/Element/input/search +--- +
{{HTMLRef}}
+ +

{{HTMLElement("input")}} элементы с типом search это текстовые поля разработанные для ввода пользователем поисковых запросов. Функциональность идентична элементам с типом text, но может отличаться стилизация за счет {{Glossary("user agent")}}, а также наличием специального не стандартизированного события {{domxref("HTMLElement/search_event", "onsearch")}}.

+ +
{{EmbedInteractiveExample("pages/tabbed/input-search.html", "tabbed-standard")}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}A {{domxref("DOMString")}} representing the value contained in the search field.
Events{{domxref("HTMLElement/change_event", "change")}} and {{domxref("HTMLElement/input_event", "input")}}
Supported Common Attributes{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("maxlength", "input")}}, {{htmlattrxref("minlength", "input")}}, {{htmlattrxref("pattern", "input")}}, {{htmlattrxref("placeholder", "input")}}, {{htmlattrxref("required", "input")}}, {{htmlattrxref("size", "input")}}.
IDL attributesvalue
Methods{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}, {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}.
+ +

Value

+ +

The {{htmlattrxref("value", "input")}} attribute contains a {{domxref("DOMString")}} representing the value contained in the search field. You can retrieve this using the {{domxref("HTMLInputElement.value")}} property in JavaScript.

+ +
searchTerms = mySearch.value;
+
+ +

If no validation constraints are in place for the input (see {{anch("Validation")}} for more details), the value can be any text string or an empty string ("").

+ +

Additional attributes

+ +

In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, search field inputs support the following attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescription
{{anch("list")}}The id of the <datalist> element that contains the optional pre-defined autocomplete options
{{anch("maxlength")}}The maximum number of characters the input should accept
{{anch("minlength")}}The minimum number of characters long the input can be and still be considered valid
{{anch("pattern")}}A regular expression the input's contents must match in order to be valid
{{anch("placeholder")}}An exemplar value to display in the input field whenever it is empty
{{anch("readonly")}}A Boolean attribute indicating whether or not the contents of the input should be read-only
{{anch("size")}}A number indicating how many characters wide the input field should be
{{anch("spellcheck")}}Controls whether or not to enable spell checking for the input field, or if the default spell checking configuration should be used
+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "list", 0, 1, 2)}}

+ +

{{htmlattrdef("maxlength")}}

+ +

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

+ +

The input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long.

+ +

{{htmlattrdef("minlength")}}

+ +

The minimum number of characters (as UTF-16 code units) the user can enter into the search field. 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 search input has no minimum length.

+ +

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

+ +

{{htmlattrdef("pattern")}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "pattern-include")}}

+ +

See the section {{anch("Specifying a pattern")}} for details and an example.

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "placeholder", 0, 1, 2)}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "readonly", 0, 1, 2)}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "size", 0, 1, 2)}}

+ +

{{htmlattrdef("spellcheck")}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "spellcheck-include")}}

+ +

Non-standard attributes

+ +

The following non-standard attributes are available to search input fields. As a general rule, you should avoid using them unless it can't be helped.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescription
{{anch("autocorrect")}}Whether or not to allow autocorrect while editing this input field. Safari only.
{{anch("incremental")}}Whether or not to send repeated {{event("search")}} events to allow updating live search results while the user is still editing the value of the field. WebKit and Blink only (Safari, Chrome, Opera, etc.).
{{anch("mozactionhint")}}A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only.
{{anch("results")}}The maximum number of items that should be displayed in the drop-down list of previous search queries. Safari only.
+ +

{{htmlattrdef("autocorrect")}} {{non-standard_inline}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "autocorrect-include")}}

+ +

{{htmlattrdef("incremental")}} {{non-standard_inline}}

+ +
+

The Boolean attribute incremental is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the {{Glossary("user agent")}} to process the input as a live search. As the user edits the value of the field, the user agent sends {{event("search")}} events to the {{domxref("HTMLInputElement")}} object representing the search box. This allows your code to update the search results in real time as the user edits the search.

+ +

If incremental is not specified, the {{event("search")}} event is only sent when the user explicitly initiates a search (such as by pressing the Enter or Return key while editing the field).

+ +

The search event is rate-limited so that it is not sent more more frequently than an implementation-defined interval.

+
+ +

{{htmlattrdef("mozactionhint")}} {{non-standard_inline}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "mozactionhint-include")}}

+ +

{{htmlattrdef("results")}} {{non-standard_inline}}

+ +
+

The results attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the {{HTMLElement("input")}} element's natively-provided drop-down menu of previous search queries.

+ +

The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser's default maximum number of entries is used.

+
+ +

Using search inputs

+ +

<input> elements of type search are very similar to those of type text, except that they are specifically intended for handling search terms. They are basically equivalent in behavior, but user agents may choose to style them differently by default (and, of course, sites may use stylesheets to apply custom styles to them).

+ +

Basic example

+ +
<form>
+  <div>
+    <input type="search" id="mySearch" name="q">
+    <button>Search</button>
+  </div>
+</form>
+ +

This renders like so:

+ +

{{EmbedLiveSample("Basic_example", 600, 40)}}

+ +

q is the most common name given to search inputs, although it's not mandatory. When submitted, the data name/value pair sent to the server will be q=searchterm.

+ +
+

You must remember to set a {{htmlattrxref("name", "input")}} for your input, otherwise nothing will be submitted.

+
+ +

Differences between search and text types

+ +

The main basic differences come in the way browsers handle them. The first thing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired. The following screenshot comes from Chrome:

+ +

+ +

In addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain. This helps users who tend to do searches on the same or similar search queries over time. This screenshot is from Firefox:

+ +

At this point, let's look at some useful techniques you can apply to your search forms.

+ +

Setting placeholders

+ +

You can provide a useful placeholder inside your search input that could give a hint on what to do using the {{htmlattrxref("placeholder","input")}} attribute. Look at the following example:

+ +
<form>
+  <div>
+    <input type="search" id="mySearch" name="q"
+     placeholder="Search the site...">
+    <button>Search</button>
+  </div>
+</form>
+ +

You can see how the placeholder is rendered below:

+ +

{{EmbedLiveSample("Setting_placeholders", 600, 40)}}

+ +

Search form labels and accessibility

+ +

One problem with search forms is their accessibility; a common design practice is not to provide a label for the search field (although there might be a magnifying glass icon or similar), as the purpose of a search form is normally fairly obvious for sighted users due to placement (this example shows a typical pattern).

+ +

This could, however, cause confusion for screenreader users, since they will not have any verbal indication of what the search input is. One way around this that won't impact on your visual design is to use WAI-ARIA features:

+ + + +

Let's have a look at an example:

+ +
<form role="search">
+  <div>
+    <input type="search" id="mySearch" name="q"
+     placeholder="Search the site..."
+     aria-label="Search through site content">
+    <button>Search</button>
+  </div>
+</form>
+ +

You can see how this is rendered below:

+ +

{{EmbedLiveSample("Search_form_labels_and_accessibility", 600, 40)}}

+ +

There is no visual difference from the previous example, but screenreader users have way more information available to them.

+ +
+

Note: See Signposts/Landmarks for more information about such accessibility features.

+
+ +

Physical input element size

+ +

The physical size of the input box can be controlled using the {{htmlattrxref("size", "input")}} attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the search box is 30 characters wide:

+ +
<form>
+  <div>
+    <input type="search" id="mySearch" name="q"
+    placeholder="Search the site..." size="30">
+    <button>Search</button>
+  </div>
+</form>
+ +

The result is this wider input box:

+ +

{{ EmbedLiveSample('Physical_input_element_size', 600, 40) }}

+ +

Validation

+ +

<input> elements of type search have the same validation features available to them as regular text inputs. It is less likely that you'd want to use validation features in general for search boxes. In many cases, users should just be allowed to search for anything, but there are a few cases to consider, such as searches against data of a known format.

+ +
+

Note: 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 simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.

+
+ +

A note on styling

+ +

There are useful pseudo-classes available for styling valid/invalid form elements: {{cssxref(":valid")}} and {{cssxref(":invalid")}}. In this section, we'll use the following CSS, which will place a check (tick) next to inputs containing valid values, and a cross next to inputs containing invalid values.

+ +
input:invalid ~ span:after {
+    content: '✖';
+    padding-left: 5px;
+    position: absolute;
+}
+
+input:valid ~ span:after {
+    content: '✓';
+    padding-left: 5px;
+    position: absolute;
+}
+ +

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

+ +

Making input required

+ +

You can use the {{htmlattrxref("required", "input")}} attribute as an easy way of making entering a value required before form submission is allowed:

+ +
<form>
+  <div>
+    <input type="search" id="mySearch" name="q"
+    placeholder="Search the site..." required>
+    <button>Search</button>
+    <span class="validity"></span>
+  </div>
+</form>
+ + + +

This renders like so:

+ +

{{ EmbedLiveSample('Making_input_required', 600, 40) }}

+ +

In addition, if you try to submit the form with no search term entered into it, the browser will show a message. The following example is from Firefox:

+ +

form field with attached message that says Please fill out this field

+ +

Different messages will be shown when you try to submit the form with different types of invalid data contained inside the inputs; see the below examples.

+ +

Input value length

+ +

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

+ +

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

+ +
<form>
+  <div>
+    <label for="mySearch">Search for user</label>
+    <input type="search" id="mySearch" name="q"
+    placeholder="User IDs are 4–8 characters in length" required
+    size="30" minlength="4" maxlength="8">
+    <button>Search</button>
+    <span class="validity"></span>
+  </div>
+</form>
+ + + +

This renders like so:

+ +

{{ EmbedLiveSample('Input_value_length', 600, 40) }}

+ +

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

+ +

Specifying a pattern

+ +

You can use the {{htmlattrxref("pattern", "input")}} attribute to specify a regular expression that the inputted value must follow to be considered valid (see Validating against a regular expression for a simple crash course).

+ +

Let's look at an example. Say we wanted to provide a product ID search form, and the IDs were all codes of two letters followed by four numbers. The following example covers it:

+ +
<form>
+  <div>
+    <label for="mySearch">Search for product by ID:</label>
+    <input type="search" id="mySearch" name="q"
+    placeholder="two letters followed by four numbers" required
+    size="30" pattern="[A-z]{2}[0-9]{4}">
+    <button>Search</button>
+    <span class="validity"></span>
+  </div>
+</form>
+ + + +

This renders like so:

+ +

{{ EmbedLiveSample('Specifying_a_pattern', 600, 40) }}

+ +

Examples

+ +

You can see a good example of a search form used in context at our website-aria-roles example (see it live).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'input.html#text-(type=text)-state-and-search-state-(type=search)', '<input type="search">')}}{{Spec2('HTML WHATWG')}}Initial definition
{{SpecName('HTML5.1', 'sec-forms.html#text-typetext-state-and-search-state-typesearch', '<input type="search">')}}{{Spec2('HTML5.1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.input.input-search")}}

+ +

See also

+ + diff --git a/files/ru/web/html/element/input/tel/index.html b/files/ru/web/html/element/input/tel/index.html new file mode 100644 index 0000000000..e13cf8729e --- /dev/null +++ b/files/ru/web/html/element/input/tel/index.html @@ -0,0 +1,523 @@ +--- +title: +slug: Web/HTML/Element/Input/tel +translation_of: Web/HTML/Element/input/tel +--- +
{{HTMLRef}}
+ +

{{HTMLElement("input")}} элемент типа tel используется чтобы разрешить пользователю вводить и редактировать номер телефона. В отличии от<input type="email"> и <input type="url"> , введеное значение не проверяется автоматически по определенном формату, перед тем как форма может быть отправлена , потому что форматы телефонных номеров сильно различаются по всему миру

+ +
{{EmbedInteractiveExample("pages/tabbed/input-tel.html", "tabbed-standard")}}
+ + + +

Despite the fact that inputs of type tel are functionally identical to standard text inputs, they do serve useful purposes; the most quickly apparent of these is that mobile browsers — especially on mobile phones — may opt to present a custom keypad optimized for entering phone numbers. Using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient.

+ +
+

Note: Browsers that don't support type tel fall back to being a standard {{HTMLElement("input/text", "text")}} input.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}A {{domxref("DOMString")}} representing a telephone number, or empty
Events{{event("change")}} and {{event("input")}}
Supported Common Attributes{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("maxlength", "input")}}, {{htmlattrxref("minlength", "input")}}, {{htmlattrxref("pattern", "input")}}, {{htmlattrxref("placeholder", "input")}}, {{htmlattrxref("readonly", "input")}}, and {{htmlattrxref("size", "input")}}
IDL attributeslist, selectionStart, selectionEnd, selectionDirection, and value
Methods{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}, {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}
+ +

Value

+ +

The {{HTMLElement("input")}} element's {{htmlattrxref("value", "input")}} attribute contains a {{domxref("DOMString")}} that either represents a telephone number or is an empty string ("").

+ +

Additional attributes

+ +

In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, telephone number inputs support the following attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescription
{{anch("maxlength")}}The maximum length, in UTF-16 characters, to accept as a valid input
{{anch("minlength")}}The minimum length that is considered valid for the field's contents
{{anch("pattern")}}A regular expression the entered value must match to pass constraint validation
{{anch("placeholder")}}An example value to display inside the field when it has no value
{{anch("readonly")}}A Boolean attribute which, if present, indicates that the field's contents should not be user-editable
{{anch("size")}}The number of characters wide the input field should be onscreen
+ +

{{htmlattrdef("maxlength")}}

+ +

The maximum number of characters (as UTF-16 code units) the user can enter into the telephone number field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the telephone number field has no maximum length. This value must also be greater than or equal to the value of minlength.

+ +

The input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long.

+ +

{{htmlattrdef("minlength")}}

+ +

The minimum number of characters (as UTF-16 code units) the user can enter into the telephone number field. This must be an non-negative integer value smaller than or equal to the value specified by maxlength. If no minlength is specified, or an invalid value is specified, the telephone number input has no minimum length.

+ +

The telephone number field will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long.

+ +

{{htmlattrdef("pattern")}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "pattern-include")}}

+ +

See {{anch("Pattern validation")}} below for details and an example.

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "placeholder", 0, 1, 2)}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "readonly", 0, 1, 2)}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "size", 0, 1, 2)}}

+ +

Non-standard attributes

+ +

The following non-standard attributes are available to telephone number input fields. As a general rule, you should avoid using them unless it can't be helped.

+ + + + + + + + + + + + + + + + + + +
AttributeDescription
{{anch("autocorrect")}}Whether or not to allow autocorrect while editing this input field. Safari only.
{{anch("mozactionhint")}}A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only.
+ +

{{htmlattrdef("autocorrect")}} {{non-standard_inline}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "autocorrect-include")}}

+ +

{{htmlattrdef("mozactionhint")}} {{non-standard_inline}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "mozactionhint-include")}}

+ +

Using tel inputs

+ +

Telephone numbers are a very commonly collected type of data on the web. When creating any kind of registration or e-commerce site, for example, you will likely need to ask the user for a telephone number, whether for business purposes or for emergency contact purposes. Given how commonly-entered phone numbers are, it's unfortunate that a "one size fits all" solution for validating phone numbers is not practical.

+ +

Fortunately, you can consider the requirements of your own site and implement an appropriate level of validation yourself. See {{anch("Validation")}}, below, for details.

+ +

Custom keyboards

+ +

One of the main advantages of <input type="tel"> is that it causes mobile browsers to display a special keyboard for entering phone numbers. For example, here's what the keypads look like on a couple of devices.

+ + + + + + + + + + + + + + + +
Examples of custom keyboards on mobile devices.
Firefox for AndroidWebKit iOS (Safari/Chrome/Firefox)
Firefox for Android screen shotFirefox for iOS screenshot
+ +

A simple tel input

+ +

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

+ +
<label for="telNo">Phone number:</label>
+<input id="telNo" name="telNo" type="tel">
+ +

{{ EmbedLiveSample('A_simple_tel_input', 600, 40) }}

+ +

There is nothing magical going on here. When submitted to the server, the above input's data would be represented as, for example, telNo=+12125553151.

+ +

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 {{HTMLElement("input")}}. This is where placeholders come in. A placeholder is a value that demonstrates the form the value should take by presenting an example of a valid value, which is displayed inside the edit box when the element's value is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.

+ +

Here, we have an tel input with the placeholder 123-4567-8901. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

+ +
<input id="telNo" name="telNo" type="tel"
+       placeholder="123-4567-8901">
+ +

{{ EmbedLiveSample('Placeholders', 600, 40) }}

+ +

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 {{htmlattrxref("size", "input")}} attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the tel edit box is 20 characters wide:

+ +
<input id="telNo" name="telNo" type="tel"
+       size="20">
+ +

{{ EmbedLiveSample('Physical_input_element_size', 600, 40) }}

+ +

Element value length

+ +

The size is separate from the length limitation on the entered telephone number. You can specify a minimum length, in characters, for the entered telephone number using the {{htmlattrxref("minlength", "input")}} attribute; similarly, use {{htmlattrxref("maxlength", "input")}} to set the maximum length of the entered telephone number.

+ +

The example below creates a 20-character wide telephone number entry box, requiring that the contents be no shorter than 9 characters and no longer than 14 characters.

+ +
<input id="telNo" name="telNo" type="tel"
+       size="20" minlength="9" maxlength="14">
+ +

{{EmbedLiveSample("Element_value_length", 600, 40) }}

+ +
+

Note: The above attributes do affect {{anch("Validation")}} — the above example's inputs will count as invalid if the length of the value is less than 9 characters, or more than 14. Most browser won't even let you enter a value over the max length.

+
+ +

Providing default options

+ +

As always, you can provide a default value for an tel input box by setting its {{htmlattrxref("value", "input")}} attribute:

+ +
+
<input id="telNo" name="telNo" type="tel"
+       value="333-4444-4444">
+
+ +

{{EmbedLiveSample("Default_value", 600, 40)}}

+ +

Offering suggested values

+ +

Taking it a step farther, you can provide a list of default phone number values from which the user can select. To do this, use the {{htmlattrxref("list", "input")}} attribute. This doesn't limit the user to those options, but does allow them to select commonly-used telephone numbers more quickly. This also offers hints to {{htmlattrxref("autocomplete", "input")}}. The list attribute specifies the ID of a {{HTMLElement("datalist")}} element, which in turn contains one {{HTMLElement("option")}} element per suggested value; each option's value is the corresponding suggested value for the telephone number entry box.

+ +
<label for="telNo">Phone number: </label>
+<input id="telNo" name="telNo" type="tel" list="defaultTels">
+
+<datalist id="defaultTels">
+  <option value="111-1111-1111">
+  <option value="122-2222-2222">
+  <option value="333-3333-3333">
+  <option value="344-4444-4444">
+</datalist>
+ +

{{EmbedLiveSample("Offering_suggested_values", 600, 40)}}

+ +

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

+ +

Here's a screenshot of what that might look like:

+ +

+ +

Validation

+ +

As we've touched on before, it's quite difficult to provide a one-size-fits-all client-side validation solution for phone numbers. So what can we do? Let's consider some options.

+ +
+

Important: HTML form validation is not a substitute for server-side scripts that ensure the entered data is in the proper format before it is allowed into the database.  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 simply 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.

+
+ +

Making telephone numbers required

+ +

You can make it so that an empty input is invalid and won't be submitted to the server using the {{htmlattrxref("required", "input")}} attribute. For example, let's use this HTML:

+ +
<form>
+  <div>
+    <label for="telNo">Enter a telephone number (required): </label>
+    <input id="telNo" name="telNo" type="tel" required>
+    <span class="validity"></span>
+  </div>
+  <div>
+    <button>Submit</button>
+  </div>
+</form>
+ +

And let's include the following CSS to highlight valid entries with a checkmark and invalid entries with a cross:

+ +
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;
+  color: #8b0000;
+}
+
+input:valid+span:after {
+  position: absolute;
+  content: '✓';
+  padding-left: 5px;
+  color: #009000;
+}
+ +

The output looks like this:

+ +

{{EmbedLiveSample("Making_telephone_numbers_required", 700, 70)}}

+ +

Pattern validation

+ +

If you want to further restrict entered numbers so they also have to conform to a specific pattern, you can use the {{htmlattrxref("pattern","input")}} attribute, which takes as its value a {{Glossary("regular expression")}} that entered values have to match.

+ +

In this example we'll use the same CSS as before, but our HTML is changed to look like this:

+ +
<form>
+  <div>
+    <label for="telNo">Enter a telephone number (in the form xxx-xxx-xxxx): </label>
+    <input id="telNo" name="telNo" type="tel" required
+           pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
+    <span class="validity"></span>
+  </div>
+  <div>
+    <button>Submit</button>
+  </div>
+</form>
+ + + +

{{EmbedLiveSample("Pattern_validation", 700, 70)}}

+ +

Notice how the entered value is reported as invalid unless the pattern xxx-xxx-xxxx is matched; for instance, 41-323-421 won't be accepted. Neither will 800-MDN-ROCKS. However, 865-555-6502 will be accepted. This particular pattern is obviously only useful for certain locales — in a real application you'd probably have to vary the pattern used depending on the locale of the user.

+ +

Examples

+ +

In this example, we present a simple interface with a {{htmlelement("select")}} element that lets the user choose which country they're in, and a set of <input type="tel"> elements to let them enter each part of their phone number; there is no reason why you can't have multiple tel inputs.

+ +

Each input has a {{htmlattrxref("placeholder","input")}} attribute to show a hint to sighted users about what to enter into it, a {{htmlattrxref("pattern","input")}} to enforce a specific number of characters for the desired section, and an aria-label attribute to contain a hint to be read out to screenreader users about what to enter into it.

+ +
<form>
+  <div>
+    <label for="country">Choose your country:</label>
+    <select id="country" name="country">
+      <option>UK</option>
+      <option selected>US</option>
+      <option>Germany</option>
+    </select>
+  </div>
+  <div>
+    <p>Enter your telephone number: </p>
+    <span class="areaDiv">
+      <input id="areaNo" name="areaNo" type="tel" required
+             placeholder="Area code" pattern="[0-9]{3}"
+             aria-label="Area code">
+      <span class="validity"></span>
+    </span>
+    <span class="number1Div">
+      <input id="number1" name="number1" type="tel" required
+             placeholder="First part" pattern="[0-9]{3}"
+             aria-label="First part of number">
+      <span class="validity"></span>
+    </span>
+    <span class="number2Div">
+      <input id="number2" name="number2" type="tel" required
+             placeholder="Second part" pattern="[0-9]{4}"
+             aria-label="Second part of number">
+      <span class="validity"></span>
+    </span>
+  </div>
+  <div>
+    <button>Submit</button>
+  </div>
+</form>
+ +

The JavaScript is relatively simple — it contains an {{domxref("GlobalEventHandlers.onchange", "onchange")}} event handler that, when the <select> value is changed, updates the <input> element's pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory.

+ +
var selectElem = document.querySelector("select");
+var inputElems = document.querySelectorAll("input");
+
+selectElem.onchange = function() {
+  for(var i = 0; i < inputElems.length; i++) {
+    inputElems[i].value = "";
+  }
+
+  if(selectElem.value === "US") {
+    inputElems[2].parentNode.style.display = "inline";
+
+    inputElems[0].placeholder = "Area code";
+    inputElems[0].pattern = "[0-9]{3}";
+
+    inputElems[1].placeholder = "First part";
+    inputElems[1].pattern = "[0-9]{3}";
+    inputElems[1].setAttribute("aria-label","First part of number");
+
+    inputElems[2].placeholder = "Second part";
+    inputElems[2].pattern = "[0-9]{4}";
+    inputElems[2].setAttribute("aria-label","Second part of number");
+  } else if(selectElem.value === "UK") {
+    inputElems[2].parentNode.style.display = "none";
+
+    inputElems[0].placeholder = "Area code";
+    inputElems[0].pattern = "[0-9]{3,6}";
+
+    inputElems[1].placeholder = "Local number";
+    inputElems[1].pattern = "[0-9]{4,8}";
+    inputElems[1].setAttribute("aria-label","Local number");
+  } else if(selectElem.value === "Germany") {
+    inputElems[2].parentNode.style.display = "inline";
+
+    inputElems[0].placeholder = "Area code";
+    inputElems[0].pattern = "[0-9]{3,5}";
+
+    inputElems[1].placeholder = "First part";
+    inputElems[1].pattern = "[0-9]{2,4}";
+    inputElems[1].setAttribute("aria-label","First part of number");
+
+    inputElems[2].placeholder = "Second part";
+    inputElems[2].pattern = "[0-9]{4}";
+    inputElems[2].setAttribute("aria-label","Second part of number");
+  }
+}
+ +

The example looks like this:

+ +

{{EmbedLiveSample('Examples', 600, 140)}}

+ +

This is an interesting idea, which goes to show a potential solution to the problem of dealing with international phone numbers. You would have to extend the example of course to provide the correct pattern for potentially every country, which would be a lot of work, and there would still be no foolproof guarantee that the users would enter their numbers correctly.

+ +

It makes you wonder if it is worth going to all this trouble on the client-side, when you could just let the user enter their number in whatever format they wanted on the client-side and then validate and sanitize it on the server. But this choice is yours to make.

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'forms.html#tel-state-(type=tel)', '<input type="tel">')}}{{Spec2('HTML WHATWG')}}Initial definition
{{SpecName('HTML5.1', 'sec-forms.html#tel-state-typetel', '<input type="tel">')}}{{Spec2('HTML5.1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.input.input-tel")}}

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf