Тег disabled в html

HTML Атрибут disabled

При наличии disabled указывает, что элемент должен быть отключен.

Отключенный элемент непригоден для использования.

Атрибут disabled может быть установлен, чтобы пользователь не использовал до, некоторые другие условия были выполнены (например, выбор флажка и т. д.). Затем, JavaScript можно удалить значение disabled и использовать элемент.

Применение

Атрибут disabled можно использовать для следующих элементов:

Примеры

Пример Button

Пример Fieldset

Отключение группы связанных элементов формы:

Пример Input

Форма HTML с отключенным полем ввода:

Пример Optgroup

Пример Option

Раскрывающийся список с одним отключенным параметром:

Пример Select

Раскрывающийся список отключен:

Пример Textarea

Отключенная текстовая область:

Поддержка браузеров

Атрибут disabled имеет следующую поддержку браузера для каждого элемента:

Элемент
button Да Да Да Да Да
fieldset Да Not supported Да 7.0 Да
input 1.0 6.0 1.0 1.0 1.0
optgroup 1.0 8.0 Да Да Да
option 1.0 8.0 1.0 Да Да
select Да Да Да Да Да
textarea Да Да Да Да Да

Мы только что запустили
SchoolsW3 видео

ВЫБОР ЦВЕТА

colorpicker

Сообщить об ошибке

Если вы хотите сообщить об ошибке или внести предложение, не стесняйтесь отправлять на электронное письмо:

Ваше предложение:

Спасибо Вам за то, что помогаете!

Ваше сообщение было отправлено в SchoolsW3.

ТОП Учебники
ТОП Справочники
ТОП Примеры
Получить сертификат

SchoolsW3 оптимизирован для бесплатного обучения, проверки и подготовки знаний. Примеры в редакторе упрощают и улучшают чтение и базовое понимание. Учебники, ссылки, примеры постоянно пересматриваются, чтобы избежать ошибок, но не возможно гарантировать полную правильность всего содержания. Некоторые страницы сайта могут быть не переведены на РУССКИЙ язык, можно отправить страницу как ошибку, так же можете самостоятельно заняться переводом. Используя данный сайт, вы соглашаетесь прочитать и принять Условия к использованию, Cookies и политика конфиденциальности.

Источник

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.

Читайте также:  canvasExample

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.

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

Если у элемента формы есть этот атрибут, то с ним нельзя взаимодействовать.

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

Кратко

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

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

Пример

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

В примере атрибут задан для целой группы элементов. В итоге ни с одним из полей внутри отключённого нельзя взаимодействовать:

    Ваше имя  Ваш номер телефона  fieldset disabled> label> Ваше имя input type="text"> label> label> Ваш номер телефона input type="text"> label> fieldset>      

Как пишется

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

Это булевый атрибут. Само его наличие говорит браузеру, что элемент нужно отключить.

Может применяться к следующим элементам формы:

Как понять

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

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

Атрибут срабатывает не только на самом элементе, но и на всех его потомках.

Наличие атрибута disabled отключает влияние атрибутов required и pattern . Потому что значение неактивного поля не может быть изменено браузер экономит время на их проверке.

Подсказки

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

💡 Элемент с атрибутом disabled можно стилизовать при помощи псевдокласса :disabled . По умолчанию браузер делает их серыми и менее контрастными.

Источник

Атрибут disabled HTML тега

  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5
  • html5

В данном примере мы указали для элемента с типом радио-кнопка ( type = «radio» ) и флажок ( type = «checkbox» ) атрибут checked. Для одного элемента мы указали атрибут disabled , который не дает нам сделать выбор (элемент отключен).

Кроме того мы создали стиль для элементов, которые выбраны (checked), используя псевдокласс :checkedcss3 и для элементов, которые не выбраны, используя псевдокласс отрицания :notcss3 и псевдокласс :checkedcss3 в качестве селектора.

Пример использования атрибута disabled HTML тега <input data-lazy-src=

HTML Атрибут disabled

Атрибут disabled (от англ. «disabled» ‒ «неработающий, отключённый») блокирует элемент формы, то есть делает его неактивным.

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

В случае кнопки ( или с атрибутом type в значениях button , reset или submit ) блокировка означает, что на кнопку нельзя будет нажать.

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

В случае с чекбоксами и радио кнопками их состояние (отмечено или нет) нельзя будет сменить.

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

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

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

Синтаксис

Значения

Данный атрибут является логическим атрибутом. В HTML данный атрибут может указываться либо без значения, либо с пустым значением, либо со значением disabled .

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

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

Источник

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