FormData and checkboxes

Try this:

var checkbox = $("#myForm").find("input[type=checkbox]");
$.each(checkbox, function(key, val) {
    formData.append($(val).attr('name'), this.is(':checked'))
});

It always adds the field to FormData with either a value of true when checked, or false when unchecked.


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.

Tags:

Javascript