How to get data from a form
Short answer
new FormData(form) collects all fields with a name attribute. Object.fromEntries() turns them into an object:
<form id="signup">
<input name="name" value="Anna">
<input name="email" value="anna@example.com">
<button>Sign up</button>
</form>
<pre id="out"></pre>
<script>
const form = document.getElementById('signup');
form.addEventListener('submit', (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(form));
document.getElementById('out').textContent = JSON.stringify(data);
});
</script>Checkboxes with the same name
Object.fromEntries() keeps only the last value of a repeated name. Use getAll() for groups of checkboxes:
const data = new FormData(form);
const toppings = data.getAll('topping');
const subscribe = data.has('subscribe');One field
A single field can be read through the form's elements collection by its name:
const email = form.elements.email.value.trim();Common mistake
A field without a name attribute does not get into FormData. Also, an unchecked checkbox is not sent at all, so check it with has(), not by its value.
<!-- not in FormData: there is no name -->
<input id="phone" value="555-1234">Functions used in this recipe
- Object.fromEntries — Creates an object from a list of key–value pairs.