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?
The <br> tag inserts a single line break. The <br> tag is useful for writing addresses or poems.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!
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>
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>
$("#element").html(data.replace(/(\n)/g, '<br>'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With