1

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!

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, there is a very strange thing. Yesterday this code worked, but today this code doesn't work (never download .txt file) How can I fix this problem?
@MyCar double check all the variable references and make sure you’re passing the right variables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.