Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  187] [ 7]  / answers: 1 / hits: 29658  / 9 Years ago, mon, november 2, 2015, 12:00:00

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>




More From » javascript

 Answers
13

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.


[#64532] Friday, October 30, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronaldo

Total Points: 694
Total Questions: 85
Total Answers: 103

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;