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>

1
  • Make it global, pass it, ... Commented Sep 13, 2017 at 17:07

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.