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

Go To StackoverFlow.com

1

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

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

 $('.jqueryFindBody').text($('.jqueryFindBody').text());

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


1

How about using .val()? http://api.jquery.com/val

$('.jqueryFindBody').val($('.jqueryFindBody').val());

Here is a demo: http://jsfiddle.net/tXnaj/

Update

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: http://jsfiddle.net/tXnaj/2/

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


0

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
Ads