This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 8 months ago.
I have a table with 4 columns. The first one is the name of a product, the second has the price per item, the third column has an input field where you can choose how many items you want, and the last column calculates the price per item * number of items.
This calculation works, but I also want to calculate all of these into a total at the bottom of the table.
I know very little javascript, so I'm not sure if I'm using the correct functions or methods.
The code consists of PHP, HTML and Javascript.
for ($i = 0; $i < $num_rows; $i++){
echo '<tr><td>' . $row[$i][0] . '';
echo '<td id="stkPris_' . $i . '">' . $row[$i][1] . '</td>';
echo '<td><input type="text" id="antall_' . $i .'" name="antall" size="1" value="0" oninput="calculate(value, this.id)"></td>';
echo '<td><input type="text" id="pris_' . $i . '" name="pris" size="1" readonly></td></tr>';
}
echo '
<tr>
<td><strong>Sum</strong></td>
<td></td>
<td></td>
<td><strong><input type="text" id= "sum" name="sum" size="1" value="0" readonly><strong></td>
</tr>
</table>';
<script>
function calculate(value, elementId){
var i;
for (i = 0; i < ' . $num_rows . '; i++){
var stkPris = document.getElementById("stkPris_" + i);
var antall = document.getElementById("antall_" + i);
var pris = document.getElementById("pris_" + i);
var sum = document.getElementById("sum");
var delsummer = antall.value * stkPris.innerText;
if(elementId == "antall_" + i){
pris.value = delsummer;
}
sum.value += pris.value;
}
}
</script>
How it looks (image)
The total seem to be a string and not a number? I have tried putting the "price per item" into an input instead and use .value instead of .innerText. Didn't do anything.
Here is a simple way to calculate stock and price, read code comments to know more.
$(document).ready(function(){
var totalStock = 0;
var totalPrice = 0;
$(".stock").each(function(){
var s = parseInt($(this).text()); // to get the stock count
var p = parseFloat($(this).parent().find(".price").text()); // to get unit price of this stock
$(this).parent().find(".sumPrice").html(s*p); // calculate Stock x Price
totalStock += s; // calculate total Stocks
});
$(".price").each(function(){
var p = parseFloat($(this).text()); // to get unit price
totalPrice += p; // calculate total prices
});
$(".stockTotal").html(totalStock); // show total stock count
$(".priceTotal").html(totalPrice); // show total prices
$(".generalTotal").html(totalStock * totalPrice); // calculate all prices x all stock
});
table{
width:100%;
}
table th, table td{
border:1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>Stock</th>
<th>Price</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>item name</td>
<td class="stock">25</td>
<td class="price">17</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>2</td>
<td>item name</td>
<td class="stock">1</td>
<td class="price">12.5</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>3</td>
<td>item name</td>
<td class="stock">6</td>
<td class="price">9.75</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>4</td>
<td>item name</td>
<td class="stock">0</td>
<td class="price">20</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>5</td>
<td>item name</td>
<td class="stock">11</td>
<td class="price">15</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>6</td>
<td>item name</td>
<td class="stock">3</td>
<td class="price">3.25</td>
<td class="sumPrice">##</td>
<tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"></td>
<td class="stockTotal">#stock total#</td>
<td class="priceTotal">#price total#</td>
<td class="generalTotal">#price total x stock total#</td>
</tr>
</tfoot>
</table>
Related
so i am using jQuery in a crud system where there is an input for quantity that multiplies the price stored in the database and then outputs it in the field next to it but it is outputting it in all the fields next to the input i tried everything but i am unable to do it, any one who can tell me whats wrong with my code,
heres the real output
and this is the result i want
this is my view file
<?php
$i=1;
?>
#foreach ($productData as $rsproductData)
<tr>
<td><?php echo $i ?></td>
<?php
$i++;
?>
<td class="d-none">{{$rsproductData->id}}</td>
<td>{{$rsproductData->products}}</td>
<td>{{$rsproductData->wholesale}}</td>
<td>{{$rsproductData->price}}</td>
<td><input type="number" class="form-control qtyChckInput mb-2" name="qty"></td>
<td class="totalPrice" name="totalPrice">0</td>
<td><button class="btn btn-success editModalBtn">Edit</button></td>
<td><button class="btn btn-danger deleteModalBtn">Delete</button></td>
</tr>
#endforeach
<tfoot>
<tr>
<td></td><td></td><td></td><td></td>
<th>Item Total</th>
<td id="itemTotal">0</td>
<td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<th>10% discount on Item Total</th>
<td id="itemDiscount">0</td>
<td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<th>5% Tax on Item Total</th>
<td id="itemTax">0</td>
<td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<th>Grand Total</th>
<td id="itemGrand">0</td>
<td></td><td></td>
</tr>
</tfoot>
</tbody>
this is my js file
$('input[name*="qty"]').keyup(function()
{
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function () {
return $(this).text();
}).get();
text = $(this).val();
$(".totalPrice").html(data[4] * text)
var itemTotal = $('.totalPrice').html();
$('#itemTotal').html(itemTotal);
var itemDiscount = itemTotal * (1 - 10 / 100);
$('#itemDiscount').html(itemTotal - itemDiscount);
var itemTax = itemTotal * (1 - 5 / 100);
$('#itemTax').html(itemTotal - itemTax);
var itemGrand = itemTax + itemDiscount - itemTotal;
console.log(itemGrand);
$('#itemGrand').html(itemGrand);
});
Try using dynamic id/class for your HTML entities, below is a short calculation for your reference.
<tr>
<td id="products_{{ $rsproductData->id }}">{{$rsproductData->products}}</td>
<td id="wholesale_{{ $rsproductData->id }}">{{$rsproductData->wholesale}}</td>
<td id="price_{{ $rsproductData->id }}" value="{{$rsproductData->price}}">{{$rsproductData->price}}</td>
<td><input type="number" class="form-control qtyChckInput mb-2" data-product="{{ $rsproductData->product }}" name="qty"></td>
</tr>
<script>
$('input[name*="qty"]').keyup(function()
{
var id = $(this).data('product');
var price = $("#price_"+id).val();
var quantity = $(this).val();
// Short calucalation for example
$('#itemGrand').html(price*quantity);
});
</script>
I have the following table:
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
I need a way to add/sum all values grouped by category, ie: add/sum all values in cat1, then add/sum all values in cat2. For each group I will do something with the total.
So I was hoping for something like:
for each unique category:
sum values in category
do something with this category total
For cat1 the total would be 123 + 486. Cat2 would just be 356. And so on if there were more categories.
I would prefer a purely javascript solution, but JQuery will do if that's not possible.
If I understand you correctly, you do a repeat of each td:first-child (The category cell).
Create a total object. You can check if the category is exist in it for each cell. If so, add current value to the stored value. If not, insert new property to it.
Like this:
var total = {};
[].forEach.call(document.querySelectorAll('td:first-child'), function(td) {
var cat = td.getAttribute('class'),
val = parseInt(td.nextElementSibling.innerHTML);
if (total[cat]) {
total[cat] += val;
}
else {
total[cat] = val;
}
});
console.log(total);
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
Here's a simple approach using only javascript
//grab data
var allTR = document.getElementsByTagName('TR');
var result = {};
//cycle table rows
for(var i=0;i<allTR.length;i+2){
//read class and value object data
var class = allTR[i].getAttribute('class');
var value = allTR[i+1].innerText;
//check if exists and add, or just add
if(result[class])
result[class] += parseInt(value);
else
result[class] = parseInt(value);
}
You have to use getElementsByTagName("td"); to get all the <td> collection and then you need to loop through them to fetch their innerText property which later can be summed up to get the summation.
Here is the working Fiddle : https://jsfiddle.net/ftordw4L/1/
HTML
<table id="tbl1">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
<tr>
<td class="total"><b>Total</b></td>
<td class="totalValue"></td>
</tr>
</table>
Javascript
var tds=document.getElementsByTagName("td");
var total=0;
for (var i = 0; i<tds.length; i++) {
if (tds[i].className == "value") {
if(total==0) {
total = parseInt(tds[i].innerText);
} else {
total = total + parseInt(tds[i].innerText);
}
}
}
document.getElementsByClassName('totalValue')[0].innerHTML = total;
Hope this helps!.
here is a solution with jQuery :) if you are interested. it's pretty straightforward
var sumCat1 = 0;
var sumCat2 = 0;
$(".cat1 + .value").each(function(){
sumCat1 += parseInt($(this).text());
})
$(".cat2 + .value").each(function(){
sumCat2 += parseInt($(this).text());
})
console.log(sumCat1)
console.log(sumCat2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
A simple approach in JQuery...
var obj = {};
$('tr').each(function() {
$this = $(this)
if ($this.length) {
var cat = $(this).find("td").first().html();
var val = $(this).find("td").last().html();
if (cat) {
if (!obj[cat]) {
obj[cat] = parseInt(val);
} else {
obj[cat] += parseInt(val);
}
}
}
})
console.log(obj)
I am adding values to table like:
Item,Quantity,Price,TotalPrice
Now there are multiple rows: How can i sum TotalPrice of all to get GrandTotal using Jquery.
Code:
$("#Product").append(" <tr><td id='clientname'>" +ClientName+ "</td> <td id='item'>"+ItemName+"</td> <td id='quantity'>"+Quantity+"</td> <td id='price'>"+Price+"</td> <td id='totalprice'>"+TotalPrice+"</td> <td> <a onClick='deleteRow(this);'>Delete</a> </td> </tr>");
Its possible when i insert new row data its show grand total in textbox/label,Like:
function TotalPriceCalc()
{
var lblTotalPrice = document.getElementById('lblTotalPrice');
lblTotalPrice.value = sum;
}
Here's an example that will sum whatever column index you provide.
$(function() {
$("#subtotal").html(sumColumn(4));
$("#total").html(sumColumn(5));
});
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="border-spacing: 10px;">
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>12</td>
<td>34</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>56</td>
<td>78</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>90</td>
<td>12</td>
</tr>
<tr>
<td colspan="3">Totals</td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</table>
After you use class= instead of id= .Cause ID MUST be unique. you need to loop through each row and find totalPrice
$(document).ready(function(){
var TotalValue = 0;
$("#Product tr").each(function(){
TotalValue += parseFloat($(this).find('.totalprice').text());
});
alert(TotalValue);
});
While you tagged Jquery .. This is a Jquery solution so please be sure to include Jquery
You should use classes, not IDs, to name repeated elements. So it should be:
...<td class="totalprice">'+TotalPrice+'</td>...
Then you can do
function TotalPriceCalc() {
var total = 0;
$(".totalprice").each(function() {
total += parseFloat($(this).text());
});
$("#lblTotalPrice").val(total);
}
Have look, this is our table
<table class="table table-bordered">
<thead>
<tr>
<th>1</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="loop">50</td>
</tr>
<tr>
<td>1</td>
<td id="loop">60</td>
</tr>
<tr>
<td>1</td>
<td id="loop">70</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="text-right">Total</td>
<td></td>
</tr>
</tbody>
And this is loop to have sum of price
$(function() {
var TotalValue = 0;
$("tr #loop").each(function(index,value){
currentRow = parseFloat($(this).text());
TotalValue += currentRow
});
console.log(TotalValue);
});
$(document).ready(function() {
var week = 5;
var players = 8;
var numbers = [];
var array = [];
for (o = 0; o < players; o++) {
for (i = 0; i < week + 1; i++) {
var improved = i + 1;
var oString = o.toString();
var iString = i.toString();
var id = "#" + oString + iString;
var rawText = $(id).text();
var refined = Number(rawText);
array.push(refined);
}
numbers.push(array);
array = [];
}
for (p = 0; i < numbers.length; p++) {
var total1 = 0;
$.each(numbers[0], function() {
total1 += this;
});
}
$("#total1").text(total1);
for (p = 0; i < numbers.length; p++) {
var total2 = 0;
$.each(numbers[0], function() {
total2 += this;
});
}
$("#total2").text(total2);
for (p = 0; i < numbers.length; p++) {
var total3 = 0;
$.each(numbers[0], function() {
total3 += this;
});
}
$("#total3").text(total3);
for (p = 0; i < numbers.length; p++) {
var total4 = 0;
$.each(numbers[0], function() {
total4 += this;
});
}
$("#total4").text(total4);
for (p = 0; i < numbers.length; p++) {
var total5 = 0;
$.each(numbers[0], function() {
total5 += this;
});
}
$("#total5").text(total5);
var total = total1 + total2 + total3 + total4 + total5;
$("#total").text(total);
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="jquery-1.11.1.min.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="style2.css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<link rel="icon" href="../favicon.ico" type="image/x-icon">
</head>
<body>
<table>
<tr>
<th>Player</th>
<th>Position</th>
<th>Week 7</th>
<th>Week 8</th>
<th>Week 9</th>
<th>Week 10</th>
<th>Week 11</th>
</tr>
<tr>
<td>Matt Ryan</td>
<td>QB</td>
<td id="01">11</td>
<td id="02">15</td>
<td id="03">00</td>
<td id="04">14</td>
<td id="05">14</td>
</tr>
<tr>
<td>Marshawn Lynch</td>
<td>RB</td>
<td id="11">06</td>
<td id="12">01</td>
<td id="13">09</td>
<td id="14">40</td>
<td id="15">12</td>
</tr>
<tr>
<td>Calvin Johsnon</td>
<td>WR</td>
<td id="21">00</td>
<td id="22">00</td>
<td id="23">00</td>
<td id="24">00</td>
<td id="25">00</td>
</tr>
<tr>
<td>Allen Hurns</td>
<td>WR</td>
<td id="31">00</td>
<td id="32">04</td>
<td id="33">23</td>
<td id="34">17</td>
<td id="35">05</td>
</tr>
<tr>
<td>A.J. Green</td>
<td>WR</td>
<td id="41">00</td>
<td id="42">00</td>
<td id="43">10</td>
<td id="44">02</td>
<td id="45">18</td>
</tr>
<tr>
<td>Julius Thomas</td>
<td>Tight End</td>
<td id="51">02</td>
<td id="52">02</td>
<td id="53">09</td>
<td id="54">18</td>
<td id="55">00</td>
</tr>
<tr>
<td>Matt Bryant</td>
<td>Kicker</td>
<td id="61">00</td>
<td id="62">03</td>
<td id="63">00</td>
<td id="64">15</td>
<td id="65">15</td>
</tr>
<tr>
<td>Texans</td>
<td>Defense</td>
<td id="71">04</td>
<td id="72">07</td>
<td id="73">12</td>
<td id="74">00</td>
<td id="75">08</td>
</tr>
<tr>
<td>Total:</td>
<td></td>
<td id="total1">00</td>
<td id="total2">00</td>
<td id="total3">00</td>
<td id="total4">00</td>
<td id="total5">00</td>
</tr>
</table>
<p>Total: <span id="totalAll"></span>
</p>
</body>
</html>
Recently, I was charged with creating a fantasy football website for my group of friends, having minimal Javascript and HTML experience. I don't mind manually inputing data from the NFL website, but I thought it would be cool to have a script to automatically add up the numbers in the table. But, the code I wrote doesn't work. Nobody I know has any knowledge in Computer Science, and Ive turned to Google throughout the whole process. The browser console returns no errors. What I expect to happen is the total points from all of my tds for each week go into the week total at the bottom, and then the week totals be added up into the final total. What really happens is nothing. Half the time, when I change something, the page crashes.
I cant seem to get a JSfiddle to run without crashing on run-time, so im putting it into pastebin
http://pastebin.com/Wb3ENMZY
All the for loops at the end are temporary, to be taken down when the first part works.
Not too sure why your code wouldn't work in JSFiddle
Here's a fiddle with a work example of what you were trying to accomplish Demo
HTML
<table>
<thead>
<tr>
<th>Player</th>
<th>Position</th>
<th>Week 7</th>
<th>Week 8</th>
<th>Week 9</th>
<th>Week 10</th>
<th>Week 11</th>
</tr>
<thead>
<tbody>
<tr>
<td>Matt Ryan</td>
<td>QB</td>
<td id="01">11</td>
<td id="02">15</td>
<td id="03">00</td>
<td id="04">14</td>
<td id="05">14</td>
</tr>
<tr>
<td>Marshawn Lynch</td>
<td>RB</td>
<td id="11">06</td>
<td id="12">01</td>
<td id="13">09</td>
<td id="14">40</td>
<td id="15">12</td>
</tr>
<tr>
<td>Calvin Johsnon</td>
<td>WR</td>
<td id="21">00</td>
<td id="22">00</td>
<td id="23">00</td>
<td id="24">00</td>
<td id="25">00</td>
</tr>
<tr>
<td>Allen Hurns</td>
<td>WR</td>
<td id="31">00</td>
<td id="32">04</td>
<td id="33">23</td>
<td id="34">17</td>
<td id="35">05</td>
</tr>
<tr>
<td>A.J. Green</td>
<td>WR</td>
<td id="41">00</td>
<td id="42">00</td>
<td id="43">10</td>
<td id="44">02</td>
<td id="45">18</td>
</tr>
<tr>
<td>Julius Thomas</td>
<td>Tight End</td>
<td id="51">02</td>
<td id="52">02</td>
<td id="53">09</td>
<td id="54">18</td>
<td id="55">00</td>
</tr>
<tr>
<td>Matt Bryant</td>
<td>Kicker</td>
<td id="61">00</td>
<td id="62">03</td>
<td id="63">00</td>
<td id="64">15</td>
<td id="65">15</td>
</tr>
<tr>
<td>Texans</td>
<td>Defense</td>
<td id="71">04</td>
<td id="72">07</td>
<td id="73">12</td>
<td id="74">00</td>
<td id="75">08</td>
</tr>
<tr>
<td>Total:</td>
<td></td>
<td id="total1">00</td>
<td id="total2">00</td>
<td id="total3">00</td>
<td id="total4">00</td>
<td id="total5">00</td>
</tr>
</tbody>
</table>
<p>Total: <span id="totalAll"></span>
</p>
Note the addition of the <thead> and the <tbody> this is so we can easily select the body rows in JQuery
Code
//Make a list of values for each column
var sums = [0,0,0,0,0];
//Go through each row in the body of the table
$("tbody tr").each(function () {
//We start at 2 because thats the firs of the weeks columns
for(var i = 2; i <= 6; i++)
{
//Add the current column's value to the sum. Note we use :eq() selector to get the i'th column
sums[i-2] += parseInt($("td:eq("+i+")", this).html());
}
});
var total = 0;
//Go through each column sum totalling it and writing it to the appropriate column
for(var i = 0; i < sums.length; i++)
{
total += sums[i];
$("#total" + (i + 1)).html(sums[i]);
}
//Write the total
$("#totalAll").html(total);
From your original code
for (p = 0; i < numbers.length; p++) {
var total1 = 0;
$.each(numbers[0], function() {
total1 += this;
});
}
This was causing Javascript to loop forever. Your for loop will loop until i < numbers.length but i isn't defined here. You probably mean p there. After replacing the i with p it no longer looped forever but each column would have the same value, numbers[0] should be changed for each column you're parsing.
I'm still having issues with your original code even after fixing those errors though.
I'm not excellent with javascript as you will see by the code (http://jsfiddle.net/au59P/2/). I've got my calculations partially working, but with a lot of incorrect results. I've spent all night working on it so I need some pointers to see where I'm going wrong.
Here's the HTML:
<table cell-spacing="0" cell-padding="0">
<tbody>
<tr>
<td>Int</td>
<td>40.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>50.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>60.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td colspan="3"></td>
<td>Subtotal</td>
<td class="subtotal"></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Int</td>
<td>40.00</td>
<td>
<input />
</td>
<td>40.50</td>
<td></td>
</tr>
<tr>
<td>Int></td>
<td>50.00</td>
<td>
<input />
</td>
<td>45.50</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>60.00</td>
<td>
<input />
</td>
<td>50.50</td>
<td></td>
</tr>
<tr>
<td colspan="3"></td>
<td>Subtotal</td>
<td class="subtotal"></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Int</td>
<td>40.00</td>
<td>
<input />
</td>
<td>30.00</td>
<td></td>
</tr>
<tr>
<td>Int></td>
<td>50.00</td>
<td>
<input />
</td>
<td>40.00</td>
<td></td>
</tr>
<tr>
<td>Int</td>
<td>60.00</td>
<td>
<input />
</td>
<td>50.50</td>
<td></td>
</tr>
<tr>
<td colspan="3"></td>
<td>Subtotal</td>
<td class="subtotal"></td>
</tr>
</tbody>
<tr>
<td class="active">Active</td>
<td class="total"></td>
<td colspan="3"></td>
</tr>
</table>
Here's the js:
var sumVal = 0;
function currentSum(){
$(".subtotal").each(function(){
sumVal += parseFloat($(this).text()).toFixed(2);
});
};
$("input").keyup(function(){
var newRate = parseFloat($(this).val(), 10).toFixed(2);
var multiplier = parseFloat($(this).parent().next("td").text(), 10).toFixed(2);
var calcRate = parseFloat(newRate * multiplier).toFixed(2);
$(this).parent().next("td").next("td").text("$" + calcRate).addClass("calculated");
var $tr = $(this).closest("tbody").find("tr");
var $total = $tr.has("td[colspan]");
var subCalc = 0;
$tr.not($total).each(function(){
if($(this).find(".calculated").text() !== ""){
var tempCalc = parseFloat($(".calculated").text().replace("$",""),10).toFixed(2);
subCalc += +parseFloat(tempCalc).toFixed(2);
};
});
$total.find("td.subtotal").text("$" + subCalc);
currentSum();
$(".active").next(".total").text(sumVal);
});
When entering a value in the input, it updates the multiplier in the 5th td, however the subtotal calculation is wrong, and the total calculation returns NaN. What's more, when I delete the value in one of the inputs, everything turns to NaN where I thought I had that if conditional in there to ignore all NaN.
Few problems
function currentSum() {
var sumVal = 0;
$(".subtotal").each(function () {
sumVal += parseFloat($(this).text().replace('$', '')) || 0;
});
return sumVal.toFixed(2);
};
then
$(".active").next(".total").text('$' + currentSum());
Demo: Fiddle
You need to check that parseFloat returns you a correct number before using it:
var someVar = /* parseFloat ... */
if (!isNaN(someVar)) {
// use someVar
}
Your main problem being parseFloat("$10") gives NaN because of the $
Updated fiddle (there are still some issues with computations)
var sumVal = 0;
var subCalc = 0;
function currentSum(){
$(".calculated").each(function(){
sumVal = (parseFloat(sumVal)+parseFloat($(".calculated").text().replace("$",""),10)).toFixed(2);
});
};
$("input").keyup(function(){
var newRate = parseFloat($(this).val(), 10).toFixed(2);
var multiplier = parseFloat($(this).parent().next("td").text(), 10).toFixed(2);
var calcRate = parseFloat(newRate * multiplier).toFixed(2);
$(this).parent().next("td").next("td").text("$" + calcRate).addClass("calculated");
var $tr = $(this).closest("tbody").find("tr");
var $total = $tr.has("td[colspan]");
$tr.not($total).each(function(){
if($(this).find(".calculated").text() !== ""){
var tempCalc = parseFloat($(".calculated").text().replace("$",""),10).toFixed(2);
subCalc = parseFloat(parseFloat(subCalc)+parseFloat(tempCalc)).toFixed(2);
};
});
$total.find("td.subtotal").text("$" + subCalc);
currentSum();
$(".active").next(".total").text(sumVal);
});
I made some changes to your script. It solves some problem. You can proceed from there.