JS和HTML中的简单计数器

时间:2016-04-12 15:07:04

标签: javascript html

我正在尝试创建一个简单的计数器,允许用户输入一个数字,然后按一个按钮,然后从100减去它们的数字,直到计数器变为0.这是HTML和JavaScript代码:

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;
    }

问题是当用户输入数字并按下按钮时,数字消失。例如:最大值为100,如果我输入10,则应返回90.但它根本不返回任何内容。

1 个答案:

答案 0 :(得分:1)

我添加了另一个标签来跟踪剩余的票证,而不是将金额留在输入中。

在javascript中使用ticketsLeft变量有助于跟踪故障单,而无需依赖我们的html来保存我们的值。

Fiddle

<强>的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>