[英]Calculate Total using javascript
I made a from in HTML using some input fields where the user can type a number and the price will automatically update according to the number being put in: 我在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>
And the piece of JS code 还有一段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);
Now i have 11 fields like those those are all working just fine but now i'd like to make a Total price. 现在我有11个像这样的字段,它们都工作得很好,但是现在我想定一个Total价格。 So one that counts all those prices together and puts them in
因此,将所有这些价格加在一起并将其计入
<td><h3>Totale Prijs</h3></td>
<td></td>
<td><span id="TotalPrice"></span></td>
But since im not experienced at all in JS i have alot of trouble accomplishing this. 但是由于我根本没有使用过JS的经验,因此在实现此目标方面存在很多麻烦。
Any help is greatly appeciated. 非常感谢任何帮助。
You can use getElementsByClassName()
instead of getElementById()
and deal with each element. 您可以使用
getElementsByClassName()
代替getElementById()
并处理每个元素。
Maybe the following does not fit exactly what you need but you will probably adapt it easily 以下内容可能无法完全满足您的需求,但您可能会轻松适应
// 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.