I am trying to serialize some form data and it's working great if there's only one checkbox checked, but if I try to check more than one checkbox it is only getting the value of the first checkbox that is checked.
var serializeForm = function (form) {
var obj = {};
var formData = new FormData(form);
for (var key of formData.keys()) {
obj[key] = formData.get(key);
}
return obj;
};
document.querySelector('#form').addEventListener('submit', function(e) {
e.preventDefault();
let data = JSON.stringify(serializeForm(e.target));
console.log(data);
});
<form id="form">
<label>
Lorem
<input type="checkbox" name="choice[]" value="lorem" checked />
</label>
<label>
Ipsum
<input type="checkbox" name="choice[]" value="ipsum" checked />
</label>
<input type="submit" />
</form>
How can I adjust the serialize function so that it will return both values if both checkboxes are checked?
CodePudding user response:
Use FormData.getAll
to get all values under a specific name as an array. However for "normal" inputs you might want the value as string. I've added a primitive yet effective way to detect by name which method to use: get
or getAll
.
var serializeForm = function(form) {
var obj = {};
var formData = new FormData(form);
for (var key of formData.keys()) {
if (key.endsWith('[]')) {
obj[key] = formData.getAll(key);
} else {
obj[key] = formData.get(key);
}
}
return obj;
};
document.querySelector('#form').addEventListener('submit', function(e) {
e.preventDefault();
let data = JSON.stringify(serializeForm(e.target));
console.log(data);
});
<form id="form">
<input type="text" name="single" value="regular">
<label>
Lorem
<input type="checkbox" name="choice[]" value="lorem" checked />
</label>
<label>
Ipsum
<input type="checkbox" name="choice[]" value="ipsum" checked />
</label>
<input type="submit" />
</form>