0

So basically, I pass in a value as an argument into a function, and then I want to use the same value in another function by storing that argument as a variable. The problem is that if I define the variable inside the first function, it can only be accessed within that function. What do I do? Here is my code:

<html>
  <body>
    <script>
        function showUser(selection) {
          var selectedOption = selection;//THIS IS THE VARIABLE I WANT TO ACCESS IN ANOTHER FUNCTION
          //Some code
        }
        function saveTime(solvedTime) {
//This is where I am using the variable
xmlhttp.open("GET","savetimes.php?q="+selectedOption+"&time="+solvedTime, true);
            xmlhttp.send();
          }
    </script>
    <form id="session">
     <select name="sessions" onchange="showUser(this.value)">
       <option value="1">Session 1</option>
       <option value="2">Session 2</option>
     </select>
   </form>
      <br>
   <div id="timesList">
   </div>
  </body>
</html>
aravk33
  • 469
  • 2
  • 10
  • 18

1 Answers1

3

Declare your variable outside the function. It will be accessible all functions in that scope. To not mutate this object with the global scope, you can wrap it with IIFE. Use addEventListener to handle the event, this is a more preferable approach to handle events. Also check in the saveTime if any value was selected or not before the request.

(function() {

   const sessions = document.getElementById('sessions');
   let selectedOption;
   
   sessions.addEventListener('change', function() {
      selectedOption = this.value;
      console.log(selectedOption);
   });  
   
   function saveTime(solvedTime) {
      if(selectedOption) {
         xmlhttp.open("GET","savetimes.php?q="+selectedOption+"&time="+solvedTime, true);
         xmlhttp.send();
      }
   }
  
})();
<html>
  <body>
    <form id="session">
 <select id="sessions" name="sessions">
     <option value="1">Session 1</option>
     <option value="2">Session 2</option>
 </select>
    </form>
    <br>
    <div id="timesList"></div>
  </body>
</html>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112