DEV Community

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

Collapse
 
tomekdev_ profile image
🤓 Tomek Nieżurawski

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) {
  event.preventDefault();

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

  console.log(object);
});
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 🤷‍♂️