androidnation
androidnation

Reputation: 636

jQuery unwanted sum result

I have a table head <th> that is set by default to 0:

<th id="total_price" style="text-align:center">0</th>

Now when, I add a new sold item, the price should be added to the value of the this <th>. So, if the new one is 20000, the value should be 20000+0=20000 and not 200000. And if I add another item, with price of 30 000 it would be now like 20000030 000.

This is jquery script:

        var initial = $("#total_price").text();
        console.log(initial);
        var newPrice = initial + (res['price']);
        console.log(newPrice);
        $("#total_price").text(newPrice);

I tried this:

        var initial = $("#total_price").text();
        console.log(initial);
        var newPrice = initial + +(res['price']);
        console.log(newPrice);
        $("#total_price").text(newPrice);

But still the same.

enter image description here

Upvotes: 0

Views: 42

Answers (2)

Rajesh
Rajesh

Reputation: 24915

As I have already commented, when you read text from DOM elements, it is read as string and when you apply + operator to it, its is treated as concatenation and adddition.

Following is a simulation:

(function(){
  var th = $("th");
  var result = "";
  
  result += "Direct addition: " + $(th[0]).text() + $(th[1]).text() + "<br/>";
  result += "Type: " + typeof($(th[0]).text()) + "<br/>";
  result += "Parse Int: " + (parseInt($(th[0]).text()) + parseInt($(th[1]).text())) + "<br/>";
  $("#result").html(result);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
  <tr>
    <th>20000</th>
    <th>0</th>
  </tr>
</table>
<p id="result"></p>

Also do refer following post: parseInt vs unary plus

Upvotes: 1

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

You need to parse the text (string) into a integer and then add it up. So do below for your calculations

 var newPrice = parseInt(initial,10) + parseInt(res['price'],10);

Or else what you are trying would be a string concatenation and not a Sum

You can get More info Here

Upvotes: 4

Related Questions