lion_bash
lion_bash

Reputation: 1409

jQuery data received from server does not keep original format using append()

I am receiving data from the server and displaying it to the user. I originally was displaying the data using a textarea and all the formatting is correct (line breaks, tabs...etc).

html:

<textarea id="textArea" class="textArea" readonly></textarea>

js:

//data stream received from server
...
data = xhr.responseText;
$( ".textArea" ).val( data );

The above works fine, however, now I want to switch my textarea to a div instead (to add styles and be able to print the div later...), but after I switched all my formatting received from the server are gone and all the data is displayed in a whole blob when I use append:

html:

<div id="textArea" class="textArea"></div>

js:

//data stream received from server
...
data = xhr.responseText;
$(".textArea").append(data);

How can I keep the source formatting when appending data to div?

Upvotes: 0

Views: 33

Answers (1)

AnonymousSB
AnonymousSB

Reputation: 3594

What you're really looking for is a way to make a div behave like a textarea, because a textarea renders text in a fixed-width font and remembers whitespace.

.textarea {
    border: 1px solid gray;
    font-family: monospace;
    height: 200px;
    overflow: auto;
    padding: 2px;
    resize: both;
    width: 400px;
    white-space: pre;
}

https://jsfiddle.net/AnonymousSB/hkfy14es/

Note: Unlike a textarea, you have to keep the first line of text on the same line as your opening div element to prevent a gap at the top, because white-space: pre; makes it render ALL white space.

Upvotes: 2

Related Questions