How to save form data to a file

Example of saving form data to a text file

by Alexey Demin

HTML

<form id="simpleForm" class="save-as-file-onsubmit prevent-default">
  <p>
    <label for="firstName">First Name</label>
    <input type="text" id="firstName" name="firstName" />
  </p>
  <p>
    <label for="lastName">Last Name</label>
    <input type="text" id="lastName" name="lastName" />
  </p>
  <p>
    <label for="birthday">Birthday</label>
    <input type="date" id="birthday" name="birthday" />
  </p>
  <p>
    <label for="checker">Accept something</label>
    <input type="checkbox" id="checker" name="checker" />
  </p>
  <p>
    <label for="gender">Gender</label>
    <select id="gender" name="gender">
      <option>male</option>
      <option>female</option>
    </select>
  </p>
  <p>
    <label for="description">Description</label>
    <textarea name="description" id="description"></textarea>
  </p>
  <button type="submit" id="formSubmit">OK</button>
</form>

CSS

* {
  font-family: monospace;
}
label {
  display: inline-block;
  float: left;
  width: 150px;
}
form {
  padding: 10px;
  border: 1px solid grey;
  border-radius: 3px;
}

JavaScript

const getFormData = function(form) {
    let formData = new FormData(form);
    let payload = {};
    for (var [key, value] of formData.entries()) {
      payload[key] = value;
    }
    return payload;
  },
  $ = (id) => document.getElementById(id);

document.onsubmit = (event) => {

  const form = event.target;

  if (form.classList.contains('prevent-default')) {
    event.preventDefault();
  }

  if (form.classList.contains('save-as-file-onsubmit')) {

    const payload = JSON.stringify(getFormData(form));
    const url = window.URL.createObjectURL(
      new Blob([payload], {
        // 'application/json' or other MIME-type
        type: 'text/plain'
      })
    );

    const link = document.createElement("a");
    link.download = 'formData.txt';
    link.style.display = "none";
    link.href = url;

    document.body.appendChild(link);

    link.click();
    link.remove();

    window.URL.revokeObjectURL(url);
  }

};