Ввод числа

Input type number

В HTML5 появилось специальное поле с атрибутом type=»number» для вода чисел. Рассмотрим его возможности.

Для поля доступны следующие атрибуты:

Атрибут Описание
step Шаг изменения значения
max Максимальное значение
min Минимальное значение
placeholder Подсказка
readonly Только для чтения
disabled Заблокирован
list Связка со списком опций datalist по id
required Обязательный для заполнения

Шаг изменения

Атрибут step=»1″ задает на сколько будет увеличиваться или уменьшаться значение в поле. Может быть как целым (10) так и дробным (0.1).

Пример:

Минимальное значение

Атрибут min=»1″ задает минимально возможное значение value . Это значение должно быть меньше или равно значению max . Может быть целым, отрицательным или дробным.

Пример:

Максимальное значение

Атрибут max=»100″ задает максимально возможное значение value .

Пример:

Опции по умолчанию

У поля есть возможность задать список с рекомендуемыми значениями с помощью элемента .

Пример:

Валидация

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

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

Пример:

Также доступны CSS псевдо свойства :invalid и :valid , с помощью них можно применить стили к неправильно заполненному полю.

input[type="number"]:invalid+span:after < content: '✖'; padding-left: 5px; color: red; >input[type="number"]:valid+span:after

Источник

HTML Input Types

This chapter describes the different types for the HTML element.

HTML Input Types

Here are the different input types you can use in HTML:

Tip: The default value of the type attribute is «text».

Input Type Text

defines a single-line text input field:

Example

This is how the HTML code above will be displayed in a browser:

Input Type Password

defines a password field:

Example

This is how the HTML code above will be displayed in a browser:

Читайте также:  Html form одним кодом

The characters in a password field are masked (shown as asterisks or circles).

Input Type Submit

defines a button for submitting form data to a form-handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form’s action attribute:

Example

This is how the HTML code above will be displayed in a browser:

If you omit the submit button’s value attribute, the button will get a default text:

Example

Input Type Reset

defines a reset button that will reset all form values to their default values:

Example

This is how the HTML code above will be displayed in a browser:

If you change the input values and then click the «Reset» button, the form-data will be reset to the default values.

Input Type Radio

defines a radio button.

Radio buttons let a user select ONLY ONE of a limited number of choices:

Example

Choose your favorite Web language:

This is how the HTML code above will be displayed in a browser:

Input Type Checkbox

defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example

This is how the HTML code above will be displayed in a browser:

I have a bike
I have a car
I have a boat

Input Type Button

defines a button:

Example

This is how the HTML code above will be displayed in a browser:

Input Type Color

The is used for input fields that should contain a color.

Depending on browser support, a color picker can show up in the input field.

Example

Input Type Date

The is used for input fields that should contain a date.

Depending on browser support, a date picker can show up in the input field.

Example

You can also use the min and max attributes to add restrictions to dates:

Example

Input Type Datetime-local

The specifies a date and time input field, with no time zone.

Depending on browser support, a date picker can show up in the input field.

Example

Input Type Email

The is used for input fields that should contain an e-mail address.

Depending on browser support, the e-mail address can be automatically validated when submitted.

Some smartphones recognize the email type, and add «.com» to the keyboard to match email input.

Example

Input Type Image

The defines an image as a submit button.

The path to the image is specified in the src attribute.

Читайте также:  Sublime text python ввод данных

Example

Input Type File

The defines a file-select field and a «Browse» button for file uploads.

Example

Input Type Hidden

The defines a hidden input field (not visible to a user).

A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.

A hidden field often stores what database record that needs to be updated when the form is submitted.

Note: While the value is not displayed to the user in the page’s content, it is visible (and can be edited) using any browser’s developer tools or «View Source» functionality. Do not use hidden inputs as a form of security!

Example

Input Type Month

The allows the user to select a month and year.

Depending on browser support, a date picker can show up in the input field.

Example

Input Type Number

The defines a numeric input field.

You can also set restrictions on what numbers are accepted.

The following example displays a numeric input field, where you can enter a value from 1 to 5:

Example

Input Restrictions

Here is a list of some common input restrictions:

Attribute Description
checked Specifies that an input field should be pre-selected when the page loads (for type=»checkbox» or type=»radio»)
disabled Specifies that an input field should be disabled
max Specifies the maximum value for an input field
maxlength Specifies the maximum number of character for an input field
min Specifies the minimum value for an input field
pattern Specifies a regular expression to check the input value against
readonly Specifies that an input field is read only (cannot be changed)
required Specifies that an input field is required (must be filled out)
size Specifies the width (in characters) of an input field
step Specifies the legal number intervals for an input field
value Specifies the default value for an input field

You will learn more about input restrictions in the next chapter.

The following example displays a numeric input field, where you can enter a value from 0 to 100, in steps of 10. The default value is 30:

Example

Input Type Range

The defines a control for entering a number whose exact value is not important (like a slider control). Default range is 0 to 100. However, you can set restrictions on what numbers are accepted with the min , max , and step attributes:

Example

The is used for search fields (a search field behaves like a regular text field).

Читайте также:  Php get request param

Example

Input Type Tel

The is used for input fields that should contain a telephone number.

Example

Input Type Time

The allows the user to select a time (no time zone).

Depending on browser support, a time picker can show up in the input field.

Example

Input Type Url

The is used for input fields that should contain a URL address.

Depending on browser support, the url field can be automatically validated when submitted.

Some smartphones recognize the url type, and adds «.com» to the keyboard to match url input.

Example

Input Type Week

The allows the user to select a week and year.

Depending on browser support, a date picker can show up in the input field.

Источник

Ввод чисел

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

Рис. 1. Вид поля для ввода чисел

Синтаксис создания поля следующий:

Допустимые атрибуты перечислены в табл. 1.

Табл. 1. Атрибуты поля с числом

Атрибут Описание
min Минимальное значение.
max Максимальное значение.
size Ширина поля.
step Шаг приращения числа. Может быть как целым (2), так и дробным (0.2).
name Имя поля, предназначено для того, чтобы обработчик формы мог его идентифицировать.
value Начальное число, которое выводится в поле.

Для ограничения введённого числа предназначены атрибуты min и max , они могут принимать отрицательное и положительное значение. При достижении верхнего или нижнего порога стрелки в поле в зависимости от браузера блокируются или не дают никакого эффекта (пример 1). Несмотря на такие запреты, в любом случае в поле самостоятельно можно вводить любые значения, включая текст. Атрибуты min и max работают только при использовании стрелок в поле.

Пример 1. Ограничение ввода чисел

       

Введите число от 1 до 10:

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

Атрибут step задаёт шаг приращения и по умолчанию равен 1. В то же время значение может быть и дробным числом, как показано в примере 2.

       

Укажите нормальную среднюю температуру человека:

Результат примера продемонстрирован на рис. 2.

Ввод дробных чисел в поле

Рис. 2. Ввод дробных чисел в поле

Браузеры плохо поддерживают это поле, пока лишь это делает Chrome и Opera. В остальных браузерах поле для ввода числа приобретает вид обычного текстового поля.

Источник

Оцените статью