user2931494 user2931494 - 3 months ago 6
jQuery Question

Calculate data attributes and output into HTML

I want to calculate all

<select>
data attributes and output the total into a
<span>
.

Here are the selects:

<select name="product-1" id="product-1">
<option value="0" data-price="0">0 (0.00$)</option>
<option value="10" data-price="52.39">10 (52.39$)</option>
<option value="20" data-price="61.93">20 (61.93$)</option>
</select>
<select name="product-2" id="product-2">
<option value="0" data-price="0">0 (0.00$)</option>
<option value="10" data-price="57.92">10 (57.92$)</option>
<option value="20" data-price="77.81">20 (77.81$)</option>
</select>
<select name="product-3" id="product-3">
<option value="0" data-price="0">0 (0.00$)</option>
<option value="10" data-price="64.63">10 (64.63$)</option>
<option value="20" data-price="84.07">20 (84.07$)</option>
</select>


Here is the span:

<span id="total">4.99</span>


Here is the jQuery:

$(document).ready(function() {
delivery = 4.99, $("select").change(function() {
total = $(this).find("option:selected").data("price") + delivery, $("#total").html(total.toFixed(2))
})
});


The problem:
I can't figure it out, how to sum all of the
<select>
attributes into one total. With my current code, it only output's the last changed option.

Answer

The easiest way to do this is to loop through the selected options of each select when a value is changed and keep a running total of the selected prices. Try this:

$(document).ready(function() {
  var delivery = 4.99;

  $("select").change(function() {
    var total = delivery;
    $('select option:selected').each(function() {
      total += parseFloat($(this).data('price'));
    });
    $("#total").html(total.toFixed(2))
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="product-1" id="product-1">
  <option value="0" data-price="0">0 (0.00$)</option>
  <option value="10" data-price="52.39">10 (52.39$)</option>
  <option value="20" data-price="61.93">20 (61.93$)</option>
</select>
<select name="product-2" id="product-2">
  <option value="0" data-price="0">0 (0.00$)</option>
  <option value="10" data-price="57.92">10 (57.92$)</option>
  <option value="20" data-price="77.81">20 (77.81$)</option>
</select>
<select name="product-3" id="product-3">
  <option value="0" data-price="0">0 (0.00$)</option>
  <option value="10" data-price="64.63">10 (64.63$)</option>
  <option value="20" data-price="84.07">20 (84.07$)</option>
</select>


<span id="total">4.99</span>