0

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

androidnation
  • 556
  • 1
  • 4
  • 17
  • You have to use `parseInt()`. `+` operator is used for addition and for concatenation of strings. Also, when you read text of DOM element, it is read as string and not number – Rajesh Mar 26 '16 at 15:00
  • 1
    You had a correct solution but forgot to put the `+` behind the `initial` since that's a string too. `+initial + +(res['price']);` –  Mar 26 '16 at 15:05
  • If you want decimals, you should probably do a parseFloat instead. Also, if you want something like "30 000" or "30,000" to be recognized as 30000, you will have to get rid of them first. Do something like `res['price'].replace(/[ ,]/g,'')` – David784 Mar 26 '16 at 15:06
  • 1
    Thanks all. I appreciate it. Now it is working with both solution given by a comment from @squint and the answer of Reddy – androidnation Mar 26 '16 at 15:08

2 Answers2

4

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

Rajshekar Reddy
  • 17,202
  • 3
  • 34
  • 54
1

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

Community
  • 1
  • 1
Rajesh
  • 21,405
  • 5
  • 35
  • 66