1
votes

I need somehow to sum up the text values from the span, but I only can extract them and not to sum up. Is there a way to do this correctly? I got blocked about the code, I'm new to jQuery.

Demo: http://jsfiddle.net/0L4s6g8p/1/

Html:

<div class="prices"> 

    <h3>Option 1 = $<span class="sum" id="option-1">11.11</span></h3>
    <h3>Option 2 = $<span class="sum" id="option-2">22.22</span></h3>
    <h3>Option 3 = $<span class="sum" id="option-3">33.33</span></h3>

</div>

<h3>Subtotal = $<span id="subtotal">0.00</span></h3>

Script:

$('.prices').each(function(){
      var sum = $('.sum').text();
      $(this).each(function(){
        sum += parseInt($('.sum').text());
      });
      $("#subtotal").text(sum);
    });
3

3 Answers

5
votes

You need to iterate over each sum element and add it up

var sum = 0;
$('.sum').each(function() {
  sum += +$(this).text()||0;
});
$("#subtotal").text(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="prices">

  <h3>Option 1 = $<span class="sum" id="option-1">11.11</span></h3>
  <h3>Option 2 = $<span class="sum" id="option-2">22.22</span></h3>
  <h3>Option 3 = $<span class="sum" id="option-3">33.33</span></h3>

</div>

<h3>Subtotal = $<span id="subtotal">0.00</span></h3>
2
votes

Its very simple! Use below code :

var total = 0;
$('.prices .sum').each(function(){
      total += parseInt($(this).text());
      $("#subtotal").text(total);
});
0
votes

You just made a couple easy errors:

  1. You should include the calculating script inside the subtotal function or it only gets called at loading and never again.

  2. You're missing a parseInt at the first assignation of sum. As it is, sum is a string and only gets concatenations. However, it is a wrong start, you're adding one value twice.

Here's the corrected script:

var flyersprice = '0.00';

function subtotal(){

    var price = $("#quantity option:selected").attr("data-price");

    flyersprice = $("#quantity option:selected").val() * price;

    $("#flyers").text(flyersprice.toFixed(2));

    $(".paper li").click(function(){
        var selected = $(this).data("price") * $("#quantity option:selected").val();
        $("#papertype").text(selected.toFixed(2));
    });

    $("input[type=radio]").click(function(){
        var extra = $(this).data("price");
        $("#extraoptions").text(extra);
    });
    $('.prices').each(function(){
      var sum = 0.0;
      $(this).each(function(){
        sum += parseInt($('.sum').text());
      });
      $("#subtotal").text(sum);
    });
 }

You should also take out the "onchange" attributes from the html and add to the script:

$('input').change(subtotal);
$('select').change(subtotal);

It is not wrong but it is better to separate script and html.