Sum of values in html table row - javascript

I have this HTML table
Now I want to display sum of hours to the last column.
I tried like this, its not worked for me.
HTML
<table class='Table'>
<tr><td><span class='hours'>8:16</span></td><td><span class='hours'>8:27</span></td><td><span class='hours'>7:30</span></td><td>Print Sum of duration of this Row</td></tr>
<tr><td><span class='hours'>6:53</span></td><td><span class='hours'>8:02</span></td><td><span class='hours'>8:17</span></td><td>Print Sum of duration of this Row</td></tr>
<tr><td><span class='hours'>8:09</span></td><td><span class='hours'>8:28</span></td><td><span class='hours'>8:42</span></td><td>Print Sum of duration of this Row</td></tr>
</table>
Jquery
$(".Table tr td .hours").each(function(){
vals1=$(this).html()
console.log(vals1)
$(this).parent().parent().parent().find("td:last").html(vals1)
})
From the above code I am unable to determine end of row(TR).
Would be helpful if any suggestion to find sum of duration.

You can iterate over each tr and find the sum of the fields like
$(".Table tr:has(.hours)").each(function() {
var sum = 0;
$(this).find('td .hours').each(function() {
var parts = $(this).text().split(':')
sum += (parts[0] * 60 || 0) + (+parts[1] || 0);
});
var mins = Math.floor(sum / 60);
var sec = sum % 60;
$(this).find("td:last").html(mins + ':' + ('0' + sec).slice(-2))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='Table'>
<tr>
<td><span class='hours'>8:16</span>
</td>
<td><span class='hours'>8:27</span>
</td>
<td><span class='hours'>7:30</span>
</td>
<td>Print Sum of duration of this Row</td>
</tr>
<tr>
<td><span class='hours'>6:53</span>
</td>
<td><span class='hours'>8:02</span>
</td>
<td><span class='hours'>8:17</span>
</td>
<td>Print Sum of duration of this Row</td>
</tr>
<tr>
<td><span class='hours'>8:09</span>
</td>
<td><span class='hours'>8:28</span>
</td>
<td><span class='hours'>8:42</span>
</td>
<td>Print Sum of duration of this Row</td>
</tr>
</table>

Related

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>

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

How to multiply the contents of table cells via js?

I want to multiply cells content (only numbers) and using javascript.
The result is to be displayed in cell X
<script type="text/javascript">
function zmiana(){
var x = document.getElementById("rowstawka");
x.getElementsByTagName('td')[1].innerHTML=document.getElementById('Stawka2').value;
var y = document.getElementById("rowgodziny");
y.getElementsByTagName('td')[1].innerHTML=document.getElementById('Godziny').value;
}
</script>
I'm using the above script to add content to cells in a table.
And here is the table:
<table id="tabela">
<tr id="rowstawka">
<td>Stawka</td>
<td>12</td>
</tr>
<tr id="rowgodziny">
<td>Godziny</td>
<td>50</td>
</tr>
<tr id="rowPensja">
<td>Pensja</td>
<td>-</td>
</tr>
<tr id="rowNetto">
<td>Pensja Netto</td>
<td>x</td>
</tr>
</table>
If you can change the html, try using classes to determine which cells contains a number to be calculated:
<table id="tabela">
<tr id="rowstawka">
<td>Stawka</td>
<td class="num">12</td>
</tr>
<tr id="rowgodziny">
<td>Godziny</td>
<td class="num">50</td>
</tr>
<tr id="rowPensja">
<td>Pensja</td>
<td>-</td>
</tr>
<tr id="rowNetto">
<td>Pensja Netto</td>
<td id="result">x</td>
</tr>
</table>
Then use this simple snippet to make the magic:
var numbers = document.querySelectorAll(".num");
var total = 1;
for (var i = 0; i < numbers.length; i++)
{
total*= Number(numbers[i].innerText);
}
document.getElementById("result").innerText = total;
Fiddle

rewrite javascript that it marks different times

In my HTML I have different times not always time difference 15 minutes. it is possible to make so that (when 8:00 clock is automatically reads the ID and the next ID makes bold (example 8:00 clock ist neu and bolld is next id with 8:02)
`
var currentDate = new Date();
var currentHour = currentDate.getHours();
var currentMinute = currentDate.getMinutes();
var minuteBin = currentMinute - (currentMinute % 15);
var idString = ""+currentHour+minuteBin;
console.log("Time =",currentHour,":",currentMinute,"bin =",minuteBin,"idString =",idString);
document.getElementById(idString).className = 'bold';
.bold {
font-weight:bold;
}
<table>
<tr id="2145">
<td>21:45</td>
<td>A</td>
</tr>
<tr id="2200">
<td>22:00</td>
<td>B</td>
</tr>
<tr id="2215">
<td>22:15</td>
<td>C</td>
</tr>
</table>
<table width="166">
<tbody>
<tr>
<td>NISJA</td>
<td>OPERATORI</td>
</tr>
<tr>
<td>06:50</td>
<td>BREST-TOURS-ZA</td>
</tr>
<tr>
<td>07:15</td>
<td>HALIMAJ-REISEN</td>
</tr>
<tr>
<td>07:50</td>
<td>DIDI-COMPANI</td>
</tr>
<tr>
<td>08:20</td>
<td>DRINI-REISEN</td>
</tr>
<tr>
<td>08:45</td>
<td>BASHKIMI-REISEN</td>
</tr>
<tr>
<td>09:05</td>
<td>FIDANI-TOURS</td>
</tr>
<tr>
<td>09:30</td>
<td>ZHUR-TOURS</td>
</tr>
<tr>
<td>09:55</td>
<td>MIR-TOURS</td>
</tr>
<tr>
<td>10:20</td>
<td>ATMAXHA</td>
</tr>
<tr>
<td>10:35</td>
<td>ARBËRIA-TOURS</td>
</tr>
<tr>
<td>11:00</td>
<td>SHPEJTIMI</td>
</tr>
<tr>
<td>11:20</td>
<td>SHARRI</td>
</tr>
<tr>
<td>11:45</td>
<td>HALIMAJ-REISEN</td>
</tr>
<tr>
<td>12:00</td>
<td>FATI-TOURS</td>
</tr>
<tr>
<td>12:10</td>
<td>BREST-ZAPLLUZHË</td>
</tr>
<tr>
<td>12:35</td>
<td>JETA</td>
</tr>
<tr>
<td>12:50</td>
<td>ERZA-ZAPLLUZHË</td>
</tr>
<tr>
<td>13:05</td>
<td>DIDI-COMPANI</td>
</tr>
<tr>
<td>13:30</td>
<td>DARDANI</td>
</tr>
<tr>
<td>14:00</td>
<td>BASHKIMI-REISEN</td>
</tr>
<tr>
<td>14:30</td>
<td>ZHUR-TOURS</td>
</tr>
<tr>
<td>14:45</td>
<td>TOSA-ZAPLLUZHË</td>
</tr>
<tr>
<td>14:55</td>
<td>NUHI-Q-GASHI</td>
</tr>
<tr>
<td>15:05</td>
<td>Op. nuk dihet</td>
</tr>
<tr>
<td>15:20</td>
<td>Op. nuk dihet</td>
</tr>
<tr>
<td>15:35</td>
<td>ATMAXHA</td>
</tr>
<tr>
<td>15:50</td>
<td>ARBËRIA-TOURS</td>
</tr>
<tr>
<td>16:10</td>
<td>SHPEJTIMI</td>
</tr>
<tr>
<td>16:25</td>
<td>MIR-TOURS</td>
</tr>
<tr>
<td>16:40</td>
<td>BRES TOUR</td>
</tr>
<tr>
<td>16:55</td>
<td>HALIMAJ-REISEN</td>
</tr>
<tr>
<td>17:15</td>
<td>SHPEJTIMI</td>
</tr>
<tr>
<td>17:35</td>
<td>SHARRI</td>
</tr>
<tr>
<td>17:55</td>
<td>JETA</td>
</tr>
<tr>
<td>18:15</td>
<td>BASHKIMI-REISEN</td>
</tr>
<tr>
<td>18:40</td>
<td>ZHUR-TOURS</td>
</tr>
<tr>
<td>18:55</td>
<td>TEUTA-MARKET</td>
</tr>
<tr>
<td>19:15</td>
<td>BRES-TOU-ZAPLL</td>
</tr>
<tr>
<td>19:45</td>
<td>DARDANI</td>
</tr>
<tr>
<td>20:10</td>
<td>ERZA</td>
</tr>
</tbody>
</table>
You want the next possible ID to light up, so we'll have to find out what that one is. Lets try the following:
First, get the current possible ID. You already have this. Except, you don't want to round this to 15. You want the current time so you can select any time you have an id for.
var currentTimeStamp = currentHour + '' + minutes;
Now we want to keep upping this id by 1 as long as it does not exist.
To prevent an infinite loop, also add a maximum amount we can count. If this id doesn't exist, document.getElementById will return undefined, which is false, so it will keep looping until either the currentTimeStamp is no longer smaller than our stopCounting value, or when getElementById is not undefined or false anymore. That result tells you the closest existing id.
var stopCounting = currentTimeStamp + 15;
while(
!document.getElementById(currentTimeStamp) &&
currentTimeStamp < stopCounting
){
currentTimeStamp++;
}
The while loop can end in one of two ways:
1) We found an element
2) We reached the maximum value we want to try (15 in this case)
So check if the element exists by checking getElement again, and defining it as false if not.
var selectedId = document.getElementById(currentTimeStamp) || false;
The last bit is to add your class if it exists (and therefor doesn't evaluate to false), otherwise we'll log an error message.
if(selectedId){
selectedId.className += "bold";
} else {
console.log("Could not find an id within 15 minutes of now.");
}
This is the whole process to use in your case. I don't know what you are trying to accomplish here, I have a slight feeling it's a complicated way to succeed. I think it might be better to use a data-attribute for this instead of an id, but okay.
Heres a fully functional snippet that searches for the next available id:
Updated
I've added a by-the-minute checker.
var current = false;
function check(){
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
document.getElementById("currentTime").innerHTML = hours + ":" + minutes;
var maximum = minutes + 15;
while(
!document.getElementById('q-' + minutes) &&
minutes < maximum
) {
minutes++;
}
var id = document.getElementById('q-' + minutes) || false;
// Remove any existing selected classes:
var all = document.querySelectorAll(".selected");
for(var i = 0; i < all.length; i++){
all.item(i).className = all.item(i).className.replace("selected", "");
}
if(id){
id.className = "selected";
}
// Run the function every 60 seconds
setTimeout(check, 1000 * 60);
}
// Start running the function
check();
.selected { color: red }
<div>Current time: <strong id="currentTime"></strong></div>
<br /><br />
<div id="q-0">The hour is coming up.</div>
<div id="q-15">A quarter past is coming up.</div>
<div id="q-30">Half past is coming up.</div>
<div id="q-45">A quarter to is coming up.</div>

Lots of NaN and incorrect values in a block of jQuery?

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.

Categories