1

I want to create a text file from Javascript. The user will submit a form, the form will have multiple choices. The user will select the appropriate answers and click on submit button. Now these answers will be put in that text file. For designing this, I have created the HTML file. Now I have a problem with the Javascript. Please tell me, is there any other way instead of JavaScript?

7
  • duplicate? stackoverflow.com/questions/8178825/… Commented Jul 20, 2013 at 5:15
  • the other way is to use server-side script, e.g. PHP Commented Jul 20, 2013 at 5:19
  • Why do you want to create a text file. Commented Jul 20, 2013 at 5:19
  • 1
    Why do you need the text file? Is it just to provide some persistence, or will there be other content? For persistence you can use localStorage or the filesystem API. If you're trying to provide a document that the user can access outside the browser you will have to send it via a server. Commented Jul 20, 2013 at 5:20
  • @Vinay: I'm not sure that the answers on that one are that great or current. I figure if there's not a better question more recent it might be worth the revisit. Commented Jul 20, 2013 at 5:48

1 Answer 1

3

With a String of whatever text you want

var str = 'Hello world!';

1. Create a Blob with MIME type of text/plain

var b = new Blob([str], {type: 'text/plain'});

2. Generate a URL from your Blob

var fileURL = URL.createObjectURL(b);

3. Point your user to it in your favourite way, e.g.

window.open(fileURL, '_blank');

OR, if you want to download this

var a = document.createElement('a'),
    e = document.createEvent("MouseEvents");  // simulated click
e.initMouseEvent("click", true, false, self,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.setAttribute('href', fileURL);
a.setAttribute('target', '_blank');           // fallback behaviour
a.setAttribute('download', 'myTextFile.txt'); // file name
a.dispatchEvent(e);                           // download
Sign up to request clarification or add additional context in comments.

1 Comment

@downvoter please explain why you've down voted this answer; it creates a text file in JavaScript in the client's browser, as requested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.