Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda