Checkbox Technical Notes
Last updated
<script>
const cb = document.querySelector('input[type=checkbox][name=agree]');
const hid = document.querySelector('input[type=hidden][name=agree]');
cb.addEventListener('change', () => { hid.disabled = cb.checked; });
</script><form id="f">
<label><input id="agree" type="checkbox" name="agree" value="1"> I agree</label>
</form>
<script>
const f = document.getElementById('f');
const cb = document.getElementById('agree') as HTMLInputElement;
f.addEventListener('formdata', e => {
e.formData.set('agree', cb.checked ? '1' : '0'); // always one key
});
</script><fieldset aria-describedby="pets-hint pets-err">
<legend>Select your pets</legend>
<p id="pets-hint">Choose all that apply.</p>
<label><input type="checkbox" name="pets" value="dog"> Dog</label>
<label><input type="checkbox" name="pets" value="cat"> Cat</label>
<label><input type="checkbox" name="pets" value="bird"> Bird</label>
<p id="pets-err" class="visually-hidden">You must select at least one.</p>
</fieldset><label><input id="parent" type="checkbox"> Select all</label>
<div>
<label><input class="child" type="checkbox"> A</label>
<label><input class="child" type="checkbox"> B</label>
<label><input class="child" type="checkbox"> C</label>
</div>
<script>
// parent controls children
const parent = document.getElementById('parent') as HTMLInputElement;
const kids = Array.from(document.querySelectorAll<HTMLInputElement>('.child'));
function syncParent() {
const checked = kids.filter(k => k.checked).length;
parent.checked = checked === kids.length && checked > 0;
parent.indeterminate = checked > 0 && checked < kids.length;
}
parent.addEventListener('input', () => {
kids.forEach(k => k.checked = parent.checked);
parent.indeterminate = false;
});
kids.forEach(k => k.addEventListener('input', syncParent));
syncParent();
</script>
<style>
/* optional visual for mixed state */
input[type="checkbox"]:indeterminate { outline: 2px solid #f59e0b; }
</style>
<input type="hidden" name="opt" value="none">
<input id="opt" type="checkbox" name="opt" value="all">
<script>
const cb = document.getElementById('opt') as HTMLInputElement;
// If you use a mixed state, set a separate hidden input to 'mixed'
</script>form.addEventListener('formdata', e => {
let v = 'none';
if (parent.indeterminate) v = 'mixed';
else if (parent.checked) v = 'all';
e.formData.set('opt', v);
});