By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,742 Members | 2,044 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,742 IT Pros & Developers. It's quick & easy.

use of a local variable

P: 3
I have a variable with a numberic value calculated/defined within a function. In some other part of the page, I want to be able to use the value of that variable; however, since that variable is generated as part of the previous function, it is defined as a local variable and its value is not available to the other function.

Is there a way to be able to transport the value of a local variable to a function that is out of scope? I welcome any suggestions.

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript"> 
  2. function some_Function() { 
  3.   somecode....;
  4.   var_Local = some_Value;
  5.  } 
  6. </script> 
  7.  
  8. <script type="text/javascript"> 
  9. function some_Other_Function() { 
  10.   somecode....;
  11.  } 
  12. </script> 
  13.  
  14. <form action="http://www.mydomain.com/results.php" method="post" 
  15. name="form" onsubmit="return (some_Other_Function(var_Local))"> 
  16. </form> 
As I described above, I would like to be able to use the value of the var_Local as part of the onsubmit, but I am getting a var_Local is unknown error, even though I can see/write its value if I do document.write within the some_Funciton() function

Thanks
Oct 10 '08 #1
Share this Question
Share on Google+
2 Replies


rnd me
Expert 100+
P: 427
how you have it will work as long as some_Function is called before some_Other_Function.

when you don't use the var keyword, you create not a local, but a global variable.
var_Local = some_Value; //makes global
var Local = some_Value; //makes local

since the value of the variable is set inside of some_Function, it must be called in order for the variable to be set as expected.


there is a third category, protected.
these are like globals except they live inside of a parent function that encloses both of the other functions.

a fourth option is an object property.
i recommend using these instead of globals whenever possible.
you can simply tack the variable onto the function object it lives in:

Expand|Select|Wrap|Line Numbers
  1. function some_Function() { 
  2.   somecode....;
  3.   var Local = "some_Value";
  4.   some_Function.Local = Local;
  5.  } 
you can then access the variable from any function like this:

Expand|Select|Wrap|Line Numbers
  1. function some_Other_Function() { 
  2.  alert(some_Function.Local);
  3.  } 
Oct 10 '08 #2

P: 3
4th option was the one. thank you very much for your time!!
Oct 17 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.