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.
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>