Zac
Zac

Reputation: 12836

How sum totals of variable generated from ajax request

If I am parsing an xml file with something like :

 $.ajax({
    type: "GET",
    url: "file.xml",
    dataType: "xml",
    success:   function  parseXml(data)
    {
      $(data).find("ITEM").each(function()
        {
            var quant=$("QTY", this).text();
        };
     };
});

How would I sum the total of everything that is returned in QTY?

Upvotes: 0

Views: 5983

Answers (4)

ezmilhouse
ezmilhouse

Reputation: 9121

be aware of js rounding problems when adding up floats in js:

$.ajax({
    type: "GET",
    url: "file.xml",
    dataType: "xml",
    success: function(data) {
       var total = 0;
       $(data).find("ITEM").each(function() {
          var quant = parseFloat($("QTY", this).text());
          // you might run into rounding problems when adding
          // floats in js, workaround gets right results 
          total = ( ( total * 100 )+( quant * 100 ) ) / 100;
       });
    };
});

Upvotes: 1

Kevin Peno
Kevin Peno

Reputation: 9196

Get it, add it. Optimized for efficiency using context.

$.get(
    "xml.xml",
    {},
    function( data )
    {
        var total = 0;

        $( "ITEM > QTY", data ).each(
            function()
            {
                var num = parseInt( $(this).text() );

                if( !isNaN(num) )
                    total += num;
            }
        );
    },
    "xml"
);

Upvotes: 0

no.good.at.coding
no.good.at.coding

Reputation: 20371

success:   function parseXml(data){
                var sum = 0;
                $(data).find("ITEM").each(function() {
                    var quant=$("QTY", this).text();
                    sum += parseFloat(quant); //or parseInt() if you're sure you'll only have or only care about integral values
                };
                //at this point sum holds the sum of all QTY values
                console.log("The sum is ", sum);
            };

Upvotes: 0

CrazyDart
CrazyDart

Reputation: 3801

try this:

$.ajax({
    type: "GET",
    url: "file.xml",
    dataType: "xml",
    success:   function  parseXml(data)
    {
      var total = 0;
      $(data).find("ITEM").each(function()
        {
            var quant=$("QTY", this).text();
            if(quant != null && quant != "")
                total += parseInt(quant);
        };
     };
});

Upvotes: 0

Related Questions