- HTML value Attribute
- Applies to
- Examples
- Example
- Example
- Example
- Example
- Example
- Example
- Browser Support
- Атрибут value
- Как пишется
- Атрибут value
- Синтаксис
- Применяется
- Значения
- Значение по умолчанию
- Типы тегов
- HTML attribute reference
- Attribute list
- Content versus IDL attributes
- Boolean Attributes
- Event handler attributes
HTML value Attribute
For , and elements, the value attribute specifies the initial value of the element.
For elements, the value attribute specifies the current value of the gauge.
For elements, the value attribute specifies how much of the task has been completed.
For elements, the value attribute specifies the value of the parameter.
Applies to
The value attribute can be used on the following elements:
Examples
Example
Two buttons with equal names, that submit different values when clicked:
Example
An HTML form with initial (default) values:
Use of the value attribute in an ordered list:
Example
A gauge with a current value, min, max, high, and low segments:
Example
A drop-down list inside an HTML form:
Example
Example
Set the «autoplay» parameter to «true», so the sound will start playing as soon as the page loads:
Browser Support
The value attribute has the following browser support for each element:
Element | |||||
---|---|---|---|---|---|
button | Yes | Yes | Yes | Yes | Yes |
input | 1.0 | 2.0 | 1.0 | 1.0 | 1.0 |
li | Yes | Yes | Yes | Yes | Yes |
meter | 8.0 | 13.0 | 6.0 | 6.0 | 11.0 |
option | Yes | Yes | Yes | Yes | Yes |
progress | 8.0 | 10.0 | 16.0 | 6.0 | 11.0 |
param | Yes | Yes | Yes | Yes | Yes |
Атрибут value
В примере ниже нумерация элементов списка начнётся с 5:
А в этом примере в поле ввода уже будет написано «Дока»:
Название лучшего справочника по вебу:
form> label> Название лучшего справочника по вебу: input type="text" value="Дока"> label> button type="submit">Соглашусь!button> form>
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Скопировать ссылку «button» Скопировано
Если указать у кнопки атрибут value с каким-то значением, то это значение будет передано на сервер в момент отправки данных из формы. На сервер передаётся пара «имя=значение». Имя кнопки можно задать атрибутом name .
В примере ниже вместе с данными формы на сервер отправится информация «diversion=Нет!»:
Соглашаетесь с нашими правилами?
form> label> Соглашаетесь с нашими правилами? input type="checkbox" name="agreement"> label> button type="submit" value="Нет!" name="diversion">Соглашаюсьbutton> form>
Скопировать ссылку «option» Скопировано
Если выбран какой-то пункт списка, то при отправке формы на сервер будет передано значение атрибута value этого пункта. Если атрибут не задан, то при отправке будет использоваться текстовое содержимое тега .
Скопировать ссылку «data» Скопировано
Для тега атрибут value является обязательным. В нём указывается понятная для компьютера информация.
Например, в интернет-магазине у каждого товара есть идентификатор. Можно указать его в качестве значения атрибута value :
Модный телефон Нужный компьютер Классный телефон Удобный телефон Нормальный телефон
ul> li> data value="item001">Модный телефонdata> li> li> data value="item002">Нужный компьютерdata> li> li> data value="item003">Классный телефонdata> li> li> data value="item004">Удобный телефонdata> li> li> data value="item005">Нормальный телефонdata> li> ul>
Скопировать ссылку «input» Скопировано
Атрибут value задаёт значение по умолчанию для поля ввода. Это значение будет передано на сервер в момент отправки формы. Поскольку у тега большой список разных типов, то и атрибут в каждом конкретном случае имеет своё значение:
- Для инпутов с типами button , reset , и submit задаёт текст на кнопке.
- Для типов text , password , и hidden задаёт начальное значение. В первых двух случаях пользователь сможет стереть его и написать что-то своё.
- Для типов checkbox , radio , и image — задаёт отправляемое на сервер значение, которое пользователь поменять не может.
Атрибут value можно задать для инпута любого типа, кроме file .
Скопировать ссылку «li» Скопировано
Скопировать ссылку «meter» Скопировано
Атрибут value определяет текущее значение элемента. Обязательно должно быть числом. Если атрибут не задан, то текущее значение равно 0.
meter max="100" min="0" value="50">meter>
Скопировать ссылку «progress» Скопировано
Поскольку тег показывает процесс выполнения какого-то действия, то атрибут value в данном случае показывает, сколько от задачи выполнено в данный момент. Значение должно быть числом.
progress id="file" max="100" value="70">70%progress>
Атрибут value
Определяет значение элемента формы, которое будет отправлено на сервер или получено с помощью клиентских скриптов. На сервер отправляется пара «имя=значение», где имя задается атрибутом name тега , а значение — атрибутом value .
В зависимости от типа элемента атрибут value выступает в следующей роли:
- для кнопок ( input type=»button | reset | submit» ) устанавливает текстовую надпись на них;
- для текстовых полей ( input type=»password | text» ) указывает предварительно введенную строку. Пользователь может стирать текст и вводить свои символы, но при использовании в форме кнопки Reset пользовательский текст очищается и восстанавливается введенный в атрибуте value ;
- для флажков и переключателей ( input type=»checkbox | radio» ) уникально определяет каждый элемент, с тем, чтобы клиентская или серверная программа могла однозначно установить, какой пункт выбрал пользователь.
- для файлового поля ( input type=»file» ) не оказывает влияние.
Синтаксис
Применяется
Значения
Значение по умолчанию
Как по вашему мнению расшифровывается аббревиатура "ОС"?
Офицерский состав Операционная система Большой полосатый мух
Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.
Типы тегов
HTML5
Блочные элементы
Строчные элементы
Универсальные элементы
Нестандартные теги
Осуждаемые теги
Видео
Документ
Звук
Изображения
Объекты
Скрипты
Списки
Ссылки
Таблицы
Текст
Форматирование
Формы
Фреймы
HTML attribute reference
Elements in HTML have attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want.
Attribute list
Attribute Name | Elements | Description |
---|---|---|
accept | , | List of types the server accepts, typically a file type. |
accept-charset | List of supported charsets. | |
accesskey | Global attribute | Keyboard shortcut to activate or add focus to the element. |
action | The URI of a program that processes the information submitted via the form. | |
align Deprecated | , , , , , , , , , , , , | Specifies the horizontal alignment of the element. |
allow | Specifies a feature-policy for the iframe. | |
alt | , , | Alternative text in case an image can’t be displayed. |
async | Executes the script asynchronously. | |
autocapitalize | Global attribute | Sets whether input is automatically capitalized when entered by user |
autocomplete | , , , | Indicates whether controls in this form can by default have their values automatically completed by the browser. |
autoplay | , | The audio or video should play as soon as possible. |
background | , , , | Specifies the URL of an image file. |
Note: Although browsers and email clients may still support this attribute, it is obsolete. Use CSS background-image instead.
Background color of the element.
Note: This is a legacy attribute. Please use the CSS background-color property instead.
Note: This is a legacy attribute. Please use the CSS border property instead.
This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.
Note: This is a legacy attribute. Please use the CSS color property instead.
Specifies the height of elements listed here. For all other elements, use the CSS height property.
Note: In some instances, such as , this is a legacy attribute, in which case the CSS height property should be used instead.
Specifies a Subresource Integrity value that allows browsers to verify what they fetch.
Note: This attribute is obsolete, use instead.
For the elements listed here, this establishes the element’s width.
Note: For all other instances, such as , this is a legacy attribute, in which case the CSS width property should be used instead.
Content versus IDL attributes
In HTML, most attributes have two faces: the content attribute and the IDL (Interface Definition Language) attribute.
The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via element.setAttribute() or element.getAttribute() . The content attribute is always a string even when the expected value should be an integer. For example, to set an element’s maxlength to 42 using the content attribute, you have to call setAttribute(«maxlength», «42») on that element.
The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo . The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.
IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength , it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.
IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn’t. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly ( select.size , for example) and you should read the specifications to understand how exactly they behave.
Boolean Attributes
Some content attributes (e.g. required , readonly , disabled ) are called boolean attributes. If a boolean attribute is present, its value is true, and if it’s absent, its value is false.
HTML defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace. The following examples are valid ways to mark up a boolean attribute:
div itemscope>This is valid HTML but invalid XML.div> div itemscope=itemscope>This is also valid HTML but invalid XML.div> div itemscope="">This is valid HTML and also valid XML.div> div itemscope="itemscope"> This is also valid HTML and XML, but perhaps a bit verbose. div>
To be clear, the values » true » and » false » are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether. This restriction clears up some common misunderstandings: With checked=»false» for example, the element’s checked attribute would be interpreted as true because the attribute is present.
Event handler attributes
Warning: The use of event handler content attributes is discouraged. The mix of HTML and JavaScript often produces unmaintainable code, and the execution of event handler attributes may also be blocked by content security policies.
In addition to the attributes listed in the table above, global event handlers — such as onclick — can also be specified as content attributes on all elements.
All event handler attributes accept a string. The string will be used to synthesize a JavaScript function like function name(/*args*/) , where name is the attribute’s name, and body is the attribute’s value. The handler receives the same parameters as its JavaScript event handler counterpart — most handlers receive only one event parameter, while onerror receives five: event , source , lineno , colno , error . This means you can, in general, use the event variable within the attribute.
div onclick="console.log(event)">Click me!div> div onclick="console.log(onclick)">Click me!div>