Download content in file using javascript/jQuery

Created at 07-Sep-2020 , By samar

This article will help you to download textarea field value on click of download button using javascript. For this purpose we have to create textarea input field to get the data (text) from user and a button to download its content on click of this button. 

Javascript download function takes two arguments first the name of file(hello.txt) and the second the text value which we have to download. In this function we have  created an anchor tag using createElement method  than we set href and download attibute and values to this anchor element after that we  append this anchor element to body of HTML document. Now the anchor tag is created and after that we call the click method on this anchor tag and remove anchor element from the HTML document. After click event on anchor tag your file will be downloaded. 


Copy code and paste it into your html file and your code is ready to work.


<textarea id="text-val" rows="4">This is the content of my file</textarea><br/>
<input type="button" id="dwn-btn" value="Download dinamically generated text file"/>

    function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename); = 'none';

   // Start file download.
   document.getElementById("dwn-btn").addEventListener("click", function(){
        // Generate download of hello.txt file with some content
       var text = document.getElementById("text-val").value;
       var filename = "hello.txt";
       download(filename, text);
   }, false); 

Try it yourself.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.