I want to Getting all selected checkboxes in an array to POST
to API by urlencoded.append
urlencoded.append("typeID", (document.getElementById("type").value==1?"1":document.getElementById("type").value==2?"2":"3"));
<div id="myDiv">
<input type="checkbox" name="name" value="1" id="type-id">
<label>Food Deals</label>
<br>
<input type="checkbox" name="name" value="2" id="type-id">
<label>Groceries Deals</label>
<br>
<input type="checkbox" name="name" value="3" id="type-id">
<label>Karam Box</label>
<br>
</div>
prepended EDIT
It looks like the OP already has access to a FormData
instance which in the OP's example code gets referred to as urlencoded
.
Thus in order to provide a quick fix for the OP's code, a solution might look like this ...
// make an array from the ...
Array.from(
// ... node list of every checked
// ckeckbox control withing the #myDiv element ...
document.querySelectorAll('#myDiv [type="checkbox"]:checked')
)
.reduce((formData, control) => {
// ... and append key/name and value to `formData` ...
formData.append(control.name, control.value);
return formData;
// ... which is represented by the `urlencoded` object
// that got provided as the `reduce` task's initial value.
}, urlencoded);
Further below one finds a fully-fledged and working example code in order to study the use of XHR
and FormData
.
+++ edit end +++
In addition to the logging check your DevTools
Network
tab as well. One should be able to inspect a failed (404) POST
request to https://stacksnippets.net/
but with the correctly sent form data.
The provided approach uses a form element where it intercepts and prevents the browser's form submit but creates an own XHR from the form's method
and action
values.
In order to collect/aggregate the form data it uses the FormData
Web API. Such an object can be directly passed to the XHR's send
method.
function createXHRFromForm(form) {
const xhr = new XMLHttpRequest;
xhr.open(
form.method,
form.action,
true
);
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
// xhr.onreadystatechange = function() {
// if (
// (this.readyState === XMLHttpRequest.DONE)
// && (this.status === 200)
// ) {
// // handle success
// }
// };
return xhr;
}
function createCheckboxFormData(form) {
// for the given example form
// following line already was sufficient enough
//
// return new FormData(form);
//
// but a custom aggregation is supposed to be shown.
return Array
.from(
form.querySelectorAll('[type="checkbox"]:checked')
)
.reduce((formData, control) => {
formData.append(control.name, control.value);
return formData;
}, new FormData);
}
function handleCheckboxDataSubmit(evt) {
evt.preventDefault();
const form = evt.currentTarget;
const xhr = createXHRFromForm(form);
const formData = createCheckboxFormData(form);
console.clear();
console.log({
entries: [...formData.entries()],
name: formData.getAll('name'),
});
xhr.send(formData);
return false;
}
function main() {
document
.querySelector('form[name="myForm"]')
.addEventListener('submit', handleCheckboxDataSubmit);
}
main();
:not([type="submit"]) {
margin: 0!important;
padding: 0!important;
}
body { zoom: .85; }
label { display: block; cursor: pointer; }
[type="submit"] { margin-top: 3px; }
<form name="myForm" action="/" method="post">
<label>
<input type="checkbox" name="name" value="1" checked/>
<span class="label">Food Deals</span>
</label>
<label>
<input type="checkbox" name="name" value="2" checked/>
<span class="label">Groceries Deals</span>
</label>
<label>
<input type="checkbox" name="name" value="3"/>
<span class="label">Karam Box</span>
</label>
<button type="submit">POST</button>
</form>