Click to See Complete Forum and Search --> : Declaring Global Variables


dab100
02-19-2003, 10:11 AM
I was wondering how i can declare a variable outside a function and be able to the variable value within the function.

I tried the code below but it did not work. I thought to declare a global variable you used the "var" keyword. Here is the code i tried:


var firstTry = false;

function checkoutFields(formInfo) {
if ((!formInfo.Surname.value == "") && (!formInfo.Diff_Address.checked) && (firstTry == false)) {
alert(messArray[19]);
var firstTry = true;
}
if (firstTry) {
formInfo.Diff_Address.value = true;
var firstTry = false;
}
}

This always gives firstTry as undefined when the function is activated

gil davis
02-19-2003, 10:16 AM
If you use var inside a function, then the variable is local.

Remove the "var" keyword inside the function.

Charles
02-19-2003, 11:30 AM
Strictly speaking, though, there are no global variables in client side JavaScript. Nor can you really make your own functions. What you think are global variables are really properties of a Window object and functions you make are really methods of a Window object. (There are, however, built in global functions. alert() is one of them.) So, if you want to be clear that firstTry isn't a property of the call object then you might want to use window.firstTry. Though, this is only really useful if you have a property of your call object that has the same name as a property of your Window object..

superrad7
02-20-2003, 11:02 AM
it doesnt work. the only way i have found is to create new variables that have the same value

khalidali63
02-20-2003, 12:04 PM
The correct syntax for a global variable to be used inside a method should be like this

var firstTry = false;

function checkoutFields(formInfo) {
if ((!formInfo.Surname.value == "") && (!formInfo.Diff_Address.checked) && (firstTry == false)) {
alert(messArray[19]);
firstTry = true;
}
if (firstTry) {
formInfo.Diff_Address.value = true;
firstTry = false;
}
}


cheers

Khalid

Charles
02-20-2003, 12:21 PM
Except that 1) that doesn't use a global variable and 2) it's no more correct than:

var firstTry = false;
function checkoutFields(formInfo) {
if ((!formInfo.Surname.value == "") && (!formInfo.Diff_Address.checked) && (self.firstTry == false)) {
alert(messArray[19]);
self.firstTry = true;
}
if (self.firstTry) {
formInfo.Diff_Address.value = true;
self.firstTry = false;
}
}