Explain Codes LogoExplain Codes Logo

Can HTML checkboxes be set to readonly?

html
responsive-design
javascript
best-practices
Alex KataevbyAlex Kataev·Nov 7, 2024
TLDR

HTML checkboxes cannot natively be set as readonly. However, you can prevent direct user interaction using code like onclick="return false" or use disabled. Still need to submit the value? Send the original value using a hidden field mechanism.

<!-- Party pooper checkbox doesn't let you change its checked status --> <input type="checkbox" onclick="return false" checked /> <!-- Hidden accomplice carries the secret value --> <input type="hidden" value="true" name="checkboxName" />

Imitating Readonly Operation

Visual feedback for unchangable checkboxes

If you want to show the unchanged status visually, dim or gray-out the checkbox. This requires some shiny CSS and does not involve disabled.

/* Sodium bulb effect on readonly checkmarks */ input[type=checkbox].readonly + label { color: #cccccc; }

Javascript: the bouncer at the checkbox party

Invoke JavaScript to enforce immutability on the client-side by preventing default actions. The deal is similar to the bouncer at a rowdy party, letting you in but not out.

/* This ain't no party, ain't no disco... No checkboxes are getting checked here, folks! */ let readOnlyCheckboxes = document.querySelectorAll('.readonly-checkbox'); readOnlyCheckboxes.forEach(checkbox => { checkbox.addEventListener('click', e => { e.preventDefault(); }); });

Server-side: The all-seeing eye

For prefab, client-proof checkbox states, use server-side checks. They supervise the integrity of the party so that nobody sneaks through the back door.

Handling Checkbox Exceptions

Checkbox states and form submissions

When you're mimicking readonly with disabled, remember, the checkbox won't submit its value with the form. Using a hidden field resolves this, as it carries the checkbox's value incognito.

The power of hidden inputs

When checkboxes of the same group wear the readonly disguise, match their name attributes, and synchronize them with hidden inputs.

Custom controls: You are the magician!

With HTML, CSS, and JavaScript, create custom checkbox controls that support a readonly state. With great power comes great responsibility, so know your stuff about form control behavior and accessibility.

Securing your Checkbox Fortress

Even though client-side scripts can pose as readonly, always remember to invite the server-side bouncer to your party to prevent unwanted guests. Server-side logic manages checkbox states based on the crowd control rules you set for differentiating between regular guests and VIPs.