Home > Back-end >  How do I make variables change outside functions in javascript?
How do I make variables change outside functions in javascript?

Time:07-16

I am a beginner with Javascript/programming and I am trying to make the "demo2" id change with the 5, 10 or 15 variable chosen in the functions (trigger by the buttons), but it keeps showing "0". What do I have to do?

    <!DOCTYPE html>
    <html>
    
    <body>
      <button onclick="alternative1()">5</button>
        <button onclick="alternative2()">10</button>
          <button onclick="alternative3()">15</button>
          
          <p id="demo"></p>
          <p id="demo2"></p>
    
      <script>
       
       var x = 0;
       var y = 0;
      
    
        function alternative1() {y = x   5;
          
    document.getElementById("demo").innerHTML = "You have chosen "   y;
        } 
        
        
        function alternative2() {y = x   10;
    document.getElementById("demo").innerHTML = "You have chosen "  y;
        }
        
        
        function alternative3() {y = x   15;
          
    document.getElementById("demo").innerHTML = "You have chosen "  y;
        }
        
        document.getElementById("demo2").innerHTML = y;
        
      </script>
    </body>
    </html> 

CodePudding user response:

You can’t access variables declared inside a function from outside a function. The variable belongs to the function’s scope only, not the global scope.

CodePudding user response:

You don't need 3 functions for this. You can do it with 1.

<!DOCTYPE html>
<html>

<body>
  <button onclick="alternative(this)">5</button>
    <button onclick="alternative(this)">10</button>
      <button onclick="alternative(this)">15</button>
      
      <p id="demo"></p>

  <script>
   
    function alternative(obj) {          
document.getElementById("demo").innerHTML = "You have chosen "   obj.innerHTML;
    }
  </script>
</body>
</html> 

Happy learning

CodePudding user response:

It is normal that there is zero because in 'y' there is zero and no operation performed on y.

I hope that this answer will help you to understand what you have done.

  • Related