Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Saving A File Using Javascript

Regy

Active Coder
I'm trying to save the contents of a textarea in a file. The problem is that the code below creates a file but the file's name is the content of the textarea. It should be myfile.txt.
JavaScript:
<script>
document.getElementById("mybutton").addEventListener("click", buttonclick);
function buttonclick(data, filename, type) {
var filename = "myfile".txt"
var content = document.getElementById("mytext").value;
var file = new Blob([content], {type: type});
var a = document.createElement("a")
url = URL.createObjectURL(file);
a.href = url;
a.download =(filename, content);
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);  
}, 0); 
}
</script>
This code seems to be the problem.
JavaScript:
a.download =(filename, content);
But in the examples online, some coders use just one variable (filename) and some use two (filename, content). So I'm stuck and could use some help. Thanks.
 
Your filename is wrong and you put wrong content in your "a.download".
JavaScript:
<script>
    document.getElementById("mybutton").addEventListener("click", buttonclick);

    function buttonclick(data, filename, type) {
        var filename = "myfile.txt";
        var content = document.getElementById("mytext").value;
        var file = new Blob([content], {type: type});
        var a = document.createElement("a")
        url = URL.createObjectURL(file);
        a.href = url;
        a.download =(content, filename);
        document.body.appendChild(a);
        a.click();

        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }, 0);
    }
</script>
 
"myfile".txt"... That there is proof that I should slow down when I'm coding.

The good news is that it's working perfectly now, so a big thanks goes out to you BGB, it's much appreciated.
 

Latest posts

Buy us a coffee!

Back
Top Bottom