How to make 'Save' button to save HTML Input (type="text") value to seperate .txt file (JavaScript)

How to make 'Save' button to save HTML Input (type="text") value to seperate .txt file (JavaScript)

  

I have issues with making 'Save' button to save my HTML Input (type="text") value to seperate .txt file.

Can someone with enough JavaScript experience and knowledge help me with this problem, thanks in advance.

I wrote my HTML code for both input and button

<input class="test" type="text" id="test1" value="123">
<button class="savebutton">Save</button>

Answer

You can use the following code to save the text to a .txt file.

>document.querySelector('button.savebutton').addEventListener('click', function() {
    const txt = document.querySelector('input.test#test1').value;
    // make a data url out of the text
    const url = "data:text/plain;base64," + btoa(txt);
    // create a element that is hidden and used to download the file at the url
    const a = document.createElement("a");
    a.href = url;
    a.download = "myfile.txt";
    a.hidden = true;
    document.body.appendChild(a) // add the download element to body
    a.click(); // click the element from js to download the file
    a.remove(); // remove the element
});

Explanation

This code gets a data url for the text using btoa, then creates a hidden a element and adds the url to it and set the file name to myfile.txt. It then clicks it to start the download and removes the element.

I hope this helps.

© 2024 Dagalaxy. All rights reserved.