Logo

Can HTML checkboxes be set to readonly?

HTML does not support a readonly attribute for checkboxes. Unlike text inputs, <input type="checkbox"> only recognizes attributes such as checked, disabled, and required—but there’s no built-in way to make a checkbox “read-only.” Below are a few ways you can simulate a read-only checkbox.

1. Use disabled

<input type="checkbox" name="myCheckbox" checked disabled>
  • Pros: The checkbox is visibly “off” (gray in many browsers), and the user can’t change it.
  • Cons: Because it’s disabled, its value won’t be submitted when the form is posted. If you need the value on the server side, this might be an issue.

2. Use Hidden Fields to Preserve Value

If you want a read-only appearance but still post the value, combine disabled with a hidden field:

<input type="checkbox" checked disabled> <input type="hidden" name="myCheckbox" value="on">
  • Behavior: The user sees a disabled (grayed-out) checkbox, which they cannot toggle, and the hidden field ensures “on” is sent with the form.

3. Block User Interaction via CSS / JavaScript

If you’d prefer the checkbox not appear disabled, you can block pointer events or revert changes via JavaScript:

<style> .checkbox-readonly { pointer-events: none; /* Disables clicks */ opacity: 1; /* Keeps normal appearance */ } </style> <input type="checkbox" class="checkbox-readonly" checked name="myCheckbox" />
  • Pros: Visually looks like a normal checkbox but cannot be changed by the user.
  • Cons: Since it’s not truly disabled, it will submit its value as either checked or unchecked. This can be good if you want the data posted, but keep in mind the user can see it’s visually clickable unless you also change the cursor or style.

4. Revert Changes in onclick or onchange

Using JavaScript, you can prevent any actual change from persisting:

<input type="checkbox" id="myCheckbox" checked name="myCheckbox" onclick="return false;" />
  • Behavior: Clicking the checkbox won’t toggle it. It remains in its original state.
  • Trade-off: Slightly hacky, but simple if you want to keep a normal look without re-styling.

Best Approach?

  • If you don’t need to submit the checkbox’s state, use disabled.
  • If you do need it submitted, but unchangeable, consider a hidden field or pointer-events: none so the user sees it, but can’t change it.

Level Up Your Web & JavaScript Skills

Deepen your understanding of JavaScript, DOM manipulation, and interactive web design by exploring courses at DesignGurus.io:

For more coding practices and system design insights, check out the DesignGurus.io YouTube channel. By carefully choosing how you simulate a read-only checkbox, you’ll maintain both clarity for the user and control over how data is submitted.

CONTRIBUTOR
TechGrind