簡體   English   中英

如何在JavaScript中從多個表單輸入值中找到數字總和?

[英]How do I find the sum of numbers from multiple form input values in JavaScript?

我有5個輸入包含價格。 第六個輸入將通過將前五個輸入的價格加在一起來顯示總價格。

function calculateTotal(){

    var priceInputs = document.querySelectorAll("input[name^='tPriceInput']");
    var totalPrice = 0;

    for(var i = 0; i < priceInputs.length; i++){

        totalPrice = totalPrice + parseInt(priceInputs[i].value);

    }

    return totalPrice;

}

上面的函數始終返回NaN ...為什么不起作用? 我也嘗試過不使用parseInt方法,但是只會將字符串加在一起。

沒有足夠的信息,但我想您已經說過您使用逗號,價格中用逗號代替點號. ,但JavaScript需要點。 對於非英語區域設置,這是一個常見問題。

如果是這樣,請嘗試以下操作:

totalPrice = totalPrice + parseInt(priceInputs[i].value.replace(",", "."));

更改

var priceInputs = document.querySelectorAll("input[name^='tPriceInput']");

var priceInputs = document.querySelectorAll("input[name='tPriceInput']");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM