Hidden input for setting a default value
When a checkbox is inside a form, its FormData shows up as “on” when checked, and null
otherwise, across all browsers.
From MDN:
If a checkbox is unchecked when its form is submitted, neither the name nor the value is submitted to the server. There is no HTML-only method of representing a checkbox’s unchecked state (e.g. value=unchecked). If you wanted to submit a default value for the checkbox when it is unchecked, you could include JavaScript to create a
<input type="hidden">
within the form with a value indicating an unchecked state.
How can we submit a false
value produced by an unchecked checkbox then? We can do the following:
HTML
<form id="form">
<label>
<input name="check" value="false" type="hidden" />
<input id="check" name="check" value="true" type="checkbox" />
Checkbox
</label>
</form>
Javascript
const check = document.querySelector('#check');
const form = document.querySelector('form');
function handleChange(e) {
const obj = {};
for (const [k, v] of new FormData(form)) {
obj[k] = v;
}
document.querySelector('#formdata').innerText = JSON.stringify(obj);
}
handleChange();
check.addEventListener('change', handleChange);
And this would be the result: