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.
Related
I have a loop that creates links with a javascript function call in the onClick events and uses the text returned from a database as one of the parameters. My issues I am having is that sometimes this text being returned has parenthesis in them which is causing a syntax error in my code.
Example:
code:
formResults += "<a onclick='openForm(" + this.displayText + "," + this.ID + ");'>" + this.displayText + "</a>";
HTMLDisplay:
<a onclick="openForm(Example Form (Example Form 1) Application Instructions ,1108);">Example Form (Example Form 1) Application Instructions </a>
as you can see the name of the form contains a set of parenthesis. Is there anyway I can include these? The reason I need to is because the function points to another system that uses the ID and displayText in order to render the proper form.
thank you
The parenthesis aren't the problem, it's the lack of quotes inside the function.
formResults += "<a onclick='openForm(\'" + this.displayText + "," + this.ID + "\');'>" + this.displayText + "</a>";
This below snippet (from yours)
`openForm(Example Form...`)
Will throw an error because it's looking for variables Example and so on, quote that string!
I strongly suggest
code:
formResults += '<a class="openForm" data-text="'+this.displayText + '" id="'+this.ID + '">' + this.displayText + '</a>';
HTMLDisplay:
<a class="openForm" data-text="Example Form (Example Form 1) Application Instructions" id="1108">Example Form (Example Form 1) Application Instructions </a>
jQuery:
$(function() {
$(".openForm").on("click",function(e) {
e.preventDefault();
openForm($(this).data("text"),this.id);
});
});
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>
Here is my test javascript function
<script type="text/javascript">
function test() {
var sHTML = "<script type='text/javascript'> " +
"function showmsg() { " +
"alert('message'); " +
"} " +
"<\/script>" +
"<div>" +
"<a href='#' onclick='javascript:showmsg(); return false;'>click</a>" +
"</div>";
var divTemp = document.createElement("div");
divTemp.innerHTML = sHTML;
var d = document.getElementById("div1");
d.appendChild(divTemp);
}
</script>
When I run this function, the div along with a tag is added in the div1, but when I click on anchor tag, it says showmsg is not defined, which is indicating that browser is NOT parsing the script tag.
How to achieve this without any 3rd party library?
Update:
The possible usage is, I want to allow user to create HTML templates along with JavaScript code, then my JS library will use those HTML templates to render user defined markup, plus allowing user to implement his/her custom logics through JS.
You need to run eval on the script contents when using innerHTML. Try something like:
var scripts = divTemp.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++) {
eval(scripts[i].textContent);
}
Obviously, you need to do this in end, after injecting the innerHTML into the DOM.
Browsers do not run JavaScript code when a <script> tag is dynamically inserted like that.
Instead of that, you can just define the function directly!
function test() {
window.showmsg = function() {
alert("message");
};
var sHTML = "<div>" +
"<a href='#' onclick='javascript:showmsg(); return false;'>click</a>" +
"</div>";
var divTemp = document.createElement("div");
divTemp.innerHTML = sHTML;
var d = document.getElementById("div1");
d.appendChild(divTemp);
}
Libraries like jQuery have code to strip <script> blocks out of text that's being stuffed into some element's innerHTML, and then evaluate it with eval(), so that's one thing to do if the code is somehow "stuck" in a block of content.
Using jquery, is this can help you :
$('<script>function test(){alert("message");};</' + 'script><div>click</div>').appendTo(document.body)
http://jsfiddle.net/TSWsF/
I have a function that uses:
name = "textBox" + (h) + (j);
id = "textBox" + (h) + (j);
value = hoursEachDay[j-1];
textBox = "<input type='text' maxlength='6' size='6' name='" + name + "'id='"+ id +"' value='" + value + "' onchange='updateHrs()'>";//or parent.updateHrs(j)
(h, i,and j being integers) to call another function that follows directly after the first function. That function is :
function updateHrs()// or updateHrs(dayOfMonth)
{
alert("This is the day changed ");
//or alert("This is the day changed " + dayOfMonth);
return;
}
I get a 'function not defined' error from firebug when I run this and trigger the onchange event handler. I have, on the suggestion of a coworker, changed updateHrs() to parent.updateHrs(), which actually works for some reason, until I try to pass a variable into the updateHrs() function (ass seen commented out above), at which point it declares that updateHrs(j) is not defined.
I am guessing that somehow the updateHrs function is being read as out of scope, although I'm not really sure how. Both of these functions are right after one another and both are right before the tag (yes there is a tag well above them as well), so they should not have a scope issue, not that I'm aware of anyway.
Thanks for any help that you can provide.
I have an event which parses a certain string which contains button name and url.
than I assign the data to a button. and add on click event which suppose to open url in a new window. But this on click event doe not work. The window does not show up. If url was wrong it would open a window and prompt a mistake.
But in my case when I click the botton it does not react. Probably something is wrong with on click event here: onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\". But I can't understand what.
here is the code
<script>
...
var checkType = partArray[0].split("+");
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\" /> "
document.getElementById("demo").innerHTML=outPuts;
</script>
<body>
...
<div id="demo"></div>
...
</body>
partArray[1] is not evaluated; the browser should still open window with the URL specified as "partArray[1]" but I doubt that is what you want. Try adding double quotes and concatenating it when you build your HTML.
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('" + partArray[1] + "', '', 'width=300,height=300');\" /> "
If you provide some more context or code it'd be easier to see what might be going on. Are you sure there is not a popup-blocker getting in the way?