Download content in file using javascript/jQuery

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"/>

 <script> 
    function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename);
       element.style.display = 'none';
       document.body.appendChild(element);
       element.click();
       document.body.removeChild(element);
   }

   // 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); 
</script> 

Try it yourself.