How to download file using Javascript/jQuery
Javascript

How to download file using Javascript/jQuery

This article presents a streamlined approach to download input/textarea field values using JavaScript or jQuery upon a click event.

To achieve this, we define a function called download(). Within this function, we utilize the createElement method to instantiate an anchor tag. Subsequently, we set the necessary href and download attributes along with their corresponding values for the anchor element. This anchor element is then appended to the body of the HTML document.

Upon invoking the click method on this anchor tag, the element is promptly removed from the HTML document. Upon clicking the download button, a file named 'file.txt' is dynamically generated, containing the content of the input/textarea field, and automatically downloaded.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Download Content</title>
</head>
<body>
    
<textarea id="downloadMe" class="form-control">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Vel, mollitia aspernatur tempora sed hic saepe aut expedita nemo numquam voluptate rem autem voluptatem non obcaecati nam esse! Voluptas, atque aperiam.</textarea><br/>
<button type="button" id="download-btn">Click To Download</button>

 <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 using javascript.
   document.getElementById("download-btn").addEventListener("click", function(){
        // Generate download of hello.txt file with some content
       var text = document.getElementById("downloadMe").value;
       var filename = "file.txt";
       download(filename, text);
   }, false);

   //using jQuery
    $("#download-btn").click(function(){
        var text = $("#downloadMe").val();
        var filename = "file.txt";
        download(filename, text);
    });
</script>
</body>
</html>

Thanks for your time. Have a nice day. You can also check our others coding solutions.

Get The latest Coding solutions.

Subscribe to the Email Newsletter