Reputation: 524
I have 2 JS files, I need to pass 2 variables from one to the other. For that I declared the variables as global in B.js and just tried to change them from A.js. This didn't work. (I have referenced both files correctly in the html). Now I'm trying to change the vars from B.js by calling a function from A.js and passing the vars as parameters.
B.js:
var re = '';
var un = '';
function init(response_string, username_string) {
re = response_string;
un = username_string;
}
A.js:
init(response, un);
The function in B.js gets the parameters correctly, however I can't seem to find a way to change the global variables. They remain as "".
EDIT: The values I parse from A.js are non-empty strings. I also tried this: init('test', 'test');
But the global variables still weren't affected.
EDIT 2: Heres more code: index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script src="A.js"></script>
<script src="B.js"></script>
</head>
<body>
<input type="text" name="" id="inp">
<a href="" onclick="pass()">Go</a>
</body>
</html>
A.js:
function pass() {
var text = document.getElementById('inp').value;
pass2(text);
}
B.js:
var global_string = '';
function pass2(v) {
console.log(v);
global_string = v;
}
Upvotes: 0
Views: 893
Reputation: 4537
You're calling init(response, un)
with two variables as parameters, but the first variable response
has not been defined, and the second variable un
, you've defined as an empty string ''
at the beginning of the code.
Call init()
with two non-empty strings, and you'll see that the global variables un
and re
get updated correctly.
var re = '';
var un = '';
function init(response_string, username_string) {
re = response_string;
un = username_string;
}
init("test1","test2");
console.log(re);
console.log(un);
Upvotes: 1