Matias
Matias

Reputation: 81

Jquery and XML - How to add the value of nodes

This may be a simple question though can´t figure out how to do it.

I am parsing an XML with Jquery Ajax. It contains dates and rates

The XML looks something like

<rate>
 <date>Today</date>
 <price>66</price>
</rate> 
<rate>
 <date>Tomorrow</date>
 <price>99</price>
</rate> 

I simply want to figure out how to calculate the total price of both days Today and Tomorrow. Thought that by using Javascript Number it will simply return the total value of the nodes..

$(xml).find("rate").each(function()
{
   $(this).find("price").each(function()
   {
   $("#TOTALPRICE").append(Number($(this).text()));
   }

}
//output is: 6699 

However, it´s just concatenating the values both not adding them.

//output is: 6699 

I greatly appreciate your help !!

Thanks

Upvotes: 1

Views: 748

Answers (4)

Matias
Matias

Reputation: 81

Got it guys !!! I Just define the Var inside the "each". That overwrite the value of the variable on each loop:

$(xml).find("rate").each(function()
{
   var myTotal = 0;
   $(this).find("price").each(function()
   {
     mytotal = mytotal  + Number($(this).text());     
   }

}

$("#TOTALPRICE"). append(myTotal);

Thanks very much, this site ABSOLUTELY ROCKS !!!

Upvotes: 0

rosscj2533
rosscj2533

Reputation: 9323

jQuery's append will insert content to the end of each element matched by the selector. That means when you are appending '66', that will be added to the element. You need to track the total as Avitus describes, then you probably want to use jQuery's text function to set the content of TOTALPRICE, like this:

$("#TOTALPRICE").text(myTotal); 

Upvotes: 0

justkt
justkt

Reputation: 14766

The append doesn't do addition, it will simply add the text. If #TOTALPRICE only contains the total, you can do the following:

$(xml).find("rate").each(function()
{
   $(this).find("price").each(function()
   {
      var current = parseInt($("#TOTALPRICE"));
      current += parseInt($(this).text());
      $("#TOTALPRICE").html(current);
   }
}

If #TOTALPRICE needs the content appended to the end because it contains other content, then the solution posted by Avitus should work for you.

Upvotes: 0

Avitus
Avitus

Reputation: 15958

if you just used a javascript variable in the middle it would get you your desired result.

var myTotal = 0;
    $(xml).find("rate").each(function()
    {
       $(this).find("price").each(function()
       {
         mytotal = mytotal  + Number($(this).text());     
       }

    }
  $("#TOTALPRICE"). append(myTotal);

Upvotes: 1

Related Questions