Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 316
user2868139 Avatar asked Mar 05 '23 04:03

user2868139


2 Answers

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>
like image 160
Mamun Avatar answered Mar 11 '23 21:03

Mamun


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>
like image 33
NullPointer Avatar answered Mar 11 '23 22:03

NullPointer