jeudi 3 mars 2016

Adding up total price of selected items (Javascript)

I ran into a problem. Code is here:

// JavaScript Document

window.totalIt= function() {
  var input = document.getElementsByName("product");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += 1;
    }
  }
  if(total>=3){
    document.getElementById("total").value = "$" + (total*29).toFixed(2);
  }
  else{
    document.getElementById("total").value = "$" + (total*39).toFixed(2);
  }
}

window.totalPrisDessert= function() {
  var input = document.getElementsByName("dessert");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseFloat(input[i].value);
    }
  }
  document.getElementById("total").value = "$" + total.toFixed(2);
}
<div id="formular">
  <div id="formulartekst">
    <form>

      <h2 class="formskrift">Order Hot Food</h2>
      <p class="kroner">$39 / $29 when 3 or more checked</p>
      <input name="product" value="39" type="checkbox" id="p1" onclick="totalIt()" /> Monday
      <br>
      <input name="product" value="39" type="checkbox" id="p2" onclick="totalIt()" /> Tuesday
      <br>
      <input name="product" value="39" type="checkbox" id="p3" onclick="totalIt()" /> Wednesday
      <br>
      <input name="product" value="39" type="checkbox" id="p4" onclick="totalIt()" /> Thursday
      <br>
      <input name="product" value="39" type="checkbox" id="p5" onclick="totalIt()" /> Friday

      <h2 class="formskrift">Dessert</h2>
      <p class="kroner">$20 ALWAYS</p>
      <input name="dessert" value="20" type="checkbox" id="p6" onclick="totalPrisDessert()"/>
      Monday<br>
      <input name="dessert" value="20" type="checkbox" id="p7" onclick="totalPrisDessert()"/>
      Tuesday<br>
      <input name="dessert" value="20" type="checkbox" id="p8" onclick="totalPrisDessert()"/>
      Wednesday<br>
      <input name="dessert" value="20" type="checkbox" id="p9" onclick="totalPrisDessert()"/>
      Thursday<br>
      <input name="dessert" value="20" type="checkbox" id="p10" onclick="totalPrisDessert()"/>
      Friday<br>

      <label>
        <br> Total
        <input value="$0.00" readonly type="text" id="total" />
      </label>
      <input type="submit" value="Order">
    </form>
  </div>
</div>

http://ift.tt/1VSrF1j

When I check the top 5 boxes they add the price in the total box. However if I check any of the below 5 boxes (desserts) the price overwrites. I need the total price showing, but right now they are acting as two different.

Thank you




Aucun commentaire:

Enregistrer un commentaire