-2

Java script:

var x = 'demo'

I want a html button from which we can download x as anyname.txt in which the value should be demo

  • 1
    You will need to provide more context, and more code to explain what you are trying to do, and what you have already tried – Lk77 Dec 28 '22 at 16:25
  • Bro like if someone will click to download then the variable value will be downloaded in txt file. Did u understand? – Gunnu Mittal Dec 28 '22 at 16:40
  • update the question then, in the current state of your question, i doubt you will get any answer, at least show some html, your event listener and so on – Lk77 Dec 28 '22 at 16:41
  • https://stackoverflow.com/questions/24898044/is-possible-to-save-javascript-variable-as-file or https://stackoverflow.com/questions/57709550/how-to-download-text-from-javascript-variable-on-all-browsers or https://stackoverflow.com/questions/3665115/how-to-create-a-file-in-memory-for-user-to-download-but-not-through-server – Yarin_007 Dec 28 '22 at 16:58
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Dec 28 '22 at 17:43

1 Answers1

0

In order to download a file when clicked on a button, the file has to exist within our project files (next to your HTML file...). So you're going to have to:

  1. Create a .TXT file yourself and write in it what you need. After that place the file in the same folder as your HTML file.
  2. Create a button in HTML using <a> tag because in order to download it we have to reference the file using href attribute.
  3. In order to download the file we use download attribute. That attribute will download the file with the name that it has. If you want the file to be downloaded as anyname.txt you just have to add a value that you want to the download attribute -> download="Anything you want"

The final code should look like this:

<a href="yourfile.txt" download="Anything you want">Download</a>

Of course, style it in CSS because this looks nothing like a button.

When clicking on this button locally (before publishing you site) it will not download the file because the computer already knows you have it. That's normal. Once published, when someone (even you) click on the button it will download the file as intended.

TheVSDev
  • 112
  • 13