I've searched everywhere for many different ways of inserting text into a newly opened window with javascript within a function, yet none have seemed to work which leads me to believe I'm missing a key fundamental ingredient here.
function validate2() {
var valTxt = document.webPage.txt2.value;
if (valTxt == null || valTxt == "") {
alert("Field cannot be empty!");
return false;
}
if (valTxt.length < 5) {
alert("You must enter at least 5 characters!")
return false;
}
myWin = window.open('mypopup.html', "mywin", '');
myWin.getElementById('userText').innerHTML = valTxt;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Exercise 3</title>
<script type="text/javascript" src="functions.js"></script>
</head>
<body>
<form name="webPage" action="http://thebest404pageever.com/">
Please type anything over 5 characters: <input type="text" name="txt2"><br/>
<input type="submit" name="b2" value="Confirm" onClick="return validate2()">
</form>
</body>
</html>
I have an empty HTML file for mypopup with just a h1 element with the id userText. The popup certainly shows up, but continuously shows blank. Is there anything I'm missing here? Thanks a lot.
myWin = window.open('mypopup.html', "mywin", '');
window.onload=function placeText(){
myWin.getElementById('userText').innerHTML = valTxt;
I appended it with this, and it doesn't look right and sure enough, doesnt work right either.
The loading of the new window is done asynchronously. As indicated in the MDN documentation:
Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.
You will need to defer your changes to the DOM until after they are loaded.
I would use a window.onload handler for this:
window.onload=function() {
myWin.getElementById('userText').innerHTML = valTxt;
};
Related
javascript newbie here, but I was wondering if it is possible to set a timeout after a user clicks a HTML Link, now I was wondering this because I am making a simple maths game, and it uses the alert method, which means that once a user clicks the link, the page in which the link is placed, is still visible in the background, which doesn't look very good. I was looking around and found a method called "window.setTimeout" and I was wondering if I could tie that method to the anchor tag in the HTML Code. Thanks :)
My Code: (Note the game isn't finished yet :) )
<html>
<head>
<title>Maths Game 0.1 Beta</title>
<link rel="stylesheet" type="text/css" href="styling.css">
<script type="text/javascript">
var num1 = prompt("What is 2x10?");
if (num1 == '20') {
alert("Nice Job!");
} else {
alert("Oh well, try again.");
}
</script>
</head>
<body>
</body>
</html>
For example, if you have a <a id="foo" href="#"> </a> in your HTML, once could do
document.getElementById("foo").onclick = function() {
setTimeout(function() {
// do stuff
}, 5000); // triggers the callback after 5s
};
Try this:
<html>
<head>
<title> Maths Game 0.1 Beta</title>
</head>
<body>
First Question
<script type="text/javascript">
function question(){
var num1 = prompt("What is 2x10?");
if (num1=='20'){
alert ("Nice Job!");
}
else {alert ("Oh well, try again.");}
}
</script>
</body>
</html>
Fiddle:
http://jsfiddle.net/h7xpxzgg/
If I understand you correctly, you want to actually load a new page and then have the alert pop up, right?
Well, timeouts won't run once the user has left your page.
But there are at least two ways to do what you're asking:
Fake the page.
You can include everything that would be on the "next page" on the current page, but hide it with display:none, and once the user clicks your link, you first make the content of the original page invisible, then make the content of the "next" page visible, and then show the alert.
Pass a value to the next page, and do the alert there.
Since this is all client-side, I suggest using window.location.hash, like
On the current page:
<script>
document.write('Next page');
</script>
On the next page:
<script>
var num1 = window.location.hash.substr(1); // To get rid of the #
if(num1 == '20')
{
alert("Nice Job!");
}
else
{
alert("Oh well, try again.");
}
</script>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
Rookie alert!
Would you tell me why my Javascript code doesn't update the message. The browser runs HTML but ignores the Javascript code. What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
</html>
You're running the Javascript before you've loaded the body, the message element doesn't exist yet. Either move the script to the end of the <body>, or change the last line to:
window.onload = updateMessage;
so that the function will be loaded after the HTML is loaded.
If the <script> tag is in the <head> element, it gets executed before the HTML elements in the <body> are created. You can put your script tag inside the <body> element, at the end of it, to solve the issue.
Assuming you don't simply have javascript disabled, you could add a window.onload=function(){ surrounding your code.
window.onload=function(){
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
}
The reason for doing this is because your javascript code is inside your <head>. Thus, the javascript is loaded before the body. When the browser attempts to execute the javascript code, the message element isn't loaded yet and doesn't exist. By adding window.onload=function(){ to surround your code, your entire code will wait until the body is loaded before executing.
When you call your javascript code, the 'message' element isn't already there. I would suggest one of the following two things:
+Put your javascript code at the end of the body ( note that it only need to be after 'message', but putting it at the end is generally the best option )
+Replace your call with window.onload = updateMessage, which will wait until all the page is loaded to execute your javascript
There are already lots of duplicate answers here but there is another way, especially if you want to keep your Javascript code in a script tag in the head. And that is, wrap your Javascript function call in setTimeout -- this causes the function to be executed after the DOM has been parsed, but before the entire window has been loaded.
It's a neat little trick that can be used when you don't have a framework's (such as jQuery) document/ready functionality. window.onload or putting the script at the bottom might cause significant delays if there is lots of heavyweight content (large images?) in the page.
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
setTimeout(updateMessage);
</script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
</html>
Notice I have added a very large image to the page, but the updated message displays before the image fully loads.
If however instead of setTimeout(updateMessage); you use window.onload = updateMessage; as suggested in the currently accepted answer, your message will not get updated until the entire image loads (if you try this out, make sure you do a hard refresh after the first time so you are not getting it from your cache). Same goes for moving the script too far down the page (below the very large image for instance) as below. I honestly think, if you don't have a framework's document/ready functionality, using setTimeout in a script block in the head is the best solution.
MESSAGE NOT UPDATED UNTIL AFTER IMAGE LOADS:
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site!</div>
<img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>
You are trying to make the changes before the DOM is loaded. See the code below,
<!DOCTYPE html>
<html>
<head>
<title>Basic Function </title>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>
</body>
<script type="text/javascript">
var msg = 'Sign up to receive our newsletter for 10% off!';
function updateMessage() {
var el = document.getElementById('message');
el.textContent = msg;
}
updateMessage();
</script>
</html>
I am new to HTML and Javascript and I decided to try write a basic shopping cart.
I have a problem though. Why doesent this:
if(totalItems == 0)
{
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!";
}
Change this:
<b id = "yourCartContains">0</b>
To say "your cart contains no items" instead of 0?
The function definitely works, because I have tried switching the function to show an alert and it does this without any problems - so function works, but for some reason the function does not change the text.
Here is the function with the alert (I even changed totalItems to 0 to prove function is being called):
var totalItems = 0;
if(totalItems == 0)
{
alert("Random Alert is called upon function being executed");
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!"; <!-- But this isnt -->
}
I am debugging in chrome.
document.getElementByID().innerHTML definitely works.
Make sure:
document refers to the same document the element is in (you're not working with an iframe or such).
you call the function when the element is attached to the DOM.
This doesn't work:
<script>document.getElementById('foo').innerHTML = 'bar';</script>
<b id="foo"></b>
This works:
<b id="foo"></b>
<script>document.getElementById('foo').innerHTML = 'bar';</script>
your html is valid. It could be that invalid markup doesn't let your browser find the correct element.
Anyway, if you're working in chrome, you really should debug with the console and not with "alerts". Press F12 (on Windows / Linux) or Cmd + Opt + I on Mac. If there are any errors, you should see them in red in the console tab.
If there are no errors, do this:
if(totalItems == 0)
{
console.log('el: ', document.getElementById('yourCartContains'));
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!"; <!-- But this isnt -->
}
and see what your console tells you. (There probably will be an el: undefined)
This works for me. Have you loaded your script after your html?
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><b id = "yourCartContains">0</b></div>
<script>
var totalItems = 0;
if(totalItems == 0)
{
alert("Random Alert is called upon function being executed");
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!"; <!-- But this isnt -->
}
</script>
</body>
</html>
<script type="text/javascript">
var totalItems = 0;
if(totalItems == 0)
{document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!";}
</script>
<span id="yourCartContains" style="font-weight:bold"></span>
I have very painful experience using text to innerHTML.
Since my text contains a lot of dynamic element (select2 for searching option list) and I forgot to put ending quote . The text looks fine, in some cases, however, the innerHTML truncate the "submit" button is missing.
The text assigned to innerHTML is translate to other strange result automatically. if HTML syntax is not correct, it produces very weird string in innerHTML. the problem is intermittent, some case is fine, some are not good. Since project is big, I wasted whole night effort to fight to bug.
I finally figure a way to debug the dynamic element by using W3 validator (https://validator.w3.org/nu). copy and paste into a file and check the dynamic element syntax. There are some online HTML checker (https://www.freeformatter.com/html-validator.html).
I'm trying to ignore Ctrl-C in my website but im stuck.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="javascript">
function whichButton(event)
{
if (event.button==2)//RIGHT CLICK
{
alert("Not Allow Right Click!");
}
}
function noCTRL(e)
{
var code = (document.all) ? event.keyCode:e.which;
var msg = "Sorry, this functionality is disabled.";
if (parseInt(code)==17) //CTRL
{
alert(msg);
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<form method="">
<strong>Not Allow Paste </strong><BR>
<input type="text" value="" onMouseDown="whichButton(event)" onKeyDown="return noCTRL(event)"/>
</form>
</body>
</html>
I tried this code, but it is can only ignore right click.
How can I ignore Ctrl-C?
Have a look at this website
But if someone wants to copy your content, they can. It will just make it harder and more time consuming to use.
And also
Regarding this Ctrl-C you could add javascript to block it, but it is useless, since the user can always disable javascript. In fact many users will find interception of right-click very annoying.
All these could have a meaning if you are building an intranet application or you can ship an integrated browser for users to view the application. With public html, I believe it isn't even worth trying. One solution would be to build your application with flash or another plug-in. This way you can encrypt everything you've sent to the client.
if your body tag adds these events
<body oncontextmenu="return noMenu();" onkeydown="return noKeys(event);">
and you then define these functions in your <head> section, you can take action when the context menu is activated (right click) or when keys are pressed on your page.
<script type="text/javascript">
function noMenu()
{
alert("Not Allow Right Click!");
return false;
}
function noKeys(event)
{
if (event == null) event = window.event;
// here you can check event.keyCode
return false;
}
</script>
I'm trying to write a web application using the new offline capabilities of HTML5. In this application, I'd like to be able to edit some HTML—a full document, not a fragment—in a <textarea>, press a button and then populate a new browser window (or <iframe>, haven't decided yet) with the HTML found in the <textarea>. The new content is not persisted anywhere except the local client, so setting the source on the window.open call or the src attribute on an <iframe> is not going to work.
I found the following question on StackOverflow: "Putting HTML from the current page into a new window", which got me part of the way there. It seems this technique works well with fragments, but I was unsuccessful in getting an entirely new HTML document loaded. The strange thing is when I view the DOM in Firebug, I see the new HTML—it just doesn't render.
Is it possible to render a generated HTML document in a new window or <iframe>?
EDIT: Here's a "working" example of how I'm attempting to accomplish this:
<!doctype html>
<html>
<head>
<title>Test new DOM</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function runonload() {
return $("#newcode")[0].value;
}
$(function() {
$("#runit").click(function() {
w=window.open("");
$(w.document).ready(function() {
$(w.document).html(w.opener.runonload());
});
});
});
</script>
</head>
<body>
<textarea id="newcode">
<!doctype html>
<html>
<head>
<title>New Page Test</title>
</head>
<body>
<h1>Testing 1 2 3</h1>
</body>
</html>
</textarea>
<br/>
<button id="runit">Run it!</button>
</body>
</html>
I think you are overcomplicating this...
try this:
<SCRIPT LANGUAGE="JavaScript">
function displayHTML(form) {
var inf = form.htmlArea.value;
win = window.open(", ", 'popup', 'toolbar = no, status = no'); win.document.write("" + inf + ""); } // </script>
<form>
<textarea name="htmlArea" cols=60 rows=12> </textarea> <br> <input type="button" value=" Preview HTML (New Window)" onclick="displayHTML(this.form)"> </form>
$(w.document).html(w.opener.runonload());
You can't set innerHTML—or, consequently, jQuery's html()—on a Document object itself.
Even if you could, you wouldn't be able to do it using html(), because that parses the given markup in the context of an element (usually <div>) from the current document. The doctype declaration won't fit/work, putting <html>/<body>/etc inside a <div> is invalid, and trying to insert the elements it creates from the current ownerDocument into a different document should give a WRONG_DOCUMENT_ERR DOMException. (Some browsers let you get away with that bit though.)
This is a case where the old-school way is still the best:
w= window.open('', '_blank');
w.document.write($('#newcode').val());
w.document.close();
Whilst you can inject innerHTML into a pop-up's document.documentElement, if you do it that way you don't get the chance to set a <!DOCTYPE>, which means the page is stuck in nasty old Quirks Mode.