开发者

Jquery and XML - How to add the value of nodes

开发者 https://www.devze.com 2022-12-25 06:36 出处:网络
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

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()));
   }

}
/开发者_JAVA百科/output is: 6699 

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

//output is: 6699 

I greatly appreciate your help !!

Thanks


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);


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.


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); 


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 !!!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号