简体   繁体   中英

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:

<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

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. 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.

Any help is greatly appeciated.

You can use getElementsByClassName() instead of getElementById() and deal with each element.

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

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