Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum array value in ajax

I have this array:

shipPrice: [["17.50"], ["7.00"]]
shippingFrom : ["SARAWAK", "KUALA LUMPUR"]

I complete the simple looping function and appear in html view.

I have tried :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const data = {
  countTotal: 2,
  shipPrice: [
    ["17.50"],
    ["7.00"]
  ],
  shippingFrom: ["SARAWAK", "KUALA LUMPUR"]
}
var totalShipping = 0;
for (var i = 0; i < data.countTotal; i++) {
  $("#ShippingFromJson").append('<li id="ShippingFromJson">' + data.shippingFrom[i] + '<span id="ShippingPriceJson">RM ' + data.shipPrice[i] + '</span></li>');
  totalShipping += data.shipPrice[i];
}
$("#isTotal").html(totalShipping);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<ul id="ShippingFromJson"></ul>
<span id="isTotal"></span>

Output is
017.507.00

It should be 24.5

Help please

>Solution :

Since your shipPrice is array of string it will concat the data and not perform arithmetic operation with +. For this parseFloat() can solve your problem. See the following example.

var data = {
  "countTotal": 2,
  "shipPrice": [
    ["17.50"],
    ["7.00"]
  ],
  "shippingFrom": ["SARAWAK", "KUALA LUMPUR"]
};


var totalShipping = 0;

for (var i = 0; i < data.countTotal; i++) {

  $("#ShippingFromJson").append('<li id="ShippingFromJson">' + data.shippingFrom[i] + '<span id="ShippingPriceJson">RM ' + data.shipPrice[i] + '</span></li>');


  totalShipping += parseFloat(data.shipPrice[i]);

}
$("#isTotal").html(totalShipping);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="ShippingFromJson"></ul>
<div id="isTotal"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading