-4
<p class="item" data-price="2" data-qty="1">item 1</p>
<p class="item" data-price="12" data-qty="4">item 2</p>
<p class="item" data-price="4" data-qty="2">item 3</p>

how to sum the price and qty of above item using loop? I know how to get the value at times its quantity but how to loop over them?

parseInt($('.item').attr('data-price')) * $('.item').attr('data-qty')
Lee shienlong
  • 69
  • 1
  • 1
  • 6

2 Answers2

2

Iterate using jQuery.each and sum

var sum = 0;
$(".item").each(function(){
  sum += this.dataset.price * this.dataset.qty;
});

$("h2").html("Result: " + sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-price="2" data-qty="1" class="item">item 1</p>
<p data-price="12" data-qty="4" class="item">item 2</p>
<p data-price="4" data-qty="2" class="item">item 3</p>


<h2> </h2>
Anoop
  • 23,044
  • 10
  • 62
  • 76
0

Here is the correct way to call HTML 5 data attributes. Source: How to select the HTML5 data attribute in jQuery?

var sum = 0;
$("p.item").each(function(i){
    var items = "p.item:eq(" + i + ")";
    sum +=  parseInt($(items).data("price"), 10) * parseInt($(items).data("qty"), 10);
});

$("h3").text(sum);

DEMO

Community
  • 1
  • 1
Alexander Dixon
  • 837
  • 1
  • 9
  • 24