When pasting data from the clipboard into an html textarea, it does some pretty cool parsing to make the paste look close to what was copied as far as newlines go.
For example, I have the following html on a page that I select (everything highlights in blue) and then I copy
it:
Hello
<br>
<br>
<br>
<div>more</div>
<div>last</div>
So to be clear, what I am copying is what the output of this jsfiddle looks like.
Now when I paste this magical, copied text into a text area, I see exactly what I would expect: "Hello", empty line, empty line, empty line, "more", "last"
. Cool! Then when I use jQuery's .val() on the textarea, I get "Hello\n\n\nmore\nlast"
. Super cool. It took the br
's and div
's and was able to infer the correct newlines from it.
Now...
What I am trying to do it programmatically take the same data I copied earlier and set it as the textarea's value as if it were pasted.
Here is what I have tried...
So, say the stuff I copied earlier was wrapped in a <div id="parent">...</div>
.
var parent = $("#parent");
var textarea = $("#theTextArea");
// Set the value of the text area to be the html of the thing I care about
textarea.val(parent.html());
Now I know this isn't the same as a copy-paste, but I was hoping it would take care of me and do what I wanted. It doesn't. The textarea gets filled with Hello<br><br><br><div>more</div><div>last</div>
. The html that was once invisible is now stringified and made part of the text.
Obviously I did this wrong. .html() returns, of course, the string of html. But is there something I could call on parent
that would give me the text with all inferred linebreaks?. I have tried calling parent.text()
, but this only gives Hellomorelast
(no line breaks).
A few notes that could help with an answer: I am using Angular, so I have access to all their goodies and jQuery.
from the contenteditable div was to throw it all in a textarea programmatically and then get the data from there.