Hiro
Hiro

Reputation: 11

Is it possible to save texts from input value on html and write on local txt file by using JavaScript?

Is it possible to save texts from input value on html and write on local txt file by using JavaScript?

Also I want to know if there is best way to do what I want to achieve by using other backend language.

Upvotes: 1

Views: 25

Answers (1)

Paul Martin
Paul Martin

Reputation: 469

Full explanation with working example here: https://robkendal.co.uk/blog/2020-04-17-saving-text-to-client-side-file-using-vanilla-js

HTML

<fieldset>
  <legend>Enter some config details</legend>
  <textarea></textarea>
  <button id="btnSave">save config</button>
</fieldset>

JS

const downloadToFile = (content, filename, contentType) => {
      const a = document.createElement('a');
      const file = new Blob([content], {type: contentType});
      
      a.href= URL.createObjectURL(file);
      a.download = filename;
      a.click();
    
        URL.revokeObjectURL(a.href);
    };
    
    document.querySelector('#btnSave').addEventListener('click', () => {
      const textArea = document.querySelector('textarea');
      
      downloadToFile(textArea.value, 'my-new-file.txt', 'text/plain');
    });

Upvotes: 1

Related Questions