Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add line breaks to an HTML textarea?

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.

like image 907
djairo Avatar asked May 14 '09 14:05

djairo


People also ask

How do you show line breaks in HTML?

To add a line break to your HTML code, you use the <br> tag. The <br> tag does not have an end tag. You can also add additional lines between paragraphs by using the <br> tags.

Which character defines a new line in the textarea?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

How do I start a new line in HTML without br?

Use block-level elements to break the line without using <br> tag. There are many ways to break the line without using <br> tag. The used properties are listed below: white-space: pre; It is used to make elements acts like <pre> tag.

How do you insert a line break in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


2 Answers

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.

like image 115
TStamper Avatar answered Sep 21 '22 12:09

TStamper


if you use general java script and you need to assign string to text area value then

 document.getElementById("textareaid").value='texthere\\\ntexttext'. 

you need to replace \n or < br > to \\\n

otherwise it gives Uncaught SyntaxError: Unexpected token ILLEGAL on all browsers.

like image 33
jit Avatar answered Sep 23 '22 12:09

jit