Convert Form Data to JSON in JavaScript

Let’s start we have a simple form.

<form id="contactForm">
    <div class="form-control">
        <label for="name">Name</label>
        <input id="name" name="name" type="text" />
    </div>
    <div class="form-control">
        <label for="email">Email</label>
        <input id="email" name="email" type="email" />
    </div>
    <div class="form-control">
        <label for="message">Remark</label>
        <textarea id="remark" name="remark" rows="6" cols="65"></textarea>
    </div>
    <button class="btn" type="submit">Submit</button>
</form>

Converting FormData to JSON

<script type="text/javascript">
  const form = document.getElementById('contactForm');
  form.addEventListener('submit', callbackFunction);
  function callbackFunction(event) {
     event.preventDefault();
     const myFormData = new FormData(event.target);
     const formDataObj = {};
     myFormData.forEach((value, key) => (formDataObj[key] = value));
     console.log(formDataObj);
  };
</script>

Output

{
name: 'test', 
email: '[email protected]', 
remark: 'temark '
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments