[RESOLVED]Sharing data between functions

Function A computes a sum on a click event. Then the function ends. A new click event from  another button runs function B. Can functtion B access the sum?

If so, how can this be done? Thanks.

davelewicki

Can functtion B access the sum?

Yes

davelewicki

If so, how can this be done?

You need to declare the variable at a higher scrope,preferably outside of all function and use the variable inside the function like given below

  <script>
    //variable to hold the value
  var str =0;
    function addition(){
      //assign value to variable
      str=10;
    }
    function SecondAddtion(){
      //use the variable here
      var total = parseInt(str) +10;
      //show the output
      alert(total)
    }
  </script>

Complete Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script>
    //variable to hold the value
  var str =0;
    function addition(){
      //assign value to variable
      str=10;
    }
    function SecondAddtion(){
      //use the variable here
      var total = parseInt(str) +10;
      //show the output
      alert(total)
    }
  </script>
</head>
<body>
<input type="button" value="Addition" onclick="addition();"/>
  <input type="button" value="SecondAddtion"  onclick="SecondAddtion();"/>
</body>
</html>

Thanks!

davelewicki

Thanks!

Glad to be of help

Leave a Reply