Kolawole Emmanuel Izzy
Kolawole Emmanuel Izzy

Reputation: 1052

Downloading Textarea Contents with line breaks in jQuery

I'm trying to download the content of a textarea on button click to a .txt file in jQuery. I was able to use the following code from this question

and i was able to use this code;

$("#downloadtext").click(function() {
// create `a` element
$("<a />", {
    // if supported , set name of file
    download: $.now() + ".txt",
    // set `href` to `objectURL` of `Blob` of `textarea` value
    href: URL.createObjectURL(
      new Blob([$("#textarea-content").val()], {
        type: "text/plain"
      }))
  })
  // append `a` element to `body`
  // call `click` on `DOM` element `a`
  .appendTo("body")[0].click();
  // remove appended `a` element after "Save File" dialog,
  // `window` regains `focus` 
  $(window).one("focus", function() {
    $("a").last().remove()
  })
  });

I'm not sure why the downloaded file has no line break even when the content in the textarea has a line break. it looks like this[see image below];

enter image description here

But i would want it to look like this;

enter image description here

Not sure what is missing in the code above or why it is stripping out the line breaks.

Your helping point me in the right direction is highly appreciated.

Upvotes: 1

Views: 189

Answers (1)

Alex
Alex

Reputation: 1423

this should work:

    new Blob([$("textarea").val().replace(/\r?\n/g, '\r\n')], {
      type: "text/plain"
    }))

Upvotes: 2

Related Questions