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

251
Views
How to change the Value of Variables while displaying them in Javascript?

I'm very new to Javascript and want to build a vending machine for my first Project. I have the problem that I want to make it so that if the right amount is paid, there is an alert saying 'You have paid for your item', but currently it's not working when the display reaches 0. I think it's because the variable amount isn't changed and instead it just displays a different number. How do I get it to actually alert when I have inserted the right amount of 1 cent coins. I tried to google my problem but I don't even know how exactly to describe it.

var item1 =  100;
var ct1 = 1;

function showPrice1()
    {
        document.getElementById("display").innerHTML = item1;
}

function insert1cent()
    {
        document.getElementById("display").innerHTML = item1 -= ct1;
    }

if (item1 == 0) 
    {
        alert('You have paid for your item');
    }

and this is the HTML:

<body>
     <div id="display">
     </div>
     <button id="button1" type="button" onclick="showPrice1()">
         1
     </button>
     <button id="ct1" type="button" onclick="insert1cent()">
        1ct
    </button>
</body>

Thank you in Advance for your help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The if statement should be inside your function to check on every click and it should return false to avoid decrementing once your counter reaches 0. As demonstrated in the fiddle.

var item1 = 10;
var ct1 = 1;

function showPrice1() {
  document.getElementById("display").innerHTML = item1;
}

function insert1cent() {
  if (item1 == 0) {
    alert('You have paid for your item');
    return false;
  }

  item1 -= ct1;

  document.getElementById("display").innerHTML = item1;
}
<div id="display">
</div>
<button id="button1" type="button" onclick="showPrice1()">
       1
</button>
<button id="ct1" type="button" onclick="insert1cent()">
       1ct
</button>

about 4 years ago · Juan Pablo Isaza 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!