Retrieving Variable From A Javascript File - javascript

My question is how to share a variable between two different javascript files. I am creating a form that transfers the value to a different page, which alerts that variable. I have 2 html files (index.html and form.html) as well as 2 javascript files (form.js and index.js). So basicly I want to share the variable theNick from form.js to index.js to display it using alert(). If this is not possible, is there another way to do this?
form.html:
<input type="text" id="Nick" placeholder="Nickname">
<a id="btn" onclick="submit()" href="index.html.">Submit</a>
form.js:
function submit(){
var theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
index.html:
<button onclick="callNick()">Click Me to view your Nickname.</button>
index.js:
function callNick(){
???????
alert(theNick); //I want to get access to this variable from form.js
}

By using the var keyword you are doing exactly the opposite. If you want to share something the easiest thing would be to bind the variable to the window object like this: window.theNick = ... and use it like alert(window.theNick).

It is sort of possible.
First of all you need to make certain that your HTML loads both JavaScript files. There isn't really a way for them to import each other, so the HTML must load both scripts.
Secondly, you need to modify your function submit to use a global variable. Global variables are initially defined outside the scope of a function. The function callNick is already looking for a global variable.
However, the submit function is defining its own, local variable because of the keyword var being used inside the function scope. Change it like so:
// Set global variable
var theNick;
function submit(){
// Use global variable
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
See this article for further information.
http://www.w3schools.com/js/js_scope.asp

You could just declare the variable outside of the function
var theNick; // you could omit this entirely since it will be declared in
// global scope implicitly when you try to assign it in the function
function submit(){
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
}
javascript does not care about which files declarations are made but in which scope.
By placing the variable in global scope you'll be able to access it everywhere.
Global variables are not the best coding strategy but this should help you with the concept

It seems like you need to store the variable in the local storage object of the window object, this way you can set its value on the first page and retrieve it on the second.
page 1
window.localStorage.setItem("yourVariable", "yourValue");
page 2
var myVar = localStorage.getItem("yourVariable");
Only one 'caveat': this is a html5 feature, so it comes with limitations, check this link for more info.

You can pass your variable into the url, using the ?yourVar= GET mark :
form.js
function submit(e){
var theNick = document.getElementById("Nick").value; //retrieves theNick
e.target.href+='?n='+theNick; // set the href of your anchor with your variable
}
form.html
<input type="text" id="Nick" placeholder="Nickname">
<!-- We pass the event object into our function as a parameter -->
<a id="btn" onclick="submit(event)" href="index.html">Submit</a>
index.js
function callNick(){
// get the variable from the current location
var theNick = window.location.href.split('?n=')[1];
alert(theNick);
}
index.html
<button onclick="callNick()">Click Me to view your Nickname.</button>
▶︎ Plunker where "form" has been changed to "index" and "index" to "result".
Note :
To pass multiple variables, you can use the & delimiter, and then use the window.location.search property as done in this CSS-tricks article.
▶︎ Multiple vars plunker

Related

javascript function not defined even its defined [duplicate]

I can't find out what is the problem with this JSFiddle.
HTML:
<input type="button" value="test" onclick="test()">
JavaScript:
function test(){alert("test");}
And when I click on button - nothing happened. The console says "test not defined"
I've read the JSFiddle documentation - there it says that JS code is added to <head> and HTML code is added to <body> (so this JS code is earlier than html and should work).
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
Change the wrapping setting to "no wrap" and it'll work:
http://jsfiddle.net/zalun/Yazpj/1/
I switched the framework to "No Library" as you don't use any.
The function is being defined inside a load handler and thus is in a different scope. As #ellisbben notes in the comments, you can fix this by explicitly defining it on the window object. Better, yet, change it to apply the handler to the object unobtrusively: http://jsfiddle.net/pUeue/
$('input[type=button]').click( function() {
alert("test");
});
Note applying the handler this way, instead of inline, keeps your HTML clean. I'm using jQuery, but you could do it with or without a framework or using a different framework, if you like.
There is another way, declare your function into a variable like this :
test = function() {
alert("test");
}
jsFiddle
Details
EDIT (based on the comments of #nnnnnn)
#nnnnnn :
why saying test = (without var) would fix it ?
When you define a function like this :
var test = function(){};
The function is defined locally, but when you define your function without var :
test = function(){};
test is defined on the window object which is at the top level scope.
why does this work?
Like #zalun say :
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
But if you use this syntax :
test = function(){};
You have an access to the function test because it's defined globally
References :
https://stackoverflow.com/a/338053/3083093
https://stackoverflow.com/a/5830423/3083093
Change wrap setting in the Frameworks & Extensions panel, to "No wrap-in <body>"
There is no problem with your code.Just choose the extension onLoad() from right side.
<script>
function test(){
alert("test");
}
</script>
<input type="button" value="test" onclick="test()">
Select OnDomready
HTML:
<input id="dButton" type="button" value="test"/>
JavaScript:
addEventListener('load', init, false);
function init()
{
oInput = document.getElementById('dButton');
oInput.onclick = test;
}
function test(){
alert("test");
}

Passing a value from a javascript to another js file

My code is...
<script type="text/javascript">
function changeval() {
$total = parseInt($("#small").val()) + parseInt($("#medium").val());
}
</script>
How can I pass '$total' to another js file, say main.js.
Call changeval function from another file, save/use returned value.
function changeval() {
return parseInt($("#small").val()) + parseInt($("#medium").val());
}
Or have one global variable save value inside the same variable and access it from another file.
Make sure that $total is assigned to the global scope and make sure the script where you want to use it is below the script where you assign it. Be careful about polluting the global scope too much because it can make code that is very tricky to debug and can cause strange errors if you overwrite a native global variable.

JavaScript Variable Passing between different .js

I am trying to pass 4 variables from one js file to another.
I read here that you must write:
window.myVar = "foo";
to make your variable "super"-global.
In the first js file, I have
window.signJoueur1 = string1.charAt(7);
window.signJoueur2 = string2.charAt(7);
window.valeurJoueur1 = random1;
window.valeurJoueur2 = random2;
In the second js file, I did
console.log(window.signJoueur1);
console.log(window.signJoueur2);
console.log(window.valeurJoueur1);
console.log(window.valeurJoueur2);
function trouveCombinaison(signJoueur1, signJoueur2, valeurJoueur1, valeurJoueur2)
{
console.log(signJoueur1);
console.log(signJoueur2);
console.log(valeurJoueur1);
console.log(valeurJoueur2);
}
It should work, but all console.log return `undefined'.
If you want more informations here are the full codes:
first .js http://pastebin.com/0zJKFNem
second .js http://pastebin.com/TsWc7TxL
the html http://pastebin.com/t3SzwZSC
So, my question is, how can I actually pass through the variables?
You are trying to use the values before they exist.
The code that assigns the values to the variables are inside a function, and that function isn't called until you click a button. The code that tries to show the values is executed when the page loads, so it uses the variables before they have been assigned any values.
Actually i just had to put window. in the second console.log group.
Such as :
function trouveCombinaison()
{
console.log(window.signJoueur1);
console.log(window.signJoueur2);
console.log(window.valeurJoueur1);
console.log(window.valeurJoueur2);
}
The fact that the console.log out of the function don't work is that it's executed when the page loads, as explained by #Guffa.
Now it works.

Javascript reference not defined, simple un-realized function [duplicate]

I can't find out what is the problem with this JSFiddle.
HTML:
<input type="button" value="test" onclick="test()">
JavaScript:
function test(){alert("test");}
And when I click on button - nothing happened. The console says "test not defined"
I've read the JSFiddle documentation - there it says that JS code is added to <head> and HTML code is added to <body> (so this JS code is earlier than html and should work).
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
Change the wrapping setting to "no wrap" and it'll work:
http://jsfiddle.net/zalun/Yazpj/1/
I switched the framework to "No Library" as you don't use any.
The function is being defined inside a load handler and thus is in a different scope. As #ellisbben notes in the comments, you can fix this by explicitly defining it on the window object. Better, yet, change it to apply the handler to the object unobtrusively: http://jsfiddle.net/pUeue/
$('input[type=button]').click( function() {
alert("test");
});
Note applying the handler this way, instead of inline, keeps your HTML clean. I'm using jQuery, but you could do it with or without a framework or using a different framework, if you like.
There is another way, declare your function into a variable like this :
test = function() {
alert("test");
}
jsFiddle
Details
EDIT (based on the comments of #nnnnnn)
#nnnnnn :
why saying test = (without var) would fix it ?
When you define a function like this :
var test = function(){};
The function is defined locally, but when you define your function without var :
test = function(){};
test is defined on the window object which is at the top level scope.
why does this work?
Like #zalun say :
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
But if you use this syntax :
test = function(){};
You have an access to the function test because it's defined globally
References :
https://stackoverflow.com/a/338053/3083093
https://stackoverflow.com/a/5830423/3083093
Change wrap setting in the Frameworks & Extensions panel, to "No wrap-in <body>"
There is no problem with your code.Just choose the extension onLoad() from right side.
<script>
function test(){
alert("test");
}
</script>
<input type="button" value="test" onclick="test()">
Select OnDomready
HTML:
<input id="dButton" type="button" value="test"/>
JavaScript:
addEventListener('load', init, false);
function init()
{
oInput = document.getElementById('dButton');
oInput.onclick = test;
}
function test(){
alert("test");
}

jquery pass value into function AFTER function?

I am new to javascript & jQuery. I'm trying to create a feature for my site that let's people display badges they have earned on their own site (and I would supply a bit of code they could just copy/paste). I had someone help me with the javascript and I have it working perfectly, but I can't find any jQuery documents that explains it to me?
<script type="text/javascript">
(function(id) {
// include js via php file with the id in as a parameter
})("myid");
</script>
The id is passed in the area labeled "myid", in jQuery can you pass in a static variable this way? When I try to delete ("myid") and change it to var id = 'myid', the function no longer works.
The occurrence of "myid" in the code you are showing is not a static variable. It is a string literal that is being passed as an argument to an anonymous function. The anonymous function is declared and then is immediately getting called.
If you are wondering why the programmer wrote the JavaScript the way they did. The following might help.
Both of the examples below will display "myid" in an alert:
Example 1:
<script type="text/javascript">
var id = 'myid';
alert(id);
</script>
Example 2:
<script type="text/javascript">
(function(id) {
alert(id);
})('myid');
</script>
The first example declares "id" as a variable. It is a global variable and is actually added as a property to the window object. The second example defines an anonymous function and immediately calls it, passing in 'myid' as the value of the "id" parameter. This technique avoids using a global variable.
Of course, you could also avoid the global variable by doing the following:
<script type="text/javascript">
(function() {
var id = 'myid';
alert(id);
})();
</script>
If you stick "myid" in a variable and then pass in that variable, it'll work. Like this:
var memberID = "myid";
(function(id) {
// include js via php file with the id in as a parameter
})(memberID);
If you say this...
(function(id) {
// include js via php file with the id in as a parameter
})(var id = 'myid');
...you're attempting to stick a variable declaration in a function call, which won't work. That's why declaring the variable above and apart from the function call won't throw any errors.

Categories