user2868139
user2868139

Reputation: 97

HTML textarea to javascript and keep line break

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.

Upvotes: 5

Views: 6961

Answers (3)

NullPointer
NullPointer

Reputation: 7368

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>

Upvotes: 5

Mamun
Mamun

Reputation: 68933

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>

Upvotes: 7

Paplusc
Paplusc

Reputation: 1130

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"

Upvotes: 0

Related Questions