You want to prevent input to a form field, but all the solutions have side effects:
- The
[readonly]attribute is only available for text fields, but not for checkboxes, selects, buttons, etc. - The
[disabled]attribute is available for all kinds of fields, but will no longer include the field value in the submitted form data. -
pointer-events: nonestill allows keyboard input, and does not indicate disabledness visually, or to screen readers.
Yet another tool is to use the
[inert] attribute
Show archive.org snapshot
:
<select inert name="foo">...</select>
The presence of the attribute prevents mouse and keyboard interaction with the field.
Styling inert fields
There are no built-in styles to indicate inertness visually. It's up to you to write some CSS for that, for example:
[inert] {
opacity: 0.5;
filter: grayscale(100%);
}
Accessibility considerations
Marking elements as inert has a caveat for accessibility: Inert elements are completely removed from the accessbility tree that the screen readers read and interact with. In the example above, screen readers will no longer announce the inert field. It might might as well be removed from the page.
This behavior is OK if the fields might as well be hidden, and you're just looking for a way to make toggling less jarring for visual users.
Depending on your requirements, you may prefer screen readers to announce the field as present, but disabled. This cannot be achieved with the [inert] attribute.