Ethan Vander Horn Ethan Vander Horn - 17 days ago 5
Javascript Question

How do I preserve line breaks when getting text from a textarea?

I am getting the value in a textarea when the user hits submit. I then take this value and place it elsewhere on the page. However, when I do this, it loses newline characters making the output pretty ugly.

Here is the textarea I am accessing:

<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required></textarea>


Here is the JavaScript code accessing the post and transcribing it.

var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.append(postText);
var card = document.createElement('div');
card.append(post);
var cardStack = document.getElementById('#card-stack');
cardStack.prepend(card);


When the input is something like:


Group Schedule:

Tuesday practice @ 5th floor (8 pm - 11 pm)

Thursday practice @ 5th floor (8 pm - 11 pm)

Sunday practice @ (9 pm - 12 am)


The output is:


Group Schedule: Tuesday practice @ 5th floor (8 pm - 11 pm) Thursday practice @ 5th floor (8 pm - 11 pm) Sunday practice @ (9 pm - 12 am)


So is there a way to preserve line breaks?

Answer

The target container should have the white-space:pre style. Try it below.

<script>
function copycontent(){
 var content = document.getElementById('ta').value;
 document.getElementById('target').innerText = content;
}
</script>
<textarea id='ta' rows='3'>
  line 1
  line 2
  line 3
</textarea>
<button id='btn' onclick='copycontent();'>
Copy
</button>
<p id='target' style='white-space:pre'>

</p>

Comments