Click to See Complete Forum and Search --> : Passing variables between functions


drgnfli4
07-11-2003, 12:56 AM
Can anyone tell me how to pass a variable that is established in one function on to a second function for further calculations.
The script I have now looks like this:

function price(size){
if (size==1) var a=.5;
if (size==2) var a=1;
if (size==3) var a=1.5;
if (size==4) var a=2;
if (size==5) var a=2.5;
if (size==6) var a=3;
if (size==7) var a=3.5;
if (size==8) var a=4;
if (size==9) var a=4.5;
if (size==10) var a=5;
if (size==11) var a=5.5;
if (size==12) var a=6;
parent.bottom.document.body.innerHTML="your total is: $"+ a * len;
}

var shad=0;

function shadow(value){
if (value==1) var shad=2;
else var shad=1;
parent.bottom.document.body.innerHTML="your total is: $"+ a * len * shad;
}

I keep getting an error with the second function that says " a is undefined"

Again, I would like "var a" (which is established in function price() ) to be passed to function shadow() for further calculations.

Any help will be appreciated. Thank you.

JHL
07-11-2003, 01:02 AM
in prize():

shadow(a);

this will pass the variable a from prize() to shadow().

another way is that you can declare 'a' as a global variable so that it can be access by any function.

drgnfli4
07-11-2003, 05:54 AM
Thanx JHL,

the method you first described will work perfectly for this script but for future refrence, How do I declare 'a' as a global variable?

Charles
07-11-2003, 06:14 AM
Client side JavaScript doesn't allow you to make global variables. THe best you can do is to give a Window object a property. You can do that explicitly, self.giantSays = 'fee, fie, foe, fum' or implicitly by omitting the word 'var'.

And you can shorten your code and get rid of all of those 'if' statements by using an Array literal and the ternary operator. In JavaSCript every line of code has a lot of overhead so it's good to keep things short.

<script type="text/javascript">
<!--
function price(size){
var value = ['', 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6][size];
var shad = value == 1 ? 2 : 1;
parent.bottom.document.body.innerHTML="your total is: $"+ a * len * shad;
}
// -->
</script>

drgnfli4
07-11-2003, 06:31 AM
Thanx Charles,

I will certainly use your suggestions.