Site icon ParallelCodes

Javascript – Create and Download Text file

The more I learn Javascript, more I love it. Today we will see a very simple code which will help us to create and download a text file using only Javascript. The code has a HTML input textbox to accept user data, which on clicking a button will be created into a text file and downloaded in user’s browser. So let’s create it.

For achieving this functionality we will use Blob object which will contain the data to be downloaded into text file. Also, this code is working on Google chrome, Firebox, Microsoft Edge and Opera browser, only not on Internet explorer.

Index.html:

<html>

<head>
<title>Javascript - Create Text file</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}

textarea {
font-family: Arial, Helvetica, sans-serif;
padding: 5px;
}
</style>
</head>

<body>
<p>Enter your text:</p>
<p><textarea id="txtData"></textarea></p>
<button type="button" id="btnSave" onclick="save()">SAVE</button>

<script>

function save() {
var data = document.getElementById("txtData").value;
var c = document.createElement("a");
c.download = "user-text.txt";

var t = new Blob([data], {
type: "text/plain"
});
c.href = window.URL.createObjectURL(t);
c.click();
}
</script>
</body>

</html>

The save() get called on clicking the button.

Output:

Reference: StackOverflow answers.

Also see:

Javascript Capitalize first letter of each word in a string.

Javascript – Replace Forward slashes in a string.

Javascript – How to filter an Array?

Creating a minimal clock with Javascript.

 


Exit mobile version