Reputation: 5
I am trying to make a simple counter that allows the user to input a number and press a button which will then minus their number from 100 until the counter gets to 0. this is the HTML and JavaScript code:
HTML:
<div class="box">
<label for="qty"><abbr title="Quantity">Qty</abbr></label>
<input id="qty" type="number" max="100" />
<button id="down" onclick="modify_qty(-qty)">Book</button>
</div>
JavaScript:
function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty,10) + val;
if (new_qty == -1) {
new_qty = 0;
alert("Sorry Tickets Have Now Sold Out");
}
document.getElementById('qty').value = new_qty;
return new_qty;
}
The problem is when the user inputs a number and presses the button, the number disappears. For example: the max is 100, if I enter 10, it should return 90. But it is returning nothing at all.
Upvotes: 0
Views: 1624
Reputation: 4050
I added another label to track the remaining tickets instead of putting the amount left in the input.
Using a ticketsLeft
variable in the javascript helps to keep track of tickets without relying on our html to hold values for us.
Javascript
var ticketsLeft = 100;
var qty = document.getElementById('qty');
var remaining = document.getElementById('remaining');
remaining.innerHTML = ticketsLeft;
function modify_qty() {
var new_qty = ticketsLeft - parseInt(qty.value, 10);
if (new_qty < 0) {
ticketsLeft = 0;
remaining.innerHTML = 0;
alert("Sorry Tickets Have Now Sold Out");
return;
}
ticketsLeft = new_qty;
remaining.innerHTML = new_qty;
return new_qty;
}
HTML
<div class="box">
<label for="qty"><abbr title="Quantity">Qty</abbr></label>
<input id="qty" type="number" max="100" />
<button id="down" onclick="modify_qty()">Book</button>
<label>Tickets Remaining: <label id="remaining"></label></label>
</div>
Upvotes: 1