HTML or JavaScript: How to trigger download of .txt file when HTML button is clicked?

What I’m doing is triggering the download of a .txt file when the HTML button is clicked and the text in the file is a string typed in the HTML text field. But I don’t know if I should use HTML or JavaScript code and I don’t know how to code it.

I read the question and it’s pretty much the same except that the text of the .txt file to download is a string typed into the HTML text field.

My code:

HTML code:

<form action="/a" method="POST">
  <input
    type="text"
    value="String"
    name="string"
  />

  <input type="submit" value="Submit" />
</form>

How to trigger download of .txt file when HTML button is clicked? I would appreciate any help. Thank you in advance!

>Solution :

Depending on your file type, modify the type to fit, here’s a list of MIME types https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

To download the file as html, modify the type to be text/html

<form action="/a" method="POST">
<input
    type="text"
    value="String"
    name="string"
    id="filename"

/>

<input type="submit" value="Submit" />
</form>
<script>
document.querySelector("form").addEventListener("submit", (e) => {
    e.preventDefault();
    const string = document.querySelector("#filename").value;
    const element = document.createElement("a");
    const file = new Blob([string], { type: "text/plain" });
    element.href = URL.createObjectURL(file);
    element.download = "test.txt";
    document.body.appendChild(element); // Required for this to work in FireFox
    element.click();
});
</script>

Leave a Reply