I have an html form with some inputs that I'd like the user to be able to download as a text file.
<form onsubmit="download()" action=''>
<input type="text" id="name">
<input type="text" id="age">
<input type="text" id ="sex">
<button type="submit" id="submit-button">Download</button>
</form>
The javascript to download the file is as follows
function download() {
var _text = makeString();
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(_text));
element.setAttribute('download', 'example.txt');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function makeString() {
return "Name: " + $("#name").val() + "\nAge: " + $("#age").val() + "\nSex: " + $("#sex").val();
}
If I enter into these inputs the values John
, 25
, and Male
, and hit download, I end up with a file that looks like
Name: JohnAge: 25Sex: Male
. What's happening to the newlines here? And what can I do to keep them in the file? Thanks!
The part of my code that creates the text file and downloads it is from an answer to this post, which is at least 4 years old. There may very well be a better way to do this and I'm open to suggestions on that front as well.