HTML textarea to javascript and keep line break
Asked Answered
N

3

5

I am trying to pass a HTML <textarea> through JavaScript, and want to keep the line breaks. Ex when I write:

Line a
Line b

It comes out as:

Line a Line b

My code:

function textwrite(){
  thetext = document.getElementById("text_change").value;    
  document.getElementById("demo").innerHTML = thetext;
}
<textarea id='text_change' oninput='textwrite()'></textarea>
    
<p id="demo"></p>

And I don't want to use <pre> tag.

Narial answered 25/10, 2018 at 14:0 Comment(2)
Possible duplicate of JavaScript: How to add line breaks to an HTML textarea?Car
Possible duplicate of Preserve line breaks in textareaDragoman
A
5

Replace \n,\r,\n\r with </br> in java script:

var myLineBreak = thetext.replace(/\r\n|\r|\n/g,"</br>");

function textwrite(){
    	thetext = document.getElementById("text_change").value;  
      var myLineBreak = thetext.replace(/\r\n|\r|\n/g,"</br>");

    	document.getElementById("demo").innerHTML = myLineBreak;
    }
<textarea id='text_change' oninput='textwrite()'></textarea>
    
    <p id="demo"></p>
Advancement answered 25/10, 2018 at 14:5 Comment(0)
C
7

Use white-space:

The white-space CSS property sets how white space inside an element is handled.

with value pre-wrap where

Sequences of white space are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

function textwrite(){
  thetext = document.getElementById("text_change").value;    
  document.getElementById("demo").innerHTML = thetext;
}
#demo { white-space: pre-wrap; }
<textarea id='text_change' oninput='textwrite()'></textarea>
    
<p id="demo"></p>
Cooperstein answered 25/10, 2018 at 14:3 Comment(4)
Want to add some comments that explain why this solves the problem?Exsanguine
@RyanWilson, updated the answer with some documentation....hope that makes more sense now......thanksCooperstein
Thank you, that is much better. +1 from me.Exsanguine
This is the correct answer, the string saves those line breaks itself, but you have to specify the CSS to show it, thx!Stupefy
A
5

Replace \n,\r,\n\r with </br> in java script:

var myLineBreak = thetext.replace(/\r\n|\r|\n/g,"</br>");

function textwrite(){
    	thetext = document.getElementById("text_change").value;  
      var myLineBreak = thetext.replace(/\r\n|\r|\n/g,"</br>");

    	document.getElementById("demo").innerHTML = myLineBreak;
    }
<textarea id='text_change' oninput='textwrite()'></textarea>
    
    <p id="demo"></p>
Advancement answered 25/10, 2018 at 14:5 Comment(0)
G
0

To do that, first set the multiline property of the textBox to true and then include at the end of each line this: "\r\n"

Gerrilee answered 25/10, 2018 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.