Consider a form which has a checkbox that the checked state is controlled by something else. Maybe a "Select/Deselect All" option. Here's a snippet where I've just hardcoded the value of the checkbox input.
<form>
<label for="is-chicken">🐔?</label>
<input name="is-chicken" type="checkbox" checked disabled />
<button type="submit">Submit</button>
</form>
<script>
const form = document.querySelector("form");
form.onsubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const isChicken = formData.get("is-chicken");
console.log(isChicken); // null
};
</script>
I want to make sure that I can block the user from interacting with the checkbox and yet still read the value.
Maybe readonly
would work?
<form>
<label for="is-chicken">🐔?</label>
<input name="is-chicken" type="checkbox" checked readonly />
<button type="submit">Submit</button>
</form>
<script>
const form = document.querySelector("form");
form.onsubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const isChicken = formData.get("is-chicken");
console.log(isChicken); // on
};
</script>
MDN says
The
readonly
attribute is supported bytext
,search
,url
,tel
,password
,date
,month
,week
,time
,datetime-local
, andnumber<input>
types and the<textarea>
form control elements. If present on any of these input types and elements, the:read-only
pseudo class will match. If the attribute is not included, the:read-write
pseudo class will match.
The attribute is not supported or relevant to
<select>
or input types that are already not mutable, such as checkbox and radio or cannot, by definition, start with a value, such as the file input type. range and color, as both have default values. It is also not supported on hidden as it can not be expected that a user to fill out a form that is hidden. Nor is it supported on any of the button types, includingimage
.
When up against this set of requirements, maybe there's a better away to solve the problem.