javascript

FormData and checkboxes


Currently when creating a FormData object, a checked checkbox is added with a value of "on", and an unchecked checkbox is not passed at all.

Do I have to hack in some hidden inputs to properly set checkboxes, or is there some customization I can do with FormData, or pre processing?

I would prefer a checked checkbox to be 1 and an unchecked to be 0. I can already do this myself (ie ugly hack), but I don't see any native way with FormData.

form.addEventListener("submit", function(e) {
  e.preventDefault();
  const data = new FormData(form);
  for (const [name,value] of data) {
    console.log(name, ":", value)
  }
})
<form id="form">
     <input name="normal" type="text" value='example' />
     <input id="inpt" name="on" type="checkbox" />
     <label for="inpt">on</label>
     <br /><button type="submit">submit</button>
</form>


Solution

  • Currently when creating a FormData object, a checked checkbox is added with a value of "on", and an unchecked checkbox is not passed at all.

    on is only used if the checkbox is missing a value attribute

    Do I have to hack in some hidden inputs to properly set checkboxes

    No. That is properly handling checkboxes. It is how they have worked in forms since the form element was added to HTML.

    Test for the presence or absence of the checkbox in the code that handles it.