Home JS - store a function's arguement in a variable to use in another function
Reply: 1

JS - store a function's arguement in a variable to use in another function

Cubetastic
1#
Cubetastic Published in 2017-09-13 17:05:36Z

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>

Suren Srapyan
2#
Suren Srapyan Reply to 2017-09-13 17:19:03Z

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>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.267914 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO