Explain Codes LogoExplain Codes Logo

What is the correct value for the disabled attribute?

html
html5
boolean-attributes
accessibility-standards
Alex KataevbyAlex Kataev·Nov 19, 2024
TLDR

To disable an HTML element, simply use the disabled attribute with no value. This makes the element unusable and unfocusable:

<input type="text" disabled>

This is the most succinct and standard way to disable form elements.

Breaking down the disabled attribute

HTML5 and Boolean attributes

In HTML5, boolean attributes like disabled need no value. They are true if present, false if not:

<button disabled>I'm unclickable!</button>

XHTML's explicitness

Contrarily, in XHTML, a value is required for validity:

<input type="text" disabled="disabled">

This is due to XHTML’s syntax strictness.

Browsers' interpretation

Major browsers comprehend the disabled attribute, irrespective of its form: <input disabled> or <input disabled="disabled">.

What not to do

Avoid non-standard values like true or false. They can breed inconsistency:

<!-- Avoid this! --> <input type="text" disabled="true"> <input type="text" disabled="false">

These values violate HTML specifications.

Dealing with disabled in JavaScript

For dynamic element state changes using JavaScript, the property is set/unset like so:

// How to say "I quit!" in Node.js element.disabled = true; // How to return from retirement. element.disabled = false;

The setAttribute and removeAttribute methods provide attribute control:

// When you really mean it. element.setAttribute('disabled', ''); // When you want to roll back changes. element.removeAttribute('disabled');

MDN documentation (in the references) offers more scripting examples and best practices.

Particular cases to account for

Working with legacy browsers

In the instance of the almost extinct IE11, you might need a true-false value for proper functionality:

<!--Only for the elderly (browsers) --> <input type="text" disabled="true">

Incorporating server-side scripting

For JSP or similar languages that impose attribute values, incorporate the right syntax to avoid server hiccups:

<!-- And now for something completely different --> <input type="text" <%= isDisabled ? "disabled=\"disabled\"" : "" %> >

Prioritizing accessibility

Ensure that your form’s functionality adheres to accessibility standards when using disabled. Offer alternate interaction methods, if necessary.

Special scenarios for the disabled attribute

Custom elements and Frameworks

Custom elements and frameworks like Angular, React, or Vue, may apply disabled differently due to internal abstractions:

// How a disabled button in a React component looks <button disabled={isButtonDisabled}>Please, Do Not Press</button>

Automating tests

When penning automated tests, remember that some frameworks may have specific requirements for handling the disabled attribute.