Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda