Reputation: 810
I have the HTML code
<span class="editableFalse" id="comments">
Lorem ipsum sit dolor amet
<br/>
Lorem ipsum sit dolor amet
</span>
<textarea id="textareaComments"></textarea>
Now I have to fetch the data from this span and set it to a Textarea below it in the same format, ie along with the newline character.
How to achieve that :
$("#textareaComments").val($("#comments").text());
The above line takes the content from the span but trims off the br tag. I dont get a newline character in the textarea. Any help.
Upvotes: 3
Views: 3099
Reputation: 404
You can use also replaceAll from jQuery I think
$("\n").replaceAll("<br>");
Upvotes: 1
Reputation: 21410
$("#textareaComments").val($("#comments").clone().find("br").replaceWith("\n").end().text())
textarea {
display: block;
width: 100%;
height: 10em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="editableFalse" id="comments">
Lorem ipsum sit dolor amet
<br/>
Lorem ipsum sit dolor amet
</span>
<textarea id="textareaComments"></textarea>
Upvotes: 1
Reputation: 22158
Just use replace:
$("#textareaComments").val($("#comments").html().replace("<br>", "\n"));
Upvotes: 2
Reputation: 4168
var str = $("#comments").html();
var regex = /<br\s*[\/]?>/gi;
$("#textareaComments").val(str.replace(regex, "\n"));
Try the replaces Br
with \n
(new line)
And use .html()
not .text()
Upvotes: 2