Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

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.

Solution 3:

I took a slightly different approach from the existing answers. I am creating my form data variable the standard jQuery way inside my form submit event handler:

var form = $(this).get(0);
var formData = new FormData(form);

Based on Quentin's answer, saying that it is only set to 'on' when the value attribute is not available, I just added a document event on change to all checkboxes to set the value when the user checks or unchecks the input.

$(document).on("change", "input[type='checkbox']", function () {
    var value = $(this).prop('checked');
    $(this).val(value);
});

When my form data object is created in the above way, all checked checkboxes now have the value of 'true' rather than 'on'.

This worked quite nicely for my purposes and seems to me to be a pretty simple fix. Interestingly, having value='false' doesn't do anything as the input is just ignored and not added to the form data object if it is not checked. But obviously that still works.

Post a Comment for "Formdata And Checkboxes"