1 | initial version |
For example:
<input type="checkbox" name="fruits[]" value="apple">
<input type="checkbox" name="fruits[]" value="banana">
<input type="checkbox" name="fruits[]" value="orange">
Note that the name attribute is "fruits[]" which indicates that this is an array of values.
For example:
<form>
<input type="checkbox" name="fruits[]" value="apple">
<input type="checkbox" name="fruits[]" value="banana">
<input type="checkbox" name="fruits[]" value="orange">
<button type="submit">Submit</button>
</form>
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(form);
fetch('http://example.com', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
});
This code listens for the form's submit event and prevents the default behavior. It then creates a new FormData object from the form, which includes all the selected checkboxes. The fetch method is used to make a POST request to the server with the FormData object as the payload. Finally, the response from the server is logged to the console.