4

I'm looking for help w/ a script that will allow users to download the output from a text area (by prompting them to save it) by clicking on my "Export" button.

<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="OUTPUT">
</textarea>

Closest I've gotten to an answer is this below, but obviously it's creating a file, not using my output:

var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'}));
a.download = 'test.csv';

// Append anchor to body.
document.body.appendChild(a)
a.click();

// Remove anchor from body
document.body.removeChild(a)

Any help would be greatly appreciated.

  • 1
    Check this blog post http://cwestblog.com/2014/10/21/javascript-creating-a-downloadable-file-in-the-browser/ will get you on the way. – Jim Oct 23 '16 at 01:01
  • Possible duplicate of [Download textarea contents as a file using only Javascript (no server-side)](http://stackoverflow.com/questions/609530/download-textarea-contents-as-a-file-using-only-javascript-no-server-side) – repzero Oct 23 '16 at 01:05

2 Answers2

4

Using your method, just pass the value of the textarea into the createObjectURL function.

<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="This text will be downloaded as a file.">
</textarea>

<br>
<button id="download">Download</button>

<script>
document.getElementById('download').addEventListener("click", download);

function download(){
    var text = document.getElementById('output');
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(new Blob([text.value], {type: 'text/plain'}));
    a.download = 'test.txt';

    document.body.appendChild(a)
    a.click();
    document.body.removeChild(a)
}
</script>
Leander
  • 508
  • 6
  • 21
  • This works in Chrome. More details of the function createObjectURL here: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL – Joseph Shih May 30 '18 at 05:51
1

Try this:

var txt  = document.getElementById('content').value;

document.getElementById('link').onclick = function(){
    this.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt);
};

document.getElementById('content').onchange = function(){
    txt = document.getElementById('content').value;
};
<body>

    <div>
 <textarea id="content">Hello World</textarea>
    </div>

    <a href="" id="link" download="content.txt">Download</a>
  
</body>
Jim
  • 2,974
  • 2
  • 19
  • 29