Explain Codes LogoExplain Codes Logo

How do I make a text input non-editable?

html
responsive-design
best-practices
accessibility
Anton ShumikhinbyAnton Shumikhin·Sep 9, 2024
TLDR

Freeze a text input field by applying the readonly attribute:

<input type="text" value="Frozen in time" readonly>

This magical attribute makes the input field immutable, yet still interactable - the field retains its native look and feel - your stylesheet's hard work doesn’t just vanish into a black hole!

Deep Dive

Control Mode: readonly

The readonly attribute is like a friendly security guard. It doesn't lock the door and throw away the key; it simply keeps your value safe, unmodifiable yet easily accessible. Your users can still select and copy it. The input's original styling stays consistent, so no tailoring tricks are needed!

Power move: disabled attribute

When you want your input field to take a nap, throw in the disabled attribute. It makes the field inactive, unselectable, and the tab-key navigates right past it. But, remember this sleepy field stores no data in form submission, it's on nap mode, after all.

The Stylish Way: pointer-events

Now, there's a less spoken secret about the pointer-events: none; CSS rule. It's like a stylist's magic touch - it makes your input slyly ignore pointer events and you got yourself a non-editable yet stylish input field.

Under The Hood

Where readonly shines

When manners matter, readonly's the attribute of choice. It’s silently powerful — no shouting with flashy stylings, no vanishing stunts in form submissions. Simply sits there, protecting your inputs from unwanted edits.

The accessibility factor

In the world of HTML, readonly is the friendly neighbor. It’s accessible, allowing focus and interaction with assistive technologies. Screen readers can still access the content, and keyboard users can smoothly navigate through the field.

The form submission saga

In form submissions, readonly fields pass with flying colors. Unlike the disabled attribute, a readonly input operates like a secret agent, keeping its value hidden but ready for action in a form submission.

The Next Level

The JavaScript Illusionist

For more dynamic interactions, JavaScript becomes your secret wand. You can play around with the readonly status willy-nilly, making your app look alive and kicking, smoothly responding to user actions.

Contextual appearances

Visual cues can be your dress code clue to users. Sometimes, adding subtle color changes or lock icons could enhance the UX while communicating to users about the field's readonly status.

Striking a balance

The appearance of a readonly field should neither be camouflaged nor glaringly conspicuous. It should be visibly distinguishable, with just the right level of emphasis.