How calculate rate from div class? - javascript

I have two html table which make sum each it row and last row show sum.
Now I what calculate rate from sum result from this html table
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">
<table width="100%">
<tbody>
<tr>
<td class="box_price-1" align="left">100</td>
<td class="box_price-1" align="left">200</td>
</tr>
<tr>
<td class="box_price-2" align="left">100</td>
<td class="box_price-2" align="left">200</td>
</tr>
<tr>
<td class="box_sum-1 box1-total-1" align="left"></td>
<td class="box_sum-2 box1-total-2" align="left"></td>
</tr>
</tbody>
</table>
</div>
<div class="box2">
<table width="100%">
<tbody>
<tr>
<td class="box_price-1" align="left">100</td>
<td class="box_price-1 box_price-m-2" align="left">2030</td>
</tr>
<tr>
<td class="box_price-2" align="left">1003</td>
<td class="box_price-2" align="left">230</td>
</tr>
<tr>
<td class="box_sum-1 box2-total-1" align="left"></td>
<td class="box_sum-2 box2-total-1" align="left"></td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var total = 0;
$('.box1 .box_price-1').each(function() {
total += parseInt($(this).text());
});
$('.box1 .box_sum-1').append("<div class='sum'>" + total + "</div>");
console.log(total);
var total = 0;
$('.box1 .box_price-2').each(function() {
total += parseInt($(this).text());
});
$('.box1 .box_sum-2').append("<div class='sum'>" + total + "</div>");
console.log(total);
var total = 0;
$('.box2 .box_price-1').each(function() {
total += parseInt($(this).text());
});
$('.box2 .box_sum-1').append("<div class='sum'>" + total + "</div>");
console.log(total);
var total = 0;
$('.box2 .box_price-2').each(function() {
total += parseInt($(this).text());
});
$('.box2 .box_sum-2').append("<div class='sum'>" + total + "</div>");
console.log(total);
</script>
I have two html table which make sum each it row and last row show sum.
Now I what calculate rate from sum result from this html table
I want show result like this
rate1 = (box1-total-1) * 100 / box2-total-1
rate2 = (box1-total-2) * 100 / box2-total-2
<div class="rate1"></div>
<div class="rate2"></div>

You are using incorrect class names. In line - $('.box1 .box_price-1') there is a class with name box_price1 not box_price-1.
let box1Sum1 = 0;
$('.box1 .box_price1').each(function() {
box1Sum1 += parseInt($(this).text());
});
$('.box1 .box_sum-1').text(box1Sum1);
let box1Sum2 = 0;
$('.box1 .box_price2').each(function() {
box1Sum2 += parseInt($(this).text());
})
$('.box1 .box_sum-2').text(box1Sum2);
let box2Sum1 = 0;
$('.box2 .box_price1').each(function() {
box2Sum1 += parseInt($(this).text());
});
$('.box2 .box_sum-1').text(box2Sum1);
let box2Sum2 = 0;
$('.box2 .box_price2').each(function() {
box2Sum2 += parseInt($(this).text());
});
$('.box2 .box_sum-2').text(box2Sum2);
const rate1 = box1Sum1 * 100 / box2Sum1;
const rate2 = box1Sum2 * 100 / box2Sum2;
console.log(rate1, rate2);
$('div.rate1').text('Rate 1: ' + rate1 );
$('div.rate2').text('Rate 2: ' + rate2 );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1">
<table width="100%" border="1">
<thead>
<th>Amount1</th>
<th>Amoutn2</th>
<th>Sum</th>
</thead>
<tbody>
<tr>
<td class="box_price1" align="left">100</td>
<td class="box_price1" align="left">200</td>
<td class="box_sum-1 box1-total-1" align="left"></td>
</tr>
<tr>
<td class="box_price2" align="left">100</td>
<td class="box_price2" align="left">200</td>
<td class="box_sum-2 box1-total-2" align="left"></td>
</tr>
</tbody>
</table>
</div>
<div class="box2">
<table width="100%" border="1">
<thead>
<th>Amount1</th>
<th>Amount2</th>
<th>Sum</th>
</thead>
<tbody>
<tr>
<td class="box_price1" align="left">100</td>
<td class="box_price1 box_price-m-2" align="left">2030</td>
<td class="box_sum-1 box2-total-1" align="left"></td>
</tr>
<tr>
<td class="box_price2" align="left">1003</td>
<td class="box_price2" align="left">230</td>
<td class="box_sum-2 box2-total-1" align="left"></td>
</tr>
<tr>
</tr>
</tbody>
</table>
</div>
<div class="rate1"></div>
<div class="rate2"></div>

Related

how can i get sum of one columns rows? [duplicate]

I am trying to add Price from table column to a total.
I am having problem adding values such as 10.00 or 5.99. I am able to calculate prices with int values, but not with values 10.00 or 5.99, etc.
Here is what I have below.
var table = document.getElementById("myTable"),
sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseF(table.rows[i].cells[2].innerHTML);
}
document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
console.log(sumVal);
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
</table>
<span id="val"></span>
You have three issues:
You are grabbing the wrong cell index, indices start at 0:
table.rows[i].cells[1]
You need to call the correct parse function:
parseFloat(table.rows[i].cells[1].innerHTML);
You need to format your output:
"SubTotal = $" + sumVal.toFixed(2);
Update: Added functionality for removing rows.
updateSubTotal(); // Initial call
function updateSubTotal() {
var table = document.getElementById("myTable");
let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[1].innerHTML);
}, 0);
document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
}
function onClickRemove(deleteButton) {
let row = deleteButton.parentElement.parentElement;
row.parentNode.removeChild(row);
updateSubTotal(); // Call after delete
}
#myTable td {
padding: 0.25em;
}
#val {
display: block;
margin-top: 0.5em;
}
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoodie</td>
<td class="count-me">15.00</td>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
</table>
<span id="val"></span>
You are accessing the incorrect array element and also need to use parseFloat
The cells array is zero-based so you need to use cells[1] to access the second column:
var table = document.getElementById("myTable"),
sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseFloat(table.rows[i].cells[1].innerHTML);
}
document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
console.log(sumVal);
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
</table>
<span id="val"></span>
updateSubTotal(); // Initial call
function updateSubTotal() {
var table = document.getElementById("myTable");
let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[1].innerHTML);
}, 0);
let subTotal2 = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[2].innerHTML);
}, 0);
document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
document.getElementById("val1").innerHTML = subTotal2.toFixed(2);
}
function onClickRemove(deleteButton) {
let row = deleteButton.parentElement.parentElement;
row.parentNode.removeChild(row);
updateSubTotal(); // Call after delete
}
#myTable td {
padding: 0.25em;
}
#val {
display: block;
margin-top: 0.5em;
}
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>M2</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoodie</td>
<td class="count-me">15.00</td>
<td class="count-me">34.00</th>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td class="count-me">22.34</th>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
</table>
<span id="val"></span>
<span id="val1"></span>
var cell = document.getElementsByClassName("count-me");
var val = 0;
var i = 0;
while (cell[i] != undefined) {
val += parseFloat(cell[i].innerHTML);
i++;
} //end while
document.getElementById("val").innerHTML = parseFloat(val).toFixed(2);
console.log(parseFloat(val).toFixed(2));
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr id="">
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td>
<button onClick="myFunction()">Remove</button>
</td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td>
<button onClick="myFunction()">Remove</button>
</td>
</tr>
</table>
<span id="val"></span>

Calculate sum of input values in for loop [duplicate]

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>

addClass with multiple results from find

I'm using this function to add the class hide to the table row that contains the value of my variable text. The problem is that usually my selected td can get two values, but this function only works well with one value.
My tables:
<div id="csvtextcomptb" class="tableunform"><table cellspacing="1"
cellpadding="1" border="1"><thead><tr><th>TABLE</th><th>TAG</th><th>DATE</th><th>STATUS</th><th>Key</th><th>Prev</th></tr></thead>
<tbody><tr><td>COMP</td><td> COMP_TRUCK </td><td>17/10/2017</td><td>Prev(1)</td><td>CA5520</td><td>MP < 1K</td></tr>
<tr class="hide"><td>COMP</td><td> COMP_TRUCK </td><td>17/10/2017</td><td>Prev(2)</td><td>CA5520</td><td>MP > 1K</td></tr>
<tr class="hide"><td>COMP</td><td> COMP_TRUCK </td><td>17/10/2017</td><td>Prev(2)</td><td>CA5534</td><td>MP > 1K</td></tr>
<tr class="hide"><td>COMP</td><td>COMP_TRUCK </td><td>17/10/2017</td><td>Prev(2)</td><td>CA5328</td><td>MP > 1K</td></tr></tbody></table></div>
<table id="filter_crca">
<tbody>
<tr>
<td class="pointer selected">MP < 1K</td>
<td class="pointer">MP > 1K</td>
</tr>
</tbody>
</table>
Function:
$(document).on("click","[id*='filter_'] tbody td", function(e){
$(this).toggleClass('selected');
var prev = $(this).text().trim();
var tbid = $(this).closest('table').attr('id');
var regExp = /[^\*filter_]\w+/;
var tableid = regExp.exec(tbid.toString());
var tipotb = tableid.toString().split('_')[0];
var text = $('#filter_' + tableid).find("td").map(function(){
if( $(this).hasClass("selected") ) {
return $(this).text()
}
}).get();
$.each(text, function(index, value){
$('#csvtext' + tipotb + 'tb tbody').find("tr:contains('" + tableid.toString().toUpperCase() + "'):contains('" + value + "')").removeClass('hide');
$('#csvtext' + tipotb + 'tb tbody').find("tr:contains('" + tableid.toString().toUpperCase() + "'):not(:contains('" + value + "'))").addClass('hide');
});
});
How can I change this function to read those values of td with selected class and merge them to add or remove hide?
Thanks!
Hope this is what you are looking for:
$(document).on("click", "[id*='filter_'] tbody td", function (e) {
var prev = $(this).text().trim();
var tbid = $(this).closest('table').attr('id');
var regExp = /[^\*filter_]\w+/;
var tableid = regExp.exec(tbid.toString());
var tipotb = tableid.toString().split('_')[0];
//Added code
$('#filter_' + tableid).find("td").not(this).removeClass('selected');
$(this).toggleClass('selected');
var text = $('#filter_' + tableid).find("td.selected").text();
$('#csvtext' + tipotb + 'tb tbody tr').addClass("hide");
//End
$('#csvtext' + tipotb + 'tb tbody').find("tr:contains('" + tableid.toString().toUpperCase() + "'):contains('" + text + "')").removeClass('hide');
//$('#csvtext' + tipotb + 'tb tbody').find("tr:contains('" + tableid.toString().toUpperCase() + "'):not(:contains('" + text + "'))").addClass('hide');
});
.selected {
color: red;
}
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="csvtextcomptb" class="tableunform">
<table cellspacing="1" cellpadding="1" border="1">
<thead>
<tr>
<th>TABLE</th>
<th>TAG</th>
<th>DATE</th>
<th>STATUS</th>
<th>Key</th>
<th>Prev</th>
</tr>
</thead>
<tbody>
<tr>
<td>COMP</td>
<td> COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(1)</td>
<td>CA5520</td>
<td>MP < 1K</td>
</tr>
<tr class="hide">
<td>COMP</td>
<td> COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(2)</td>
<td>CA5520</td>
<td>MP > 1K</td>
</tr>
<tr class="hide">
<td>COMP</td>
<td> COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(2)</td>
<td>CA5534</td>
<td>MP > 1K</td>
</tr>
<tr class="hide">
<td>COMP</td>
<td>COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(2)</td>
<td>CA5328</td>
<td>MP > 1K</td>
</tr>
</tbody>
</table>
</div>
<table id="filter_comp">
<tbody>
<tr>
<td class="pointer selected">MP < 1K</td>
<td class="pointer">MP > 1K</td>
</tr>
</tbody>
</table>
I dont knkow if the below snippet is your need , but I've set some change in your code to sweet your demand , also you have wrong table associated to it's filter id !
See below snippet :
$(document).on("click", "[id*='filter_'] tbody td", function(e) {
$(this).toggleClass('selected');
var prev = $(this).text().trim();
var tbid = $(this).closest('table').attr('id');
var regExp = /[^\*filter_]\w+/;
var tableid = regExp.exec(tbid.toString());
var tipotb = tableid.toString().split('_')[0];
$('#csvtext' + tipotb + 'tb tbody').find("tr").addClass('hide');
$('#filter_' + tableid).find("td").each(function() {
if ($(this).hasClass("selected")) {
var text = $(this).text();
$('#csvtext' + tipotb + 'tb tbody').find("td:contains('" + text + "')").parent('tr').removeClass('hide');
}
});
});
.pointer {
cursor: pointer;
border: 1px solid black;
}
.selected {
color: red;
font-weight: bold;
}
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="csvtextcrcatb" class="tableunform">
<table cellspacing="1" cellpadding="1" border="1">
<thead>
<tr>
<th>TABLE</th>
<th>TAG</th>
<th>DATE</th>
<th>STATUS</th>
<th>Key</th>
<th>Prev</th>
</tr>
</thead>
<tbody>
<tr>
<td>COMP</td>
<td> COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(1)</td>
<td>CA5520</td>
<td>MP < 1K</td>
</tr>
<tr >
<td>COMP</td>
<td> COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(2)</td>
<td>CA5520</td>
<td>MP > 1K</td>
</tr>
<tr >
<td>COMP</td>
<td> COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(2)</td>
<td>CA5534</td>
<td>MP > 1K</td>
</tr>
<tr >
<td>COMP</td>
<td>COMP_TRUCK </td>
<td>17/10/2017</td>
<td>Prev(2)</td>
<td>CA5328</td>
<td>MP > 1K</td>
</tr>
</tbody>
</table>
</div>
<table id="filter_crca">
<tbody>
<tr>
<td class="pointer selected">MP < 1K</td>
<td class="pointer selected">MP > 1K</td>
</tr>
</tbody>
</table>

How To Sum All Table Rows td (TotalPrice) using td id Jquery

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

Trouble with IDs and for loops in Javascript

$(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.

Categories