简体   繁体   中英

Javascript function works only once

I've got a function which should get all inputs from site, add their values multiplied by their amounts and then replace a string inside with the result. The problem is the function executes only once or sometimes it's never executed. Its code is:

function calcTotal() {
    var inputs = document.getElementsByTagName("input");
    var total = 0;

    var priceString = null;
    var e = null;
    var price = null;

    for (var i = 0; i < inputs.length; i++) {
        e = inputs[i].value;
        priceString = "hidden_" + inputs[i].name;
        if (e.match(/[0-9\.]/)) {
            var price = document.getElementById(priceString).innerHTML;
            total = total + parseFloat(e) * parseFloat(price);
        }

    }
    var totalString = document.getElementById("total");
    var stringToDisplay = total.toFixed(2);
    totalString.innerHTML = stringToDisplay.toString();
}

The function should replace this span: <span id="total">0.00</span>

The function is called on each input's change by code:

<?php foreach($allPremium as $premiumItem){?>
<?php $ceny[$premiumItem->type]=$premiumItem->price;?>
<div class="premium-pack-item">
<?php echo $premiumItem->name;?>
<br />
<?php echo $premiumItem->description;?>
<br />
<?php echo "&euro; ".number_format($premiumItem->price, 2);?>
<br />
<span id="hidden_amount_<?php echo $premiumItem->type;?>" style="display:none"><?php echo $premiumItem->price;?></span>
<input onkeypress="calcTotal()" type="number" size=1 name="amount_<?php echo $premiumItem->type;?>">
</div>
<?php }?>

Could you explain me where I made a mistake?

我首先会检查你是否使用开发人员工具获得任何javascript错误,这可能会揭示真正的原因。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM