CKTIS / JavaScript
Disabling HTML form controls with `disabled`
Use `disabled` to make an HTML form control unavailable for user interaction and exclude it from validation and form data. The `.disabled` property and `:disabled` selector answer different questions.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
<input name="city" disabled>
<script>
const input = document.querySelector('input[name="city"]');
input.disabled = true;
input.disabled = false;
input.matches(":disabled");
</script>disabled is a Boolean HTML attribute: its presence counts, so even disabled="false" disables the element. It applies to elements such as input, button, select, textarea, and form-associated custom elements. The rules for option and optgroup are separate: a disabled optgroup makes its options unselectable without disabling the select itself.
A disabled fieldset disables its descendant controls except those inside its first legend element child, if any. On an input, .disabled reflects only the input's own attribute: true adds it and false removes it. Use input.matches(":disabled") to check the effective state, including the effect of a fieldset.
Users cannot focus or normally operate a disabled control, but scripts can still change, for example, input.value. The browser skips a disabled control during constraint validation and when building form data, including with new FormData(form). By contrast, on supported text-entry controls, readonly prevents user edits and excludes the control from constraint validation, but does not by itself prevent focus or exclude it from form data.
These are web-platform features, not ECMAScript features. Disabling a control is not a security boundary: validate data and enforce permissions on the server.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Disabled form control</title>
</head>
<body>
<script>
const form = document.createElement("form");
const group = document.createElement("fieldset");
const input = document.createElement("input");
input.name = "city";
input.value = "Oslo";
group.append(input);
form.append(group);
const report = () => console.log(JSON.stringify([
input.disabled,
input.matches(":disabled"),
input.willValidate,
new FormData(form).has("city")
]));
group.disabled = true;
report();
group.disabled = false;
report();
</script>
</body>
</html>Result
[false,true,false,false] [false,false,true,true]
Each line shows `.disabled`, whether `:disabled` matches, `.willValidate`, and whether the `city` entry is present, in that order. Enabling the `fieldset` changes the last three results; the input never has its own `disabled` attribute.
Related lessons
- JavaScript · Lesson 20 · Intermediate · Version: 3
- JavaScript · Lesson 21 · Intermediate · Version: 3