IskandarG
IskandarG

Reputation: 333

Add JavaScript String with line breaks and tabs to HTML element

I have this HTML:

<p id="element">Waiting for Message</p>

And this string from the server using JSON.stringify() with breaks and tabs in it i.e

var = "Heading (info:info) \n info: \n \t and so on "; // The actual string is more complex though, just an example

And this Jquery to post the string to the paragraph tag:

$("#element").text(data); // data is the string from the server(not in JSON!)

The problem is the HTML ignores the formatting but when I use an alert box it displays with the proper formatting. I am dynamically updating the element as data comes from the server. Any pointers?

Upvotes: 10

Views: 38848

Answers (3)

Diptox
Diptox

Reputation: 1809

$("#element").html(data.replace(/(\n)/g, '<br>'));

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281892

Make use of the pre tag in HTML and update your text there

$(document).ready(function(){

var data = {
    "id": "1",
    "nome": "erwrw",
    "cognome": "sdsfdfs",
    "CF": "qwert",
    "eta": "27",
    "sesso": "uomo",
    "indirizzo": "qwerrt",
    "luogo": "wewrw",
    "provincia": "ewrewrw",
    "citta": "erwrwr",
    "comune": "ewrewrw"
  }

var obj = JSON.stringify(data, null, 4);
$('#element').text(obj);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="element">Waiting for Message</pre>
<button id="btn">send</button>

Upvotes: 4

dfsq
dfsq

Reputation: 193311

You should tell browser to respect those whitepaces. Easy way to do it is using white-space: pre rule:

var data = "Heading (info:info) \n info: \n \t and so on "; 

$("#element").html(data);
#element {
  white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="element">Waiting for Message</p>

Upvotes: 9

Related Questions