How do you populate a text box with jquery and linebreaks?

I know how to fill a text field, but how to fill it so that it supports line breaks?

eg

HTML

<div id="previous_purchases">blah blah blah<br />blah blah</div> 

JQuery

  $('#previous_purchases').click(function(){ var what = $(this).text(); $('#purchased').text(what); }); 

All blah just swing in the text box on the same line. Any ideas?

edit: I'm trying to use html () instead of text, but it gives the same result. I would suggest that using html () I would get a text box with "
"but that's not the case ... its just all on one line.

Even with this code:

  $('#previous_purchases').click(function(){ var what = $(this).html(); $('#purchased').html(what); }); 
+6
jquery
source share
3 answers

Try to do:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready( function() { $('#previous_purchases').click(function() { var what = $(this).html().replace(/<br>/, '\n'); $('#purchased').html(what); }); }); </script> </head> <body> <div id="previous_purchases">blah blah blah<br />blah blah</div> <textarea id="purchased" cols="25" rows="10"></textarea> </body> </html> 

See Attributes / html

+5
source share

Instead of calling the text () function, you can use html () and text with formatted text.

 $('#previous_purchases').click(function(){ var what = $(this).text(); $('#purchased').html(what); }); 
+2
source share

text () automatically removes html. So basically you want to use html () instead of text and replace
on \ n

+2
source share

All Articles