How To Format Form Data as JSON?

To format form data as JSON, follow these steps:

  1. Collect form data: You can either collect form data using HTML form elements like text fields, radio buttons, select boxes, etc. or you can use a JavaScript form library.
  2. Store form data: Store the form data in a JavaScript object. You can use the object to store the values of all the form fields.
  3. Convert form data to JSON: You can use the JSON.stringify() method to convert the form data object to JSON. This method takes the JavaScript object as an argument and returns a JSON string.

Example:

<form id="myForm">
  <input type="text" name="name" id="name">
  <input type="email" name="email" id="email">
  <input type="submit" value="Submit">
</form>

<script>
  document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault();
    var formData = {
      name: document.getElementById("name").value,
      email: document.getElementById("email").value
    };
    var jsonData = JSON.stringify(formData);
    console.log(jsonData);
  });
</script>

In this example, the form data is collected when the form is submitted and stored in the formData object. The JSON.stringify() method is then used to convert the formData object to a JSON string, which is logged to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *