Блокировка поля

HTML attribute: disabled

The Boolean disabled attribute, when present, makes the element not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants.

Try it

Overview

If the disabled attribute is specified on a form control, the element and its form control descendants do not participate in constraint validation. Often browsers grey out such controls and it won’t receive any browsing events, like mouse clicks or focus-related ones.

The disabled attribute is supported by , , , , , and .

This Boolean disabled attribute indicates that the user cannot interact with the control or its descendant controls. If this attribute is not specified, the control inherits its setting from the containing element, for example fieldset ; if there is no containing element with the disabled attribute set, and the control itself does not have the attribute, then the control is enabled. If declared on an , the select is still interactive (unless otherwise disabled), but none of the items in the option group are selectable.

When a supporting element has the disabled attribute applied, the :disabled pseudo-class also applies to it. Conversely, elements that support the disabled attribute but don’t have the attribute set match the :enabled pseudo-class.

This Boolean attribute prevents the user from interacting with the button. If this attribute isn’t set, the button can still be disabled from a containing element, for example ; if there is no containing element with the disabled attribute set, then the button is enabled.

Читайте также:  Std stringstream cpp reference

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

Attribute interactions

The difference between disabled and readonly is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled.

Because a disabled field cannot have its value changed, required does not have any effect on inputs with the disabled attribute also specified. Additionally, since the elements become immutable, most other attributes, such as pattern , have no effect, until the control is enabled.

Note: The required attribute is not permitted on inputs with the disabled attribute specified.

Usability

Browsers display disabled form controls greyed as disabled form controls are immutable, won’t receive focus or any browsing events, like mouse clicks or focus-related ones, and aren’t submitted with the form.

If present on a supporting elements, the :disabled pseudo class will match. If the attribute is not included, the :enabled pseudo class will match. If the element doesn’t support the disabled attribute, the attribute will have no effect, including not leading to being matched by the :disabled and :enabled pseudo classes.

Constraint validation

If the element is disabled , then the element’s value can not receive focus and cannot be updated by the user, and does not participate in constraint validation.

Examples

fieldset> legend>Checkboxeslegend> p> label> input type="checkbox" name="chbox" value="regular" /> Regular label> p> p> label> input type="checkbox" name="chbox" value="disabled" disabled /> disabled label> p> fieldset> fieldset> legend>Radio buttonslegend> p> label> input type="radio" name="radio" value="regular" /> Regular label> p> p> label> input type="radio" name="radio" value="disabled" disabled /> disabled label> p> fieldset> p> label >Select an option: select> optgroup label="Group 1"> option>Option 1.1option> optgroup> optgroup label="Group 2"> option>Option 2.1option> option disabled>Option 2.2option> option>Option 2.3option> optgroup> optgroup label="Group 3" disabled> option>Disabled 3.1option> option>Disabled 3.2option> option>Disabled 3.3option> optgroup> select> label> p> fieldset disabled> legend>Disabled fieldsetlegend> p> label> Name: input type="name" name="radio" value="regular" /> Regular label> p> p> label>Number: input type="number" />label> p> fieldset> 

Specifications

Browser compatibility

html.elements.button.disabled

BCD tables only load in the browser

html.elements.fieldset.disabled

BCD tables only load in the browser

html.elements.input.disabled

BCD tables only load in the browser

html.elements.optgroup.disabled

BCD tables only load in the browser

html.elements.option.disabled

BCD tables only load in the browser

html.elements.select.disabled

BCD tables only load in the browser

html.elements.textarea.disabled

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on May 22, 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.

Источник

Блокирование элементов форм

У любого элемента формы есть два состояния, которые ограничивают доступ к элементу или ввод данных, — блокирование (disabled) и только для чтения (readonly).

Блокирование

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

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

На рис. 1 представлены разные элементы форм в заблокированном состоянии.

Рис. 1. Вид заблокированных элементов в Chrome

Для блокирования элемента формы используется атрибут disabled . Добавление этого атрибута разрешает отображать элемент формы, но не позволяет изменять его.

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

Пример 1. Блокирования поля

        

Я согласен со всеми условиями

Результат данного примера в Safari показан ниже (рис. 2).

Рис. 2. Заблокированное текстовое поле

В данном примере применяется блокирование кнопки, но оно снимается, как только пользователь поставит флажок возле текста «Я согласен со всеми условиями».

Поле только для чтения

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

Для установки режима «только для чтения» используется атрибут readonly , он добавляется к тегу или . На вид элемента формы это никак не влияет, но как было уже замечено, модифицировать значение поля не удастся.

Ниже представлены два поля с многострочным текстом, одно из которых находится в обычном режиме, а второе — «только для чтения».

В примере 2 показано создание поля для чтения.

Пример 2. Использование readonly

       

Источник

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