Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery/javascript maintain linebreak when copying text

Suppose I have

<input type="hidden" id="in1">

...

<p id="editable_p"></p>

<script> 
$('#some_button').click( function() {
  $('#in1').val($('#editable_p').text());
});
</script>

Clearly, my intention is to set the value of the hidden field to be the content of the <p> tag. This works, however it does not maintain line breaks, which is important for me. Is there a basic library function that will copy the value of the editable paragraph that maintains the linebreaks, or is there some kind of extended hack that must be performed to get this to work as I intend?

Thanks much in advance.

like image 787
Bill VB Avatar asked Nov 30 '25 17:11

Bill VB


1 Answers

You may find there are a number of text nodes in your #editable_p.p and calling text() as per a lot of XML type environments, will just concatenate the strings from the text nodes found in the descendant tree, potentially losing structure. This operation can do weird stuff to line breaks and other whitespace.

To avoid this, iterate over the actual text nodes, and concatenate the strings yourself, adding \n end of lines as necessary. Assuming you have succeeded in this and have the string with line breaks, I think talereader could be correct that a textarea or similar may be needed to represent the resulting string, and submit it faithfully to a server.

Selecting text nodes with JQuery is already outlined in How do I select text nodes with jQuery?

like image 84
Cefn Hoile Avatar answered Dec 03 '25 07:12

Cefn Hoile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!