Reputation: 1663
i have jquery script with operator minus, but i got wrong values, this is my code
var fuid = $(this).attr("data-delete-id");
var hargaProduk = parseInt($("#harga_"+fuid).text());
var hargaTotal = parseInt($("#total-harga").text());
var newValue = hargaTotal - hargaProduk;
$("#total-harga").html(newValue);
And this is my HTML Code
// foreach in here
<tr id="table_1">
<td>Data 1</td>
<td>Rp <span id="harga_1"> 275,000</span></td>
<td><span class="delete-product" data-delete-id="1"><span>Delete</span></span></td>
</tr>
<tr id="table_2">
<td>Data 2</td>
<td>Rp <span id="harga_2"> 175,000</span></td>
<td><span class="delete-product" data-delete-id="2"><span>Delete</span></span></td>
</tr>
<tr id="table_3">
<td>Data 3</td>
<td>Rp <span id="harga_3"> 180,000</span></td>
<td><span class="delete-product" data-delete-id="3"><span>Delete</span></span></td>
</tr>
//end foreach in here
<tr style="background:#DEDEDE;">
<td><b>Total </b></td>
<td></td>
<td><b>Rp <span id="total-harga"><?= number_format(CartTotal())?></span></b></td>
<td></td>
</tr>
When i run it, it displaying like this:
But when i click delete in number 3 and run JS script value change to Rp -179
Is there something wrong with my code? i just want to display value from variable hargaTotal - hargaProduk
Thankyou
Upvotes: 1
Views: 80
Reputation: 5443
it getting problem for comma(,).use this JavaScript code
var fuid = $(this).attr("data-delete-id");
var hargaProduk = parseInt( $("#harga_"+fuid).text().replace(/,/g, ""));
var hargaTotal = parseInt( $("#total-harga").text().replace(/,/g, ""));
var newValue = hargaTotal - hargaProduk;
$("#total-harga").html(newValue);
Upvotes: 0
Reputation: 1074148
JavaScript's parseInt
and parseFloat
stop at the first invalid character, and they don't support commas, so parseInt("180,000")
returns 180
. To parse your numbers, you'll need to remove the commas:
var hargaProduk = parseInt($("#harga_"+fuid).text().replace(/,/g, ""));
// ------------------------------------------------^^^^^^^^^^^^^^^^^^
...and then add them back when displaying; if you search, you'll find solutions for formatting numbers with thousands separators here on SO, such as this one.
Upvotes: 4