I want to be able to write some text in a textarea and click a button to have the browser download a .txt file with the text I wrote in my textarea.
I have no idea how to go about this. What should I try? Is there any way I cam have it downloaded to me without using a database or a server?
I want to be able to write some text in a textarea and click a button to have the browser download a .txt file with the text I wrote in my textarea.
I have no idea how to go about this. What should I try? Is there any way I cam have it downloaded to me without using a database or a server?
Share asked Dec 4, 2020 at 3:14 CoolsugarCoolsugar 1701 gold badge2 silver badges11 bronze badges 1- 3 get text from textarea frist. and follow like here stackoverflow./questions/45789444/… – Hyunjune Kim Commented Dec 4, 2020 at 3:24
3 Answers
Reset to default 5To get data from text area:
var textcontent = document.getElementById("textareaID").value;
To download as txt file:
var downloadableLink = document.createElement('a');
downloadableLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(textcontent));
downloadableLink.download = "myFile" + ".txt";
document.body.appendChild(downloadableLink);
downloadableLink.click();
document.body.removeChild(downloadableLink);
You can create an input field with <textarea>
inside it.
Example: HTML
<h2>Create .txt file</h2>
<div>
<label for="fname">File name (without .txt):</label>
<br>
<input type="text" id="fname" name="fname"><br><br>
<label for="fcontent">File Content:</label>
<br>
<textarea id="fcontent" name="w3review" rows="4" cols="50"></textarea>
<br>
<button id="create">Create File</button>
<a download="info.txt" id="downloadlink" style="display: none">Download Here</a>
</div>
Javascript:
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create');
var fileContent = document.getElementById("fcontent");
create.addEventListener('click', function() {
const fileName = document.getElementById("fname").value;
document.getElementById("downloadlink").setAttribute("download", fileName);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(fileContent.value);
link.style.display = 'block';
}, false);
})();
You can see the live demo here.
NOTE: If you want to make an HTML file be the default instead of a .txt file, you can do that by changing the type: 'text/plain'
in the JavaScript file into type: 'text/html'
See the working example on JSFiddler
Javascript/JQuery
$('#mybutton').click(function(){
var data = $('#mytextarea').val();
this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent(data);
});
HTML
<textarea id="mytextarea"></textarea>
<a id="mybutton" href="" download="output.txt">Export to .txt</a>