• Home
  • Save form data to text file html JavaScript

Save form data to text file html JavaScript

In order to save form data to a text file using HTML and JavaScript, you can use the FileSystem or Blob objects in JavaScript, along with the FormData object to gather the data from the form.

First, you will need to create an HTML form with the necessary input fields. You can then use JavaScript to access the form data and create a new FormData object. You can then append the form data to this object using the append method.

Once you have the data in the FormData object, you can then create a new Blob object that will hold the data from the form. You can use the Blob constructor to do this, passing in the FormData object and the type of file you want to create, such as “text/plain” for a plain text file.

Next you can use the URL.createObjectURL() method to generate a URL that can be used to download the text file to the user’s local machine. It’s a one-time-use URL, so you can create the link to download and on the click of that link download the file and revoke the URL using URL.revokeObjectURL()

Finally, you can use the FileSystem object to save the Blob object to a file on the user’s local machine. This can be done using the FileSystem.createFile method, which takes the file name and the Blob object as its arguments. The file will be saved in the user’s browser.

Here is an example of how you could implement this functionality in your HTML and JavaScript code:

 

<form id="form">
<input type="text" id="name" name="name" placeholder="Name">
<input type="text" id="email" name="email" placeholder="Email">
<button id="submit">Submit</button>
</form>
const form = document.getElementById("form");
form.addEventListener("submit", function (e) {
e.preventDefault();
const formData = new FormData();
formData.append("name", document.getElementById("name").value);
formData.append("email", document.getElementById("email").value);
const blob = new Blob([formData], { type: "text/plain" });
const objectURL = URL.createObjectURL(blob);
// create a download link and download the file.
//revoke the object url
URL.revokeObjectURL(objectURL);
});

Keep in mind this approach is not reliable in all browsers, more over this will only work on client side and will not store the data in any server, if you want to store data on server you should make a http request to server and store the data on server.