DEV Community

Discussion on: How to use the FormData object

Collapse
 
birajmainali profile image
Biraj Mainali

Also we can do like this...

 <form id="data--json">
   <input type="text" id="FirstName" value="John" />
   <input type="text" id="LastName" value="Smith" />
 </form>

Enter fullscreen mode Exit fullscreen mode
const jsonForm = () => {
  let data = {};
  const formElem = document.querySelectorAll("#data--json > input");
  for (let i = 0; i < formElem.length; i++) {
    const key = formElem[i].getAttribute("id");
    const elem = formElem[i];
    data[`${key}`] = elem.value;
  }
  return data;
};

console.log(jsonForm());
Enter fullscreen mode Exit fullscreen mode
Collapse
 
davidskuza profile image
David Skuza

You can do Object.fromEntries(new FormData(document.querySelector('#data--json')))