Convert FormData to JSON
You guessed it! This is how you convert FormData to json. Yippee!
Make a form
<form id="yowza">
<input name="author" value="Tolkien" />
</form>
Capture the Submit
Now intercept that submit event:
function handleSubmit(evt) {
evt.preventDefault()
const json = formatForm(evt.target)
// ...ajax submit, or whatever
}
document.getElementById('yowza')
.addEventListener("submit", handleSubmit);
Convert Form Data
How do you get form data? Well, there's a nice API called FormData
. Let's instantiate that, pass our form to it, then call FormData.entries()
to get JSON out:
function formatForm(form) {
return Array.from(new FormData(form).entries()).reduce((acc, entry) => {
return {
...acc,
[entry[0]]: entry[1]
}
}, {})
}
Yielding something like:
{ name: 'Tolkien' }
JSON!, into the wild, blue yonder.