Html format option text

Html format option text

Тег (от англ. option — пункт, параметр, опция) определяет отдельные пункты списка, создаваемого с помощью контейнера .

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

Синтаксис¶

select> option>Пункт 1option> option>Пункт 2option> select> 

Закрывающий тег не обязателен.

Атрибуты¶

disabled Заблокировать для доступа элемент списка. label Указание метки пункта списка. selected Заранее устанавливает определённый пункт списка выделенным. value Значение пункта списка, которое будет отправлено на сервер или прочитано с помощью скриптов.

Также для этого элемента доступны универсальные атрибуты.

disabled¶

Блокирует элемент списка для его выбора.

Значение по умолчанию

По умолчанию этот атрибут выключен.

label¶

Атрибут предназначен для указания метки пункта списка, сокращённой по сравнению с текстом внутри . Если атрибут label присутствует, то текст внутри игнорируется и в списке выводится значение label .

Значение по умолчанию

selected¶

Значение по умолчанию

По умолчанию этот атрибут выключен.

value¶

Значение по умолчанию

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

Описание и примеры¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 html> head> meta charset="utf-8" /> title>OPTIONtitle> head> body> form action="option2.php"> p> select size="3" name="hero"> option disabled>Выберите рыцаряoption> option value="t1" selected>Гавейнoption> option value="t2">Ланселотoption> option value="t3">Галахэдoption> option value="t4">Персивальoption> select> p> p>input type="submit" value="Отправить" />p> form> body> html> 

Источник

Html format option text

Один пункт в раскрывающемся списке .

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Тег используется в интерактивных элементах управления для вёрстки одиночного пункта списка.

Пример

Скопировать ссылку «Пример» Скопировано

              form> label for="city-select">Ваш городlabel> select name="city" id="city-select"> option value="">-- Выберите город --option> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan">Казаньoption> option value="samara">Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select> form>      

Подробно

Скопировать ссылку «Подробно» Скопировано

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

Атрибуты

Скопировать ссылку «Атрибуты» Скопировано

disabled

Скопировать ссылку «disabled» Скопировано

Атрибут булевого типа. Если задан, то пункт списка нельзя выбрать. Часто браузеры выделяют такой элемент управления серым цветом, и на нём не срабатывают события клика или фокуса. Даже если атрибут не задан, элемент всё равно может быть отключён, если находится внутри тега с заданным атрибутом disabled .

           select name="city1"> option value="">-- Выберите город --option> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan">Казаньoption> option value="samara" disabled>Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      

label

Скопировать ссылку «label» Скопировано

Значение этого атрибута задаёт текст пункта в списке. Если атрибут не задан, то в качестве значения берётся текстовое содержимое тега .

        select name="city2"> option value="petersburg" selected label="Ленинград">Санкт-Петербургoption> option value="samara" label="Куйбышев">Самараoption> option value="volgograd" label="Сталинград">Волгоградoption> option value="ekaterinburg" label="Свердловск">Екатеринбургoption> select>      

Несмотря на то, что задано текстовое содержимое тега , в выпадающем списке отображаются значения из атрибутов label :

selected

Скопировать ссылку «selected» Скопировано

           select name="city3"> option value="">-- Выберите город --option> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan" selected>Казаньoption> option value="samara">Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      
          select name="city4" multiple size="6"> option value="petersburg">Санкт-Петербургoption> option value="moscow" selected>Москваoption> option value="kazan" >Казаньoption> option value="samara" selected>Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      

value

Скопировать ссылку «value» Скопировано

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

На практике

Скопировать ссылку «На практике» Скопировано

Денис Ежков советует

Скопировать ссылку «Денис Ежков советует» Скопировано

🛠 Раньше браузеры не предоставляли никаких средств для нормальной стилизации элемента , и это доставляло очень много головной боли фронтенд-разработчикам 🙁 Стиль элементов можно было поменять, только если тегу был задан атрибут multiple . Тогда список целиком становился частью потока страницы, и мы имели возможность применять стили к его элементам. Вот как выглядело решение:

          select name="city" id="city-select" multiple> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan">Казаньoption> option value="samara">Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      
 select  counter-reset: cnt;> option:nth-child(2n)  background-color: #282a2e;> option  counter-increment: cnt;> option::before  content: counter(cnt) ". ";> select  counter-reset: cnt; > option:nth-child(2n)  background-color: #282a2e; > option  counter-increment: cnt; > option::before  content: counter(cnt) ". "; >      

Теперь практически все браузеры умеют стилизовать даже без атрибута multiple .

В Safari стилизация для доступна не полностью, даже если тег имеет атрибут multiple .

Источник

: The HTML Option element

If this Boolean attribute is set, this option is not checkable. Often browsers grey out such control and it won’t receive any browsing event, like mouse clicks or focus-related ones. If this attribute is not set, the element can still be disabled if one of its ancestors is a disabled element.

This attribute is text for the label indicating the meaning of the option. If the label attribute isn’t defined, its value is that of the element text content.

If present, this Boolean attribute indicates that the option is initially selected. If the element is the descendant of a element whose multiple attribute is not set, only one single of this element may have the selected attribute.

The content of this attribute represents the value to be submitted with the form, should this option be selected. If this attribute is omitted, the value is taken from the text content of the option element.

Styling with CSS

Styling the element is highly limited. Options don’t inherit the font set on the parent. In Firefox, only color and background-color can be set, however in Chrome and Safari it’s not possible to set any properties. You can find more details about styling in our guide to advanced form styling.

Examples

Technical summary

Content categories None.
Permitted content Text, possibly with escaped characters (like é ).
Tag omission The start tag is mandatory. The end tag is optional if this element is immediately followed by another element or an , or if the parent element has no more content.
Permitted parents A , an or a element.
Implicit ARIA role option
Permitted ARIA roles No role permitted
DOM interface HTMLOptionElement

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

HTML Form Elements

This chapter describes all the different HTML form elements.

The HTML Elements

The HTML element can contain one or more of the following form elements:

The Element

One of the most used form element is the element.

The element can be displayed in several ways, depending on the type attribute.

Example

All the different values of the type attribute are covered in the next chapter: HTML Input Types.

The Element

The element defines a label for several form elements.

The element is useful for screen-reader users, because the screen-reader will read out loud the label when the user focus on the input element.

The element also help users who have difficulty clicking on very small regions (such as radio buttons or checkboxes) — because when the user clicks the text within the element, it toggles the radio button/checkbox.

The for attribute of the tag should be equal to the id attribute of the element to bind them together.

The Element

The element defines a drop-down list:

Example

The elements defines an option that can be selected.

By default, the first item in the drop-down list is selected.

To define a pre-selected option, add the selected attribute to the option:

Example

Visible Values:

Use the size attribute to specify the number of visible values:

Example

Allow Multiple Selections:

Use the multiple attribute to allow the user to select more than one value:

Example

The Element

The element defines a multi-line input field (a text area):

Example

The rows attribute specifies the visible number of lines in a text area.

The cols attribute specifies the visible width of a text area.

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

You can also define the size of the text area by using CSS:

Example

The Element

The element defines a clickable button:

Example

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

Note: Always specify the type attribute for the button element. Different browsers may use different default types for the button element.

The and Elements

The element is used to group related data in a form.

The element defines a caption for the element.

Example

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

The Element

The element specifies a list of pre-defined options for an element.

Users will see a drop-down list of the pre-defined options as they input data.

The list attribute of the element, must refer to the id attribute of the element.

Example

The Element

The element represents the result of a calculation (like one performed by a script).

Example

Perform a calculation and show the result in an element:

HTML Exercises

HTML Form Elements

Tag Description
Defines an HTML form for user input
Defines an input control
Defines a multiline input control (text area)
Defines a label for an element
Groups related elements in a form
Defines a caption for a element
Defines a drop-down list
Defines a group of related options in a drop-down list
Defines an option in a drop-down list
Defines a clickable button
Specifies a list of pre-defined options for input controls
Defines the result of a calculation

For a complete list of all available HTML tags, visit our HTML Tag Reference.

Источник

Читайте также:  Python gui windows linux
Оцените статью