How to save HTML form data to a text file using JavaScript?

To save HTML form data to a text file using JavaScript, gather all fields into a Blob, then create a link with href=createObjectURL(blob), finally click() the link in code.

Here's how you do it:

<form id="form">
  <label>Some Input:</label>
  <input id="input" required>
  <br />
  <label>Some Select:</label>
  <select id="select">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
  </select>
  <br />
  <button>Submit</button>
</form>
<script>
document.getElementById("form").addEventListener("submit", event => {
  event.preventDefault();

  const link = document.createElement("a");
  link.download = 'form.txt';
  link.href = window.URL.createObjectURL(
    new Blob([ [
      document.getElementById("input").value,
      document.getElementById("select").value
    ].join('\n') ],
    { type: 'text/plain' })
  );
  link.style.display = "none";
  document.body.appendChild(link);

  link.click();
  link.remove();
});
</script>

Try it out live!