This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 4 years ago.
If I try to declare s as a variable it errors out. It is acting like s isn't a variable and really doesn't like any changes to the syntax at all.
I've actually written a decision tree webpage that relies on this concept a lot and I'm not sure why it works.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
A variable is undeclared when it does not use the var keyword. It gets created on the global object (that is, the window), thus it operates in a different space as the declared variables.
Find out more on this link
Variables that are assigned without var keyword are called undeclared. These are created in the global scope. So your s variable is available in the click handler.
Now this only happens in non-strict mode, so if you put 'use strict' directive inside or above the selection function you'll get an error.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
'use strict'
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
Setting your s like this:
function selection(select){
s = select;
}
is similar (for variable scope) to:
var s;
function selection(select) {
s = select;
}
So s exists as a property of window, and available both inside of selection function and for alert("boop " + s);, because window is a global object. But if you declare and assign a value to variable with var inside a function:
function selection(select) {
var s = select;
}
s will have only a scope of function selection, and retrieving it here:
alert("boop " + s);
causes an error, because it doesn't exist here.
Related
Trying to write a JS/HTML program that takes the user's name as an input and outputs "Hello, [Name]!" when you click he button.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>
JS:
let txtName = document.querySelector('#txtName');
//let name = "lauren";
function sayHello() {
document.write("Hello, " + txtName + "!");
}
When I try to run it, it outputs "Hello, null!" everytime.
Move it to the function itself and add "value":
function sayHello() {
let txtName = document.querySelector('#txtName').value;
document.write("Hello, " + txtName + "!");
}
Your function does not have access the the txtName variable. You should move it inside the function. You can also use getElementById instead of a query selector. Since were there, why not remove the variable entirely:
function sayHello() {
document.write("Hello, " + document.getElementById('txtName').value + "!");
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>
Your code had 2 problems with it. One is scope and the other is value.
let txtName
As the variable is initiated using let, its scope is limited and not global. Use var to make it global, so it can get access inside functions too.
let txtName = document.querySelector('#txtName');
This line of code is running as soon as the page loads. So it is assigned the input object as the page gets loaded (and not the value). For printing the name, although we need the value of this object, (which is the second point) and not the whole object itself. We access its value by using .value.
var txtName = document.querySelector('#txtName').value;
Define this line inside the called function else it will get null value, because it will run as soon as the page loads and null value will be assigned because no input is there inside the input box.
function sayHello() {
var txtName = document.querySelector('#txtName').value;
document.write("Hello, " + txtName + "!");
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>
I have variable which is i think global ,,so all my child functions must be able to get that variable,But i am getting a reference error,Variable not declared
Here is below code.Please help if i am doing any wrong thing.Thanku
<!DOCTYPE html>
<html>
<head>
<script>
var Test1Object = 'Testing'; // This is my variable
</script>
<script src = 'ch.js'>
</script>
</head>
<body>
<button onclick="openwindow()">Create window</button>
</body>
</html>
My Ch.js
(function(){
alert(Test1Object) // Here i am getting this object
this.openwindow = function() {
w =window.open("untitled.html",'TheNewpop','height=315,width=625');
w.document.write(
"<body>"+
"<\/body>" +
"<script src = \"windowpo.js\"><\/script>" // THis is where i reference my windowpo.js
)
w.document.close();
w.focus();
}
})()
My windowpo.js
(function(){
alert(Test1Object) // Here there is not Test1Object (Reference error)
})();
My issue is that in my windowp.js how can i get my Test1Object Variable...
Easy doing by just acessing your refrence inside the window by using window.opener like in this runnable demo plnkr. Inside your window application you can access it via window.opener.Test1Object where window.opener holds a reference of the JavaScript instance where it was opened. In that way you can access all the stuff you configured in your main application:
Source: window.opener MDN reference
View
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker</title>
<script type="text/javascript">
var Test1Object = 'Testing';
</script>
<script src="main.js"></script>
</head>
<body>
<a onclick="openwindow()">Open Window</a>
</body>
</html>
main.js
this.openwindow = function() {
w = window.open(location.href+"untitled.html",'TheNewpop','height=315,width=625');
w.document.close();
w.focus();
}
unitiled.html
Some Test
<script src="windowpo.js"></script>
windowpo.js
alert(window.opener.Test1Object);
As most other answers don't seem to even read the question properly, I'll add my 2 cents as an answer, too:
The main problem in your code, is that you have to JS execution contexts here: One for the original page (the HTML code you show) and one for the popup you open in Ch.js. In general both do not share any data, variables or whatever.
You have, however, a window object reference in your variable w after calling window.open(). You use this already to inject HTML code to the popup.
If you now want to have JS variables available in the popup JS context, you can either inject additional <script> tags into the popups HTML code and set the variables there (bad choice, imho) or use postMessage() to send data across. I give some sample code for the postMessage() variant below:
Ch.js
this.openwindow = function() {
w = window.open("untitled.html",'TheNewpop','height=315,width=625');
w.document.write(
"<body>"+
"<\/body>" +
"<script src = \"windowpo.js\"><\/script>" // THis is where i reference my windowpo.js
);
w.document.close();
w.focus();
// wait for pupup to be ready
window.addEventListener( 'message', function( e ){
// send the variable
if( e.data == 'inited' ) {
w.postMessage( Test1Object, '*' );
}
})
}
windowpo.js
// wait for messages from opener
window.addEventListener( 'message', function( e ) {
alert( e.data );
});
// tell the opener we are waiting
window.opener.postMessage( 'inited', '*' );
For some more information see the respective MDN article on Window.postMessage().
You need to declare the variable before you include in any file. Simply create a script tag above the included files define it there.
<script type='text/javascript' >
var Test1Object = 'Testing';
</script>
<script type='text/javascript' src='js/Ch.js'></script>
<script type='text/javascript' src='js/windowpo.js'></script>
this way you should be able to use withing all files
I have the following code. The first time the function is called the iframe changes contents to newPage but the second time the function is called the page doesn't change.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Submit</title>
<script>
var url = 1;
function setURL(url){
var win1 = "http://localhost/Audio/src/submit1.html" ;
var win2 = "http://localhost/Audio/src/newPage.html";
if (url === 1){
document.getElementById('iframe').src=win2;
url=2;
}
else{
document.getElementById('iframe').src=win1;
url=1;
}
}
</script>
</head>
<body>
<iframe src="http://localhost/Audio/src/audio.html" style="width:0;height:0;border:0; border:none;"></iframe>
<iframe id="iframe" style="border:0; " src="http://localhost/Audio/src/submit1.html">
</iframe>
<input type="button" value="click me 71" onclick="setURL(url)">
</body>
</html>
You have two variables called url.
The one defined as a global and the one defined as the function argument.
Your function only changes the one defined as the function argument, which isn't preserved anywhere.
If you want to modify the global one: Don't define the argument in the function definition (and don't bother passing an argument to the function).
since you are passing the same name as parameter (url) you have to explicitly say which one do you want to change or change the parameter name (from url to u for instance)
I want to set a permanent value to a div element with jQuery;
the full js file:
$(function () {
var $a;
var $b;
$('button').click(function () {
$a = $('#a').val();
$b = $('#b').val();
var $big = getBigger($b, $a);
var $small = getSmaller($b, $a);
$('#bigger').text($big);
$('#smaller').text($small);
});
});
//a simple function for getting a bigger element
function getBigger(a, b) {
return a ^ (a ^ b) & -(a < b);
}
//a simple function for getting a smaller element
function getSmaller(a, b) {
return (a < b) ? a : b;
}
the full html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style/style.css">
<title>Compare</title>
</head>
<body>
<form>
Enter a: <input type="number" id="a"><br/>
Enter b: <input type="number" id="b"><br/>
<button> Compare</button>
<div id="bigger"></div>
<div id="smaller"> </div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The problem is that when I leave the scope the variable gets destroyed
PS. Now I realise that my mistake is that when a <button> is added in a form element, everytime the button is pressed, the data in the form gets reseted
When you run code within a function it creates a scope. Each variable you define using the var statement will be available only in that scope.
To create a variable for usage outside of the current scope, either declare a variable without putting var beforehand or directly write window.varname = value. Have another read on that topic.
Besides that, in your code $('#bigger').text($big); the var $big never even gets defined, so maybe that is the problem.
And setting an elements text works independent from scopes or variables.
Try this
To Access:
$("#a").data('value');
To Set
$("#a").data('value' , 'whatevervalue');
To Access Without JQuery:
document.getElementById("a").dataset.value;
To Set Without JQuery;
document.getElementById("a").dataset.value = "Some Value";
A Div cannot hold the Value attribute unless you use:
document.getElementById("a").setAttribute("value" , "val");
Then to Assign it to Inside your div:
$("#myDivElement").html($("#a").data('value'))
var jem = 55;
var app = angular.module("store",[]);
app.controller("storeController",function(){
this.product = jem;
});
jem = 0;
<!DOCTYPE html>
<html ng-app="store">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="storeController as store">
<p>{{"HI"}}</p>
<p>{{store.product}} </p>
</body>
</html>
Why does this output is "0" instead of "55"? Since jem is a basic javascript variable when product is assigned with jem it gets its value copied and should not change when jem is changed?
Notice that your controller definition is inside a callback function (as it should be...)
app.controller("storeController", function(){
this.product = jem;
});
A side effect of this, relevant to your question, is that the assignment statement within the callback, this.product = jem, will get executed after the assignment statement, jem = 0, outside of the callback.
The takeaway is that callbacks do not take place sequentially with the rest of your code.