Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  91] [ 5]  / answers: 1 / hits: 57279  / 10 Years ago, tue, july 22, 2014, 12:00:00

Is there a way to convert a string from a JavaScrip variable, into a downloadable file that users can download when clicking a button ?


Thanks for any advice.


<div id="txt">Lorem Ipsum</div>
<br />
<button id="test">Download text as file !</button>

More From » javascript

 Answers
22

Yes it is, you could do something like this in HTML5, using the download attribute


function download_txt() {
var textToSave = document.getElementById('txt').innerHTML;
var hiddenElement = document.createElement('a');

hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.txt';
hiddenElement.click();
}

document.getElementById('test').addEventListener('click', download_txt);

FIDDLE


[#70093] Monday, July 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
naomim

Total Points: 344
Total Questions: 95
Total Answers: 114

Location: Wales
Member since Mon, May 17, 2021
3 Years ago
;