Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
How do I make variables change outside functions in javascript?

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> 

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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.

about 4 years ago · Santiago Gelvez Report

0

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

about 4 years ago · Santiago Gelvez Report

0

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.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!