Ok, I'm having a huge problem, and I've been looking for days about how to do this. Either I can't read well enough to understand it, or I'm stupid. I'm not sure what it is yet. I'll be honest and say that this is homework, but I've been struggling with this for 3 days now, and as its an online class, I can't go see my instructor and ask him what I'm doing wrong. I have emailed him, but his help is limited and vague, and I cannot figure this out. Anyway, to the point. I want to add HTML to the text that's going to be displayed in a new window using a JavaScript function. Here's the basics of what I have.
function myWindow(){
var pageContent, pageTitle;
pageTitle = document.write("Selected Image Preview");
document.write.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>"Name of Image"</h3>";
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
pageContent += "</strong></body></html>";
}
Now, I have no idea what I'm doing wrong, considering I've read almost everything that I could find, searched all over this site, as well as dozens of others. I've tried the W3 schools, and some site that looked like it was last updated in 2001, and my book has absolutely NO examples of HTML being used inside the function (it's a javascript book, so the HTML help is very limited). Starting at the top, it tells me that "Uncaught SyntaxError: Unexpected token ILLEGAL junk.html:16" on the script line. Then it won't load the rest of the page. If I comment that out, it tells me that '<h3>' is an unexpected identifier, and it just keeps going. There's always something wrong and if I comment out the lines that give errors, then there's nothing left. Please help me figure out what I'm doing wrong. And if it's necessary, I am calling the function onload with the <body onload="myWindow();"> tag.
P.S. Please don't kill me if I've formatted this incorrectly. I did read the directions, and tried to format this as neatly as possible.
The biggest problem was that the closing </script> tag in the line with the call to alert() terminated the script, even though it was within a string literal. See the link in my comment to your original post. There were some other problems with quotes, and if a teacher is really teaching the <font> tag in 2014, I think I should track him down and throw up in his lap.
Note that the slash in </script> and the embedded double-quotes are now escaped with backslashes. That's the biggest change. Also, the function now returns the computed value so it can be used.
This code goes through a JavaScript console clean. It doesn't open any new windows, and it doesn't deal with the "style" line, which I couldn't figure out.
function myWindow(){
var pageContent, pageTitle;
pageTitle = "Selected Image Preview";
// document.write.style.textAlign="center"; // WTF?
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)<\/script>";
pageContent += "</head>";
pageContent += "<body style=\"text-align: center;\">";
pageContent += "<h3>Name of Image</h3>";
pageContent += "<strong>" + "<font color= \" violet \">\"Here is the image you selected. \"</font>";
pageContent += "</strong></body></html>";
return(pageContent);
}
I've edited the code. The <h3> line was within the head of the document, now fixed, and I added a style attribute to <body> based on your remark about wanting text centered.
Ok, your code contains errors, because you need to learn how to work with strings and quotes and how to escape quotes.
var str1 = "qwe";
var str2 = "asd";
var str3 = str1 + str2; // will be qweasd
var str3 = str1 + '1111' + str2; // will be qwe1111asd
var str3 = str1 + 'z"1"' + str2; // will be qwez"1"asd
var str3 = str1 + "z\"1\"" + str2; // will be qwez"1"asd. There is no difference if you use double quotes or single. If you use single quotes, all single quotes in the string must be escaped with backslash and opposite with double quotes
// and the same with single quotes:
var str3 = str1 + 'z\'1\'' + str2; // will be qwez'1'asd
also, you are using document.write function, which overrides the content of current page, but you need a new window, which is why we should use function window.open which returns a new window handler. We save it into OpenWindow variable and then we apply our content using OpenWindow.document.write passing our string pageContent as a first parameter
and the correct code:
function myWindow(){
var pageContent, pageTitle;
document.title = "Selected Image Preview";
document.body.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>Name of Image</h3>";
pageContent += '</head><body align="center"><strong><font color="violet">Here is the image you selected.</font>';
pageContent += "</strong></body></html>";
var OpenWindow = window.open('#','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(pageContent);
}
pageContent += "<h3>"Name of Image"</h3>";
You don't need quotes around name of image. The entire line should be treated as a String.
pageContent += "<h3>Name of Image</h3>";
Basically, anything in HTML tags doesn't need quotes unless you intend for quotes to appear.
For this line:
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
You should use single quotes.
pageContent += "</head><body align='center'><strong>" + "<font color='violet'>Here is the image you selected. </font>";
You should be able to fix the rest of your HTML, keeping in mind single quotes for attributer, no quotes for content.
As to the HTML itself, it should look like this to follow at least intended standards. You should move most of the styles eventually to CSS.
<html>
<head>
<title>Selected Image Preview</title>
<script>// your script here </script>
</head>
<body>
<div align='center'>
<!-- your content here -->
</div>
</body>
Related
Im trying to save some HTML in a JS variable by using the backtick formatting however is it possible to preserve the HTML variable according to the following example
var msg = "This is a test" + "\n" + "Test"
Im attempting to store this variable as a HTML paragraph while keeping the linebreaks
var emsg = '<p style="white-space: pre-wrap;"><\"{msg}"\</p>'
But when sending that content in an email to myself (Using Emailjs) I get the following
<"{msg}"
Any clue what I'm doing wrong? Thanks!
You are using single quotes ('), not backticks (`)
Placeholders in template literals are indicated by a dollar sign ($), which you are missing.
var msg = "This is a test" + "\n" + "Test"
var emsg = `<p style="white-space: pre-wrap;"><\"${msg}"\</p>`
console.log(emsg)
You could go with template literals like #spectric showed.
or you can go with simple quote using + to seperate it with msg variable
var msg = "This is a test" + "\n" + "Test";// V V
var emsg = '<p style="white-space: pre-wrap;"><\"'+msg+'"\</p>';
console.log(emsg);
as described + removing the extra <\" and "\ probably
var emsg = <p style="white-space: pre-wrap;">${msg}</p>
edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not "e;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}
Inside my content.js I am writting a new HTML page with a pre polulated form, which contains var a and var b. Those 2 variables are created before, inside content.js, so I can easily use them inside my HTML page. Now I want to override those variables a and b as the user finishes editing the form and presses the button Accept. Is there anyway I can achieve this?
This is a part of the code
var a="FName";
var b="LName";
var myWindow = window.open("Accept", "myWindow", "width=450, height=300");
myWindow.document.write(
"<html>"+
"<head>"+
'<script> function closeWindow(){ var x = document.getElementById("firstname").value alert(x); window.close();}'+
"</script>"+
"</head>"+
"<body>"+
"<form>"+
"<div id=leadinformation>"+
"<p id=titleParagraph>You are about to create a new Lead:</p>"+
"First Name....."+ "<input type=text id=firstname value="+a+">" +"<br>"+
"Last Name....."+ "<input type=text id=lastname value="+b+">" +
"</div>"+
"<div>"+
"<button id=Accept onClick=closeWindow() >Accept</button>"+
"<button id=Close onClick=closeWindow() >Close</button>"+
"</div>"+
"</form>"+
"</body>"+
"<html>"
);
myWindow.document.getElementById('Accept').onclick=Accept;
myWindow.document.getElementById('Close').onclick=Close;
function Accept(){
alert(myWindow.document.getElementById('firstname').innerText);
}
function Close() {//do smthing
}
Sorry for bad formating.
Currently the output of the Accept(); is empty at the moment. How can I get first name input result?
What I want to achieve:
1) I am creating a button on a page
2) When I click on the button a new html page pops out (the one that I am hardcode writing it)
3) I pre populate the form with some variables that I created before
4) When Clicking The Accept button on the form the Accept() function is triggered where I would want to use those input values the user has written.
This should help you: Sharing global javascript variable of a page (...).
The question is about "How to share a variable to another page in an iframe", but this works for a new windows as well.
i.e.:
myWindow.document.write(
"<html>" +
"<head>" +
'<script>' +
'function closeWindow(){' +
'var x = document.getElementById("firstname").value;' +
'alert(x);' +
'// do something to parent.a and parent.b here, just because you can:' +
'parent.a = "Oh, would you look at it, it works!";' +
'parent.b = "And it is so pretty too!";' +
'window.close();' +
'}' +
"</script>" +
"</head>" +
" Your body code here, etc " +
"</html>"
);
Also, please note that your code lacks a semicolon (;) after inserting value to var x in your new window's JavaScript code. That will most probably make your code malfunction. The closing </html> tag lacks the slash, but I don't know if that's gonna break anything; you'd better fix that as well, just in case.
Noob question alert! So, I've got this script, which loops through an array and adds a <br> tag to the end of each array item. But i dont know the proper way of displaying this output on my page. Currently, when it loads the <br> tags show up on screen, whereas I want them to render as line-breaks. It is outputting into a <textarea> if that makes a difference. Thanks a bunch.
var outputLinkText = document.getElementById('outputLinkText');
var outputStageOne = "";
for (var i = 0; i < arrayOne.length; i++) {
outputStageOne += (arrayOne[i] + "<br>");
}
if ( 'textContent' in timePlace ) {
outputLinkText.textContent = outputStageOne;
}
else {
outputLinkText.innerText = outputStageOne;
}
<textarea> tags don't support <br> tags (or any other HTML tags) within their contents. They only hold plain text.
You need to add "\n" as the separator instead.
(Strictly, it should be "\r\n" but a "\n" on its own is usually sufficient)
Yes the textarea is a difference, try this :
"\r\n" instead of "<br>"
I keep getting this error in the $('#savetickets-list') line. I want to dynamically add fields to a table, the table has the id in HTML.
<div class="savetickets-list">
</div>
In javascript I fill the table in a for loop
for (var i = 0; i < len; i++) {
// the data comes from a web database
var ticketname = results.rows.item(i).iTicketName;
$('#savetickets-list').append('
<div class="saveticket gradient-top">
<h3>' + ticketname + '</h3>
</div>
');
}
I dont know how to solve this. jQuery is loaded, I also checked the name of the selector.
Please help.
$('#savetickets-list').append('\
<div class="saveticket gradient-top">\
<h3>' + ticketname + '</h3>\
</div>\
');
when you want to write multiline strings in JS, you must escape new lines.
It is because you are using new lines.
JS does not automatically read new lines for you. It treats them as new statements.
The way I prefer to do this is like:
$('#savetickets-list').append('<div class="saveticket gradient-top">'+
'<h3>' + ticketname + '</h3>'+
'</div>');
Just checked.
The problem is in the newlines, you have to concatenate strings or put all the statement in a single line.