How to display text with multiline from JavaScript to the HTML - javascript

I want to display multi line text, from JavaScript to the HTML using looping. The text position is after display the image. The text result should be like
Place ..... // newline price ....
<div id="display">
<script type="text/javascript" src="../controler/package.js"></script>
</div>
var display = document.getElementById('display');
function buildImages(images,place,k,price){
var last=document.createElement("IMG");
last.src=images;
last.width=800;
last.height=600;
last.style.marginTop=30;
display.appendChild(last);
var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place);
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(z);
display.insertBefore(x,display.childNodes[k]);

The cleanest way is probably to do the same thing you would do in HTML: wrap your text nodes in <p> elements.
Wrapping the text in an HTML element will always help you later to customize style or whatever!
Raw text nodes are not that convenient.

There are multiple ways to achieve this. One is using br tags
var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place);
var br = document.createElement("BR");
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(br);
x.appendChild(z);
Another could be using a pre tag
var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place + "\n price:" + price);
x.appendChild(t);
Or you could could use two spans that have display: block;
var x = document.createElement("H3");
var t = document.createElement("SPAN");
t.style.display = "block";
t.innerText = "Place:" +place;
var z = document.createElement("SPAN");
z.style.display = "block";
z.innerText = "Price:" +price;
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(z);

It can not work like this by design. if you do not use
<pre>
or
<code>
if you want to use line feeds or if you prefer other tags like
<p>
then you has to use at least
<br>
by this you can still format the text as you wish. Will look usually a bit messy. I would use a table.

Related

Losing CSS styling upon printing

I am using a style sheet to properly print out a webpage. The webpage has fields sat next to each other but upon printing these fields no longer sit next to each other but instead cascade down the sheet. I have created a style sheet but I'm not sure exactly how that is supposed to stop this from happening unless I hard code into the style sheet what I want to happen. Unfortunately I can't do that because I need to print out several different pages that have different layouts.
Is there any way to fix this?
function removeLinks(printDiv) {
var all_links = document.getElementById(printDiv).getElementsByTagName("a");
for (var i = 0; i < all_links.length; i++) {
all_links[i].removeAttribute("href");
}
}
function printdiv(printDiv) {
var divCaseNote = document.getElementById(printDiv);
var oldstr = document.body.innerHTML;
var oldTitle = document.title;
if (divCaseNote != null) {
divCaseNote.style = "padding: 20px;";
innerHTML = divCaseNote.innerHTML;
}
removeLinks(printDiv);
var headstr = "<html><head rel=\"stylesheet\" media=\"all\" link href=\"/CSS/style.css\"/><title> </title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printDiv).innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
document.title = oldTitle.replace(" - View Case Note", "");
window.print()
document.body.innerHTML = oldstr;
document.title = oldTitle;
EDIT: A snippet of the html output of this function. It holds all the correct divs for the columns but instead of printing the columns side by side they print cascading down the page.
<div class=\"view-value\" style=\"border-left: none;\">
Jerry</div></div></div>
<div class=\"col-md-3\"><div class=\"media-body\">
<div class=\"view-label\">Participant's Last Name</div>
<div class=\"view-value\" style=\"border-left: none;\">Field</div>
What it should look like
[
What it actually looks like after printing
The problem is that the inline styles are getting obliterated by this statement:
divCaseNote.style = "padding: 20px;";
which removes all the style attribute and replaces it with just the padding.
To add/alter the padding but nothing else you want to change just that property so try:
divCaseNote.style.padding = "20px";

Textarea to variable: Spacing

I'm taking the content of a textarea and saving it in a variable. But I notice that when I save the content, the variable ignores the spacing (new lines). How do I fix this. I want the variable to store the structure of the text, with all the new lines and tabs. My code in which I save the content from the textarea is below:
let content = document.getElementById('content').value
The whole function is below:
function mail(){
var options = document.getElementById('users').options
let content = document.getElementById('content').value
var emails = []
var regex = /\*user\*/gi
for(var i = 2; i < options.length; i++){
emails.push(options[i].innerHTML)
content = content.replace(regex, emails[i-2])
window.open(`mailto:${emails[i-2]}?subject=To ${emails[i-2]}&body=${content}`)
}
}
Thanks!!! Any help is appreciated!
Actually, spaces and new lines are exists but because you put your content in html (body{}), they are invisible.
some solutions:
let content = document.getElementById('content').value.replace(/\n/g,"<br/>").replace(/ ( +)/g,function(a,b){var s="", i=0; for(;i<b.length;i++)s+=" "; return " "+s;});
or this:
let content = "<pre>"+document.getElementById('content').value+"</pre>"
or this:
let content = "<div style='white-space: pre'>"+document.getElementById('content').value+"</div>"
The above solutions were for when the body is html.
Edit:
I guess this will solve your problem:
let content = escape(document.getElementById('content').value);
The variable does contain new lines if new lines are entered in the textarea. Keep in mind that textarea will wrap the text to fit it so if you see wrapped text, that doesn't mean there is a new line character in the text.
<textarea id="content"></textarea>
<input type="button" value="submit" onclick="msg()">
<script>
function msg() {
let message = document.getElementById('content').value;
alert(message);
}
</script>

Adding br tag in innerHTML between text and image

In my javascript program I have created div and added image and some hardcoded text in div by using innerHTML. But I am trying to add dynamic br tag between text and image. First text should be displayed then want to line break and then image should be displayed. So created br and added but somehow it doesn't work. Can anyone correct me ?
code:
function useInnerHTML() {
var movieText2 = prompt("One of my favourite movies");
var textNode = document.createTextNode(movieText2);
ele.appendChild(textNode);
document.body.appendChild(ele);
var newDiv2 = document.createElement("div");
var br = document.createElement("br");
newDiv2.className = "green";
var pic = "A picture is worth a thousand words";
var text2 = '<img src=\'https://i.stack.imgur.com/meXYL.png\'>';
newDiv2.innerHTML = pic + text2;
document.body.appendChild(newDiv2);
document.body.appendChild(br);
}
useInnerHTML();
.pink {
background-color: pink;
}
.green {
background-color: #71e887;
}
my output:
![output][1]
Simply use
pic = "A picture is worth a thousand words <br>";
since by using .innerHTML the <br> tag will not be escaped and actually embedded into the HTML as a breakline Element.
Or
Use Template strings and insertAdjacentHTML
function addNewMovie() {
var movieName = prompt("One of my favourite movies").trim(); // Trim it!
if(!movieName) return; // do nothing if empty!
var movieTemplate = `
<div class="movie">
<h1>${movieName}</h1>
<div class="green">
A picture is worth a thousand words<br>
<img src='//placehold.it/100x100/0bf'>
</div>
</div>
`;
document.body.insertAdjacentHTML("beforeend", movieTemplate);
}
<button onclick="addNewMovie()">ADD NEW MOVIE</button>
...cleaner, nicer.
You are adding the <br> after the picture, try doing it like this:
newDiv2.innerHTML = pic + br + text2;
document.body.appendChild(newDiv2);

Taking tab example from fiddle ans use in my project

http://jsfiddle.net/738wtmhs/1/
using above example in fiddle in my own project: for the purpose of this exercise I am using DOM methods to create and append the elements.
function GetFeatureProperties(feature) {
//add header to 1st FirstTabContent
var featureHeader = "<center><b> <FONT COLOR='FF6600'> Feature Properties </FONT> </b> </center> </br>";
var FirstTabContent = document.createElement('div');
FirstTabContent.id = "tabs-1";
FirstTabContent.innerHTML = featureHeader;
//Second Tab
var SecondTabContent = document.createElement('div');
SecondTabContent.id = "tabs-2";
var newImage = document.createElement("img");
newImage.src = "http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg";
newImage.width = "100";
newImage.height = "100";
SecondTabContent.appendChild(newImage);
//add li and ul
var DivHolding2Tabs = document.createElement('div');
DivHolding2Tabs.class = "shoptab";
var header2 = document.createElement('h2');
header2.innerHTML = "Feature";
DivHolding2Tabs.appendChild(header2);
var _ul = document.createElement('ul');
var _anchor1 = document.createElement("a");
_anchor1.href = "#tabs-1";
_anchor1.innerHTML = "Info";
var _li1 = document.createElement('li');
_li1.appendChild(_anchor1);
var _anchor2 = document.createElement("a");
_anchor2.href = "#tabs-2";
_anchor2.innerHTML = "Images";
var _li2 = document.createElement('li');
_li2.appendChild(_anchor2);
_ul.appendChild(_li1);
_ul.appendChild(_li2);
DivHolding2Tabs.appendChild(_ul);
DivHolding2Tabs.appendChild(FirstTabContent);
DivHolding2Tabs.appendChild(SecondTabContent);
var jelm = $(DivHolding2Tabs); //convert to jQuery Element
var htmlElm = jelm[0]; //convert to HTML Element
var OuterDiv = document.createElement('div');
OuterDiv.id = "loc-list";
OuterDiv.appendChild(htmlElm);
return OuterDiv.innerHTML;
}
and this looks like the image seen below....if I click on the link 'image' the page jumps a bit but nothing happens and nothing happens when I press 'info' also I have included the CSS in my project so why arnt the tabs showing and yes I am using jquery ui 1.10.3.custom.js
---------------------------------------------------------------------------------------------
UPDATE
<ul id="list"><li><div><h2>Feature</h2><ul><li>Info</li><li>Images</li></ul><div id="tabs-1"><center><b> <font color="FF6600"> Feature Properties </font> </b> </center> <br></div><div id="tabs-2"><img src="http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg" width="100" height="100"></div></div></li></ul>
Also changed from jquery 1.10.3 custom to jquery 1.11.2.custom with all the downloaded tabs selected
If you look at this fiddle, I managed to make it work.
Here's the possible problems
1) I changed return OuterDiv.innerHTML because I needed the <div id="loc-list"> to be part of the code to initialize it. You gave it an id so my guess is you wanted it to be included but by doing innerHTML, you didn't get it.
2) Once your function returns, you need to initialize the tabs with $('#loc-list').tabs();

Regular expression in javascript to get contents of <span> tags

I have a string with this form
<p>Central: <span class="fieldText">Central_Local</span>
<br>Area Resolutoria: <span class="fieldText">Area_Resolutoria</span>
<br>VPI: <span class="fieldText">VIP</span>
I'm trying to get the span elements, and find the values within
var message = currentMarker.get("mensaje");
var pat = new RegExp("^(.*?<span .*?>(.*?)</span>.*?)+$");
message.match(pat);
I need to get these values:
Central_Local
Area_Resolutoria
VIP
IP_ERX
How can this be done, or how can my regex be improved?
jQuery
var message = currentMarker.get("mensaje");
var contents = [];
$('<div>', {html: message }).find('span.fieldText').each(function(){
contents.push( $(this).text() );
});
demo at http://jsfiddle.net/DfDPR/2/
Pure javascript
var message = currentMarker.get("mensaje");
var contents = [];
var div = document.createElement('div');
div.innerHTML = message;
var spans = div.getElementsByTagName('span');
for (var span = 0; span < spans.length; span++)
{
contents.push(spans[span].innerHTML);
}
demo at http://jsfiddle.net/DfDPR/3/
As mentioned in the comments, regex is not a good candidate for parsing HTML...
Trivial task in jQuery:
var values = $('span.fieldText', message).map(function(){
return $(this).text();
}).get();
values will be an array with all the values you need. You can iterate over it or do anything you like.

Categories

Resources