I'm making a website using data from Pokemon and trying to execute a dialog box. I've tried using JS newline character in the text:
function alertBox(monster) {
$("#dialog").dialog();
$("#dialog").dialog("option", "title", monster);
$("#dialog").text("Height: " + pokemon.height[monster] + "\n" +
"Weight: " + pokemon.weight[monster]);
}
...And I've also tried using the html line break tag:
function alertBox(monster) {
$("#dialog").dialog();
$("#dialog").dialog("option", "title", monster);
$("#dialog").text("Height: " + pokemon.height[monster] + "<\br>" +
"Weight: " + pokemon.weight[monster]);
}
But neither seems to be returning the newline effect I'm looking for! The JS newline just acts as a space and the html line break tag just concatenates to the string. Is there a way to force a newline in the dialog text?
The jQuery UI dialog method is used to create a basic dialog window which is positioned into the viewport and protected from page content. It has a title bar and a content area, and can be moved, resized and closed with the 'x' icon by default.
A dialog is a type of modal window. Access to the rest of the UI is disabled until the modal is addressed. All modal surfaces are interruptive by design – their purpose is to have the user focus on content on a surface that appears in front of all other surfaces.
The jQuery .text()
function automatically escapes HTML entities, so your <br />
tag is no longer being interpreted as HTML, but instead gets converted to escaped text.
To prevent this HTML escaping, you need to use .html()
instead of .text()
to set the contents:
function alertBox(monster) {
$("#dialog").dialog();
$("#dialog").dialog("option", "title", monster);
$("#dialog").html("Height: " + pokemon.height[monster] + "<br />" +
"Weight: " + pokemon.weight[monster]);
}
Consider adding:
$("#dialog").css("white-space","pre-wrap");
This will make the \n
significant, and it will render as such.
Alternatively, consider using some actual HTML. For instance, your dialog could be:
$("#dialog").html("<ul>" +
"<li><b>Height:</b> "+pokemon.height[monster]+"</li>" +
"<li><b>Weight:</b> "+pokemon.weight[monster]+"</li>" +
"</ul>");
For more complex layouts, I'd suggest using a templating system instead of hardcoding HTML into your JavaScript.
Hope it will help to see how text() val() and html() works
$(document).ready(function () {
$("#dialog").html("Height: " + 11 + "<br>" +
"Weight: " + 22);
$("#dialog2").val("Height: " + 11 + "\n" +
"Weight: " + 22);
$("#dialog3").text("Height: " + 11 + "\n" +
"Weight: " + 22);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog"></div>
<textarea rows="5" cols="20" name="text" id="dialog2"></textarea>
<textarea rows="5" cols="20" name="text" id="dialog3"></textarea>
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