Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with variables (newbie)

Status
Not open for further replies.

jaburke

Programmer
May 20, 2002
156
US
I have a javascript variable defined as:
var name;

In my HTML, I am calling a javascript function that sets the name variable.

Once I return from the function call, the value of name isn't set. What am I doing wrong? How can I access the value of the name variable from the html after the function is called?
 
If the argument name in your function definition is also "name", then the variable "name" in the function will be local to that function:

Code:
var name = 1;

function doSomething(name) {
	name++;
	alert(name);		/* 2 */
};

alert(name);			/* 1 */
doSomething(name);
alert(name);			/* 1 */;

There are several ways around this. You could:

- Use a different argument name, so that "name" refers to the global variable instead of a local variable:

Code:
var name = 1;

function doSomething(otherName) {
	name++;
	alert(name);		/* 2 */
};

alert(name);			/* 1 */
doSomething(name);
alert(name);			/* 2 */;

Or, refer to "window.name" inside the function, which would always be the global variable. This way you can also refer to only "name" to use the local version:

Code:
var name = 1;

function doSomething(name) {
	window.name++;
	alert(window.name);	/* 2 */
	name++;
	alert(name);		/* 2 */
};

alert(name);			/* 1 */
doSomething(name);
alert(name);			/* 2 */;

Of course, you've posted no code at all, so all of this is guesswork. If I'm right, and you are naming your argument "name", it has to be asked: Why are you passing a global variable into a function when you can access it anyway without passing it in?

If I'm wrong, and you've not got an argument called "name", then I can only assume you also have a local variable called "name", in which case, either rename it or use the "window." trick.

Failing all of this, post some code. We're not psychic :)

Hope this helps,

Dan


Coedit Limited - Delivering standards compliant, accessible web solutions

[blue]@[/blue] Code Couch:
[blue]@[/blue] Twitter:
The Out Atheism Campaign
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top