How to select text from a multiline textbox with the line breaks in Jquery?

Go To


<textarea style="height: 300px;"  class="jqueryFindBody" cols="20" rows="2">

In the textbox above, if I replace its text with its own text, the line breaks get lost


I tried using html instead of text, but the line breaks are always lost. How do I preserve the line breaks?

2012-04-03 19:44
by developer747


How about using .val()?


Here is a demo:


If you want to display the value of the textarea element in HTML then you'll need to parse the endline characters into <br /> tags. You can do this with a simple RegExp:

$('.jqueryFindBody').val().replace(/\r|\n/g, '<br />');

This finds all the \n and \r characters and replaces then with <br /> tags.

Here is a demo:

2012-04-03 19:47
by Jasper
Thank you you Jasper it worked : - developer747 2012-04-03 19:54


Newlines in text boxes are represented as \n and \r (newline and carriage return) The topic is also discussed here: jQuery convert line breaks to br (nl2br equivalent)

2012-04-03 19:53
by jornare