[英]Calculate Total using javascript
我在HTML中使用了一些輸入字段,使用這些輸入字段,用戶可以在其中輸入數字,價格會根據輸入的數字自動更新:
<td>Pizza Margherita</td>
<td><input type="number" id="countMargherita" class="orderform" name="PizzaMargherita" onkeyup="validateForm(this)" min="1"></td>
<td><span id="totalMargherita"></span></td>
還有一段JS代碼
var priceMagarita = 7;
var numPizzaMargheritaInput = document.getElementById('countMargherita');
var priceMargheritaLabel = document.getElementById('totalMargherita');
function onNumPizzaMargheritaInputChange(e){
var totalMargherita = priceMargherita * parseInt(e.target.value);
var formattedPrice = '\u20ac '+totalMargherita.toFixed(2);
priceMMargheritaLabel.innerHTML = '';
priceMargheritaLabel.appendChild(document.createTextNode(formattedPrice));
}
numPizzaMargheritaInput.addEventListener('change', onNumPizzaMargheritaInputChange, false);
現在我有11個像這樣的字段,它們都工作得很好,但是現在我想定一個Total價格。 因此,將所有這些價格加在一起並將其計入
<td><h3>Totale Prijs</h3></td>
<td></td>
<td><span id="TotalPrice"></span></td>
但是由於我根本沒有使用過JS的經驗,因此在實現此目標方面存在很多麻煩。
非常感謝任何幫助。
您可以使用getElementsByClassName()
代替getElementById()
並處理每個元素。
以下內容可能無法完全滿足您的需求,但您可能會輕松適應
// create a price object with all pizzas prices
var prices = {
PizzaMargherita : 7,
PizzaHawai : 42
}
// get all inputs which contains number of pizzas.
// Maybe you will add something else than "order form"
function recalculate()
{
var all_inputs = document.getElementsByClassName('orderform');
var total = 0;
for(i=0;i<all_inputs.length;i++)
{
var that_input = all_inputs[i]
var subtotal = parseInt(that_input.value * prices[that_input.name]);
total += subtotal
document.getElementById('totalMargherita').innerHTML = subtotal;
}
document.getElementById('totalPrice').innerHTML = total;
}
// add your listener in each inputs
var all_inputs = document.getElementsByClassName('orderform');
for(i=0;i<all_inputs.length;i++)
all_inputs[i].addEventListener('change',function(e){recalculate(); }, false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.