DEV Community

Discussion on: If there is an input, there should be a form

whitewcallum580 profile image
Callum White

Just out of interest, how would you extract the values from the form when onsubmit is called?

tomekdev_ profile image
🤓 Tomek Nieżurawski Author

It depends, if I use a framework (say React) I'd just use the state to retrieve the data and don't bother about anything.

In Vanilla solution I'd go for FormData:

const form = document.getElementById('my-form');

form.addEventListener('submit', function handleSubmit(event) {

  const formData = new FormData(;
  const object = {};
  formData.forEach((value, key) => {object[key] = value});

Enter fullscreen mode Exit fullscreen mode

FormData object is not easy to use so in the example above I already "re-write" it to object structure where I can potentially convert it into JSON (through JSON.stringify(object)). Unfortunately, that's not the end of the story if you have to deal with multi-select values but with a little tweak in the forEach callback it can be managed.

So -> FormData unless you already keep the state somewhere 🤷‍♂️