use of a local variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tolgs
    New Member
    • Jan 2008
    • 3

    use of a local variable

    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.

    Code:
    <script type="text/javascript"> 
    function some_Function() { 
      somecode....;
      var_Local = some_Value;
     } 
    </script> 
    
    <script type="text/javascript"> 
    function some_Other_Function() { 
      somecode....;
     } 
    </script> 
    
    <form action="http://www.mydomain.com/results.php" method="post" 
    name="form" onsubmit="return (some_Other_Function(var_Local))"> 
    </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
  • rnd me
    Recognized Expert Contributor
    • Jun 2007
    • 427

    #2
    how you have it will work as long as some_Function is called before some_Other_Func tion.

    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:

    Code:
    function some_Function() { 
      somecode....;
      var Local = "some_Value";
    [B]  some_Function.Local = Local;[/B]
     }
    you can then access the variable from any function like this:

    Code:
    function some_Other_Function() { 
     alert(some_Function.Local);
     }

    Comment

    • tolgs
      New Member
      • Jan 2008
      • 3

      #3
      4th option was the one. thank you very much for your time!!

      Comment

      Working...