How to add line breaks to an HTML textarea?

djairo picture djairo · May 14, 2009 · Viewed 316.2k times · Source

I’m editing a <textarea> with JavaScript. The problem is that when I make line breaks in it, they won’t display. How can I do this?

I’m getting the value to write a function, but it won’t give line breaks.

Answer

TStamper picture TStamper · May 14, 2009

Problem comes from the fact that line breaks (\n\r?) are not the same as HTML <br/> tags

var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '<br />');

UPDATE

Since many of the comments and my own experience have show me that this <br> solution is not working as expected here is an example of how to append a new line to a textarea using '\r\n'

function log(text) {
    var txtArea ;

    txtArea = document.getElementById("txtDebug") ;
    txtArea.value +=  text + '\r\n';
}

I decided to do this an edit, and not as a new question because this a far too popular answer to be wrong or incomplete.