3

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.

Bill
  • 2,319
  • 9
  • 29
  • 36
  • 2
    is the editable text stored as HTML ? ie what makes the line break ?
    ? if so try using `.html()` instead of `text()`
    – Manse Dec 20 '11 at 19:35
  • 1
    I think the itself removes the line breaks, not JavaScript. Did you try to replace the input with a – binar Dec 20 '11 at 19:36
  • I've tried that, but it still doesn't maintain linebreaks copying into the textarea. – Bill Dec 20 '11 at 19:49
  • @ManseUK - This does appear to work, however I was a bit suprised to find that it would wrap the newline in a '

    new-line-of-text..
    '
    – Bill Dec 20 '11 at 19:51

1 Answers1

3

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?

Community
  • 1
  • 1
Cefn Hoile
  • 431
  • 2
  • 9