Global Variable In A Function

S

SamMan

I have a .js file that receives a value from an html page. I'd like this
value to be a global variable that all functions in the .js file can use. I
have tried just declaring a var at the top of my .js file, but when the
value comes into the function and gets assigned to that variable, it is not
global.

Any help, hints, etc. would be appreciated.

Thanks,
Sam
 
J

Jérôme VUIBERT

Strange it works for me but the global variable is in the <script> part of
the html document.

jerome
 
S

SamMan

What I'm trying to do is to pass a value from "first.html" to a function in
the .js file (works fine). This value should get assigned to a global
variable (not working) and within the same function, a new window is opened.
"second.html". This second pop-up window then calls (onLoad) another
function within the same .js file and writes the value of the global
variable to the page.

Thanks,
Sam
 
M

Martin Honnen

SamMan said:
I have a .js file that receives a value from an html page. I'd like this
value to be a global variable that all functions in the .js file can use. I
have tried just declaring a var at the top of my .js file, but when the
value comes into the function and gets assigned to that variable, it is not
global.

If you declare
var varName;
outside of any function then you have declared a global variable which
you can then use as
varName = expression
 
S

SamMan

Martin Honnen said:
If you declare
var varName;
outside of any function then you have declared a global variable which
you can then use as
varName = expression

Thanks Martin,

I'm aware of what you are saying, but the problem I'm having is that unless
I initialize the var (var varName = "someValue"), the variable remains null,
or undefined. In the code below, when "text" is assigned to "print", it is
not global, and "print" retains the value of "null".

Thanks for the help,
Sam

var print="null";

function testWindow(text) { //called by first page
print = text;
alert("first -" + print)
var newWin;
newWin = window.open("dataPage.html","", "height=80,width=250");
}

function passVar() { //called by pop-up page
alert("second function -" + print);
document.write(print);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top