Search code examples
htmlformspostcheckbox

POST unchecked HTML checkboxes


I've got a load of checkboxes that are checked by default. My users will probably uncheck a few (if any) of the checkboxes and leave the rest checked.

Is there any way to make the form POST the checkboxes that are not checked, rather than the ones that are checked?


Solution

  • Add a hidden input for the checkbox with a different ID:

    <input id='testName' type='checkbox' value='Yes' name='testName'>
    <input id='testNameHidden' type='hidden' value='No' name='testName'>
    

    Before submitting the form, disable the hidden input based on the checked condition:

    form.addEventListener('submit', () => {
        if(document.getElementById("testName").checked) {
            document.getElementById('testNameHidden').disabled = true;
        }
    }