How to download file using Javascript/jQuery

This article will help you to download input/textarea field values using Javascript or jQuery on click event.

For this purpose, we create a function download(). In this function, we have created an anchor tag using the createElement method then we set href and download attributes and values to this anchor element after that we append this anchor element to the body of the HTML document. After that, we call the click method on this anchor tag and remove this element from the HTML document. After click the download button, it will dynamically generate a file with input/textarea content and that will be downloaded as file.txt.

 

<!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>
Tags : javascrpt jQuery

Related Post

Position sticky for complex table header
Maksud

Maksud

I am a thinker, not a talker.