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.
If you need to submit a form when a checkbox is checked or when it is unchecked like when you are using a switch, a good way is to create an hidden input. If you try to submit the checkbox argument if the checkbox is unchecked the form will not be submitted at all.
Return Value: It returns a string value that represents the value of the value attribute of a input checkbox field.
The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With