Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData and checkboxes

Tags:

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.

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.

like image 611
BarryBones41 Avatar asked Nov 02 '15 21:11

BarryBones41


People also ask

How submit form if checkbox is checked?

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.

What value does a checkbox return?

Return Value: It returns a string value that represents the value of the value attribute of a input checkbox field.

How do I keep a checkbox checked in HTML?

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.


2 Answers

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.

like image 88
Quentin Avatar answered Sep 21 '22 09:09

Quentin


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.

like image 37
misha Avatar answered Sep 19 '22 09:09

misha