button onclick function is not called - javascript

I'm making a webpage and when a button is clicked, it will delete every element inside the HTML element and append an iframe. Although, it doesn't seem to be working.
index.html:
<html id="html">
<head>
<script type="text/javascript" src="/freevpn/script.js"></script>
</head>
<body>
<input type="text" id="input" value="https://">
<button onclick="submit()">Go!</button>
</body>
</html>
script.js:
function submit() {
var submit = document.getElementById("submit");
var input = document.getElementById("input");
var iframe = document.createElement("iframe");
var html = document.getElementById("html");
iframe.setAttribute("src", input.value);
html.innerHTML = "";
html.appendChild(iframe);
iframe.requestFullscreen();
}
I'm not sure why this isn't working, but it has to be something. Thanks in advance!
NEW UPDATE: There were a few problems. It is linking to the javascript, I fixed the function, and I added parenthesis, but it doesn't seem to be updated in the browser. I've cleared my cache and everything, and it still isn't updating. My website is linked through Freenom, Cloudflare, Google Analytics and Search Console, so does it just take a while to update? And if so, is there a way to make it faster?

Try this, you are calling the function incorrectly.
You must use the () to call a function:
<button onclick="submit()">Go!</button>
function submit() {
var submit = document.getElementById("submit");
var input = document.getElementById("input");
var iframe = document.createElement("iframe");
var html = document.getElementById("html");
iframe.setAttribute("src", input.value);
html.innerHTML = "";
html.appendChild(iframe);
iframe.requestFullscreen();
}
<html id="html">
<head>
<script type="text/javascript" src="/freevpn/script.js"></script>
</head>
<body>
<input type="text" id="input" value="https://www.youtube.com/embed/_70Q-Xj3rEo">
<button onclick="submit()">Go!</button>
</body>
</html>

You are missing the parentheses when you are calling your JavaScript function. Try the below:
<button onclick="submit()">Go!</button>
Here is a handy reference for the onclick Event: https://www.w3schools.com/jsref/event_onclick.asp
Also it is a good idea to call put your <script> tag at the bottom of the body (i.e. below the button in your code snippet). This is because the Javascript file will be loaded first and the HTML elements may not have been created yet that you are accessing with the DOM.

Related

I want to save a text input field into local storage and then display the value on an other .html page

I´m a beginner and for my first project I´d like to make a text based game.
I´d like the player to input his name into a field and then display his name on following pages.
I choose to to this with localStorage because I do not know any server-side programming yet.
If possible, I would like to not use a javascript library.
I think, I´m gettin the value of the user the right way:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
// Gets input value
var uName = document.getElementById("myInput").value;
// Saves data to retrieve later
localStorage.setItem("userName", uName);
// Updates HTML
updateHTML();
}
</script>
</head>
<body>
set user name:
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
</body>
</html>
The second page looks like this:
<!DOCTYPE html>
<html>
<head>
<script>
function getName() {
return localStorage.getItem("userName");
}
function updateHTML() {
var uName = getName();
document.getElementById("storedName").innerHTML = uName;
}
</script>
</head>
<body class=backgroundcomputer001>
"Welcome back <p id="storedName"></p>
</div>
</body>
</html>
I don't know what I am doing wrong, and I already spent more than two days on this problem.
Any help appreciated.
( I know that I should keep the javascript and the html seperated, but it is more easy for me to visualize what is happening.)
So first the updateHTML function is not called anywhere. You have declared it but haven't called it. You can add updateHTML(); to the end of your script and it will be executed. The second problem is that even in this case the code wouldn't be able to display the name because of the following error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
This means that at the moment the function was executed the document wasn't still completely loaded. As a solution you can put your script just before closing body tag.
<!DOCTYPE html>
<html>
<head>
</head>
<body class=backgroundcomputer001>
<div>
Welcome back <p id="storedName"></p>
</div>
<script>
function getName() {
return localStorage.getItem("userName");
}
function updateHTML() {
var uName = getName();
document.getElementById("storedName").innerHTML = uName;
}
updateHTML();
</script>
</body>
Instead of using the function updateHTML(); what you need is to redirect to the following HTML and you have to do it with this instruction:
window.location.href = "index.html"; // name of your html that presents the username
And for the HTML where it presents the user name, add a function that is executed when it finishes reloading the HTML, like this:
<script>
window.onload=function() { //This function is executed when loading the page
var uName = localStorage.getItem("userName");
document.getElementById("storedName").innerHTML = uName;
}
</script>
And to present the name and this next to the welcome you can do it like this
<p>"Welcome back <span id="storedName"> </span></p>
Sorry for my english but i hope i have solved your problem. Happy quarantine :D

Browser ignores Javascript [duplicate]

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>

Null while grabbing an element with .getElementById

I am trying to grab an element (a button) and add an event listener on it.
Whenever I run
var button = document.getElementById('clickMe');
console.log(button); // null
I checked that my javascript file is loading and checked that everything is case sensitive. Here is my html and JS Files:
HTML:
<!doctype html>
<html>
<head>
<script src="js/timer.js"></script>
</head>
<body>
<button id='clickMe' type='button'>Hello</button>
</body>
</html>
JS
var button = document.getElementById('clickMe');
console.log(button);
function buttonClicked () {
alert('the button was clicked');
}
button.addEventListener('click', buttonClicked);
function timerComplete () {
alert('timer complete');
}
setTimeout(timerComplete, 2000);
The most common errors I have found was camel casing getelementbyid which I did.
Does anyone know why I keep getting null? Is it trying to grab the element before it is loaded?
Your Javascript code is executed before the Button is added to the DOM. You could change your HTML to this:
<!doctype html>
<html>
<body>
<button id='clickMe' type='button'>Hello</button>
<script src="js/timer.js"></script>
</body>
</html>
Or even better, if you don't mind making your JS code a bit more complex you could wait for your dom elements to be loaded before executing that part of the code:
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('clickMe');
console.log(button);
});
If you use this JS you can put back your script tag back to the head

How can I save the contents of a textarea as a variable using javascript in an external document?

I have tried, as many have suggested, saving a variable as the .value or .innerHTML of an ID, found by using document.getElementById. Here is all of my HTML:
<html>
<head>
<title>write</title>
<script type="text/javascript" src="g.js"></script>
<link rel="stylesheet" type="text/css" href="g.css" />
</head>
<body>
<div id="box">
<textarea id="txt" placeholder="placeholder. type here.">text text</textarea>
</div>
</body>
</html>
and here is my javascript, currently meant to fire an alert that contains the text in the text area – right now that would be, text text:
function run(){
var txt = document.getElementById('txt');
alert(txt);}
run()
Right now, loading the page fires an alert with the text Null and adding .value after getElementById('txt') results in no alert. Many thanks in advance.
The problem is that your javascript is executing before the DOM is constructed. When you load the JavaScript file in the <head> of the document, it is executed immediately, before the <textarea> tag has been created.
Try moving your script block below the textarea, just before the </body> tag.
Here's an example: fiddle
After the DOM is constructed you can use getElementById just as have and can access the contents of the textarea with the value attribute. All of this is in the fiddle above.
Alternatively, you can wrap your run() method call with a library that provides an event when the DOM becomes ready. jQuery's example would be:
$(function () {
// code you want to execute when the DOM is ready.
run();
});
function run() {
var txt = document.getElementById("txt").value;
alert(txt);
}
$(document).ready(function(){
run();
});
check this jsfiddle link
You are not getting textarea value because your javscript function is getting executed before there's value in DOM
or using javascript
function run(){
var txt = document.getElementById("txt").value;
alert(txt);
}
window.onload = run();
More about window.onload
The javascript below works in firefox. In fact, if you click the answer button for this question, you can try it out in firebug on this very page...
var textArea = document.getElementById("wmd-input"); // #wmd-input is the text input where your answer goes...
alert( textArea.value );
Make sure you enter some text first, of course.
While you're at it, you should give jQuery a try:
alert( $("#wmd-input").val() );
Or better yet,
console.log($("#wmd-input").val());
Hope that helps.

IE Issue: Submitting form to an iframe using javascript

I was trying to create an iframe element using javascript, like so:
var iframe = document.createElement('iframe');
iframe.setAttribute('name', 'frame_x');
However, when I tried submitting a form using the newly-created iframe as target, IE opens up a new window, instead of using the iframe.
form.setAttribute('target', 'frame_x');
form.submit();
This works perfectly in Firefox. Also, the iframe gets created, but is not used.
You've hit a bug in Internet Explorer.
You CAN NOT set the name attribute of ANY element in IE using the standard DOM Method .setAttribute('name', value);
In IE (before version 8 running in IE8 standards mode) this method will not work to set the name attribute.
You need to use one of the following:
//A (any browser)
var iframe = document.createElement('iframe');
iframe.name = 'frame_x';
//B (only in IE)
var iframe = document.createElement('<iframe name="frame_x"/>');
//C (use a JS library that fixes the bug (e.g. jQuery))
var iframe = $('<iframe name="frame_x"></iframe>');
//D (using jQuery to set the attribute on an existing element)
$('iframe:first').attr('name','frame_x');
Welcome to SO.
One issue I saw in your code is that you're never actually displaying the iframe. In order for it to appear on the page, you have to insert it into your document. In my example, I create a <span> tag to act as the slot where the iframe will get inserted.
See if this does what you're looking for.
<!-- http://stackoverflow.com/questions/2181385/ie-issue-submitting-form-to-an-iframe-using-javascript -->
<html>
<head>
<script type="text/javascript">
function submitFormToIFrame(){
var form=document.getElementById('myform');
form.setAttribute('target', 'frame_x');
form.submit();
}
</script>
</head>
<body>
<h1>Hello Erwin!</h1>
<form id="myform" name="myform" action="result.html">
<input type="button" value="Submit the Form" onClick="submitFormToIFrame();">
</form>
<span id="iframeSlot">
<script type="text/javascript">
var iframe = document.createElement('iframe');
iframe.setAttribute('name', 'frame_x');
document.getElementById('iframeSlot').appendChild(iframe);
</script>
</span>
</body>
</html>
UPDATE:
I found that this solution is only working in Firefox. So I did some experimenting. It seems that if you define the iframe in the html (instead of generating it via JS/DOM) then it works. Here is the version that works with IE and Firefox:
<html>
<head>
<script type="text/javascript">
function submitFormToIFrame(){
//IE
if( document.myform ){
document.myform.setAttribute('target','frame_x');
document.myform.submit();
//FF
} else {
var form=document.getElementById('myform');
form.setAttribute('target', 'frame_x');
form.submit();
}
}
</script>
</head>
<body>
<h1>Hello Erwin!</h1>
<form id="myform" name="myform" action="result.html" target="">
<input type="button" value="Submit the Form" onClick="submitFormToIFrame();">
</form>
<span id="iframeSlot">
<iframe name="frame_x">
</iframe>
</span>
</body>
</html>
function sendForm(idform){
var nfi = "RunF"+tagRandom();
$("body").append("<iframe name=\""+nfi+"\" id=\""+nfi+"\" class=\"runAgents\" src=\"#\"></iframe>");
$("#"+idform).attr("target",nfi);
$("#"+idform).submit();
}
To continue #scunliffe’s answer, if using Prototype.js:
var iframe = Element('iframe', {name: 'frame_x'});
which works because this helper function detects HAS_EXTENDED_CREATE_ELEMENT_SYNTAX for IE, working around the .name = … bug.

Categories

Resources