Suppose i have the table below and i want to add the column Credits to get its sum
<table id="tbl_semester11">
<thead>
<tr>
<th>Semester 1</th>
</tr>
</thead>
<thead>
<tr>
<th>Module Code</th>
<th>Module Name</th>
<th>Credits</th>
<th>Module %</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>MGMT1101C</td>
<td>Management Seminar</td>
<td id="txtcredit112" class="sum">3</td>
<td><input type="number" id="txtpercentage112" min="40" max="100" onchange="process([1,1,2,5]);"></td>
<td id="txtgrade112">D</td>
</tr>
<tr class="alt">
<td>HCA1105C</td>
<td>Computer Architecture</td>
<td id="txtcredit113" class="sum">4</td>
<td><input type="number" id="txtpercentage113" min="40" max="100" onchange="process([1,1,3,5]);"></td>
<td id="txtgrade113">D</td>
</tr>
<tr>
<td>PROG1115C</td>
<td>Object Oriented Software Development I</td>
<td id="txtcredit114" class="sum">4</td>
<td><input type="number" id="txtpercentage114" min="40" max="100" onchange="process([1,1,4,5]);"></td>
<td id="txtgrade114">D</td>
</tr>
<tr class="alt">
<td>MATH1103C</td>
<td>Decision Mathematics</td>
<td id="txtcredit115" class="sum">3</td>
<td><input type="number" id="txtpercentage115" min="40" max="100" onchange="process([1,1,5,5]);"></td>
<td id="txtgrade115">D</td>
</tr>
<tr>
<td>ITE1107C</td>
<td>Language and Communication Seminar</td>
<td id="txtcredit116" class="sum">3</td>
<td><input type="number" id="txtpercentage116" min="40" max="100" onchange="process([1,1,6,5]);"></td>
<td id="txtgrade116">D</td>
</tr>
<tr class="al">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td bgcolor="#b3ffb3"><b>S.P.A</b></td>
<td bgcolor="#4dff4d" id="spa11">40.7</td>
</tr>
</tbody>
</table>
Here is my JS
function getsum(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + '.sum').each(function () {
sum += +(this).text()||0;
});
return sum;
arr is the same parameter as process i.e [1,1,3,5].The problem is that sum always returns 0
Your selector is wrong. If you want to select children with the .sum class, you should add a space between parent and children. Your function should be:
function getsum(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' .sum').each(function () {
sum += parseInt($(this).text())||0;
});
return sum;
}
Also, I used parseInt() because .text() returns a string. That way you are sure to have a NaN value or an actual integer.
Related
I have a simple table and I want to sum two comlumns. On top of than only when a relevant checkbox is checked.
The table is like that
<table id="Zinzino" style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<th><strong>Název</strong></th>
<th class="sum"><strong>První balíček</strong></th>
<th class="sum"><strong>Měsíčně</strong></th>
<th> </th>
</tr>
<tr>
<td>BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru"></td>
<td>149 EUR</td>
<td>30 EUR</td>
<td> </td>
</tr>
<tr>
<td>Extend (2x)<input type="checkbox" </td>
<td>44 EUR</td>
<td>22 EUR</td>
<td> </td>
</tr>
<tr>
<td>Zinobiotic (3x)<input type="checkbox" </td>
<td>64 EUR</td>
<td>23 EUR</td>
<td> </td>
</tr>
<tr>
<td><strong>Celkem</strong></td>
<td class="celkem"> </td>
<td class="celkem"> </td>
<td> </td>
</tr>
</tbody>
</table>
I can modify the hmtl if needed. I have a working fiddle solution Because I have not found anything working out of the box I coded this one. I am sure that someone could provide us with something more elegant. Or even correct my code.
This should do it. Feel free to ask if some detail is not understood.
$("input[type='checkbox']").on('change', function() {
updateTotals();
});
function updateTotals() {
// loop cells with class 'celkem'
$('.total').each(function(){
// for each total, get the column
const column = $(this).index();
let total = 0;
// loop trough all table rows, except the header and the row of totals
$(this).closest('table').find('tr:not(:first, :last)').each(function(){
if($(this).find('input').is(':checked')) {
// if the input is checked, add the numeric part to the total
const str = $(this).find(`td:eq(${column})`).text().replace(/\D/g, "");
if(str) {
total += Number(str);
}
}
});
if(!total) {
// if the total is zero, clear the cell
$(this).text("");
} else {
// otherwise, print the total for this column in the cell
$(this).text(total + " EUR");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" width="100%">
<tr>
<th>Col 1</th>
<th><strong>Col 2</strong></th>
<th><strong>Col 3</strong></th>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>149 EUR</td>
<td>30 EUR</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>44 EUR</td>
<td>22 EUR</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>64 EUR</td>
<td>23 EUR</td>
</tr>
<tr>
<td><strong>Totals</strong></td>
<td class="total"> </td>
<td class="total"> </td>
</tr>
</table>
OK, I completed my solution which can be seen as an "almost One-Liner" in Vanilla JavaScript. Because of its brevity the readybility is slightly impaired.
In the second line the array trs is filled with all table rows (trs) with checked boxes. Only if something was checked (i.e. trs.length is "truthy") the calculation of sums is started in the following lines, otherwise sums is set to false. The "calculation" consists of a two-stage .map()-process (resulting in a 2D Array with all the individual prices) and a subsequent .reduce() call to do the summation for each column. A .forEach() is used internally here to do the summation for each of the relevant columns (not the first and the last ones).
In the last two lines the reults are written back to the table (last table record). Here the trenary operator ( ? : ) carefully checks whether sums is "truthy" before attemping the concatenation of sums[j]+" EUR".
document.getElementById("Zinzino").addEventListener('change',function(ev){
const trs=[...document.querySelectorAll("tbody tr")].filter(tr=>tr.querySelector(':checked'));
const sums=trs.length // calculate only when boxes were checked ...
? trs.map(tr=>[...tr.children].slice(1,-1) // NOT first and last columns
.map(td=>parseInt(td.textContent))) // 2D array of prices
.reduce((a,c)=>(a.forEach((dum,j)=>a[j]+=c[j]),a) ) // summation for each column
: false; // -> no calculation
// put results into last table row:
[...document.querySelectorAll("tbody tr:last-child td")].slice(1,-1)
.forEach((td,j)=>td.textContent=sums ? sums[j]+" EUR" :'' );
})
<table id="Zinzino" style="border-collapse: collapse; width: 100%;" border="1">
<thead><tr>
<th><strong>Název</strong></th>
<th class="sum"><strong>První balíček</strong></th>
<th class="sum"><strong>Měsíčně</strong></th>
<th> </th>
</tr></thead>
<tbody>
<tr>
<td>BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru"></td>
<td>149 EUR</td>
<td>30 EUR</td>
<td> </td>
</tr>
<tr>
<td>Extend (2x)<input type="checkbox"></td>
<td>44 EUR</td>
<td>22 EUR</td>
<td> </td>
</tr>
<tr>
<td>Zinobiotic (3x)<input type="checkbox"></td>
<td>64 EUR</td>
<td>23 EUR</td>
<td> </td>
</tr>
<tr>
<td><strong>Celkem</strong></td>
<td class="celkem"> </td>
<td class="celkem"> </td>
<td> </td>
</tr>
</tbody>
</table>
i want to calculate sum of all columns, and subtraction of col1 and col2 only, i found few examples online to add row data but how i can perform both action on one row. using class or id name.
<table id="sum_table" width="450" border="1">
<thead>
<tr>
<th>column one</th>
<th >column two</th>
<th >column three</th>
<th >sum of all columns</th>
<th >subtraction</th>
</tr>
</thead>
<tbody>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
<td><span class="sum"></span> </td>
<td><span class="subtract"></span> </td>
</tr>
<tr>
<td class="col1">43</td>
<td class="col2">432</td>
<td class="col3">33</td>
<td> <span class="sum"></span> </td>
<td> <span class="subtract"></span> </td>
</tr>
</tbody>
</table>
<button id="calculate" onclick = "calculate()">calculate</button>
jquery:
function calculate(){
var col1=$('.col1').text();
var col2=$('.col2').text();
var col3=$('.col3').text();
var sum= col1+col2+col3;
var subtract= col1-col2;
$(".sum").text(sum);
$(".subtract").text(subtract);
}
JSFiddle
Loop through all the table tr and use .find() on the columns you need. I added .col on each of the value columns so we won't need to specify the three columns on addition.
function calculate() {
var sum;
var difference;
$("tbody tr").each(function() {
sum = 0;
difference = 0;
$(this).find(".col").each(function() {
// console.log($(this).html());
sum += parseFloat($(this).html());
});
difference = parseFloat($(this).find(".col1").html()) - parseFloat($(this).find(".col2").html());
$(this).find(".sum").html(sum);
$(this).find(".subtract").html(difference);
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sum_table" width="450" border="1">
<thead>
<tr>
<th>column one</th>
<th>column two</th>
<th>column three</th>
<th>sum of all columns</th>
<th>subtraction</th>
</tr>
</thead>
<tbody>
<tr>
<td class="col col1">1</td>
<td class="col col2">2</td>
<td class="col col3">3</td>
<td><span class="sum"></span> </td>
<td><span class="subtract"></span> </td>
</tr>
<tr>
<td class="col col1">43</td>
<td class="col col2">432</td>
<td class="col col3">33</td>
<td> <span class="sum"></span> </td>
<td> <span class="subtract"></span> </td>
</tr>
</tbody>
</table>
<button id="calculate" onclick="calculate()">calculate</button>
Here's the answer using input fields;
$(document).ready(function() {
$("#calculate").on("click", function() {
var sum;
var difference;
$("tbody tr").each(function() {
sum = 0;
difference = 0;
$(this).find(".col").each(function() {
// console.log($(this).html());
sum += parseFloat($(this).find("input").val());
});
difference = parseFloat($(this).find(".col1").find("input").val()) - parseFloat($(this).find(".col2").find("input").val());
$(this).find(".sum").html(sum);
$(this).find(".subtract").html(difference);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sum_table" width="450" border="1">
<thead>
<tr>
<th>column one</th>
<th>column two</th>
<th>column three</th>
<th>sum of all columns</th>
<th>subtraction</th>
</tr>
</thead>
<tbody>
<tr>
<td class="col col1"><input value="1" /></td>
<td class="col col2"><input value="2" /></td>
<td class="col col3"><input value="3" /></td>
<td><span class="sum"></span> </td>
<td><span class="subtract"></span> </td>
</tr>
<tr>
<td class="col col1"><input value="43" /></td>
<td class="col col2"><input value="432" /></td>
<td class="col col3"><input value="33" /></td>
<td> <span class="sum"></span> </td>
<td> <span class="subtract"></span> </td>
</tr>
</tbody>
</table>
<button id="calculate">Sum
</button>
Please check this working example.
var col1=0,col2=0,col3=0,sum=0,subtract=0;
function calculate(){
$(".jsTableBody tr").each(function(){
col1=$(this).find('.col1').text();
col2=$(this).find('.col2').text();
col3=$(this).find('.col3').text();
sum= parseInt(col1) + parseInt(col2)+ parseInt(col3);
console.log(sum);
subtract= parseInt(col1)-parseInt(col2);
$(this).find(".sum").html(sum);
$(this).find(".subtract").html(subtract);
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sum_table" width="450" border="1">
<thead>
<tr>
<th>column one</th>
<th >column two</th>
<th >column three</th>
<th >sum of all columns</th>
<th >subtraction</th>
</tr>
</thead>
<tbody class="jsTableBody">
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
<td><span class="sum"></span> </td>
<td><span class="subtract"></span> </td>
</tr>
<tr>
<td class="col1">43</td>
<td class="col2">432</td>
<td class="col3">33</td>
<td> <span class="sum"></span> </td>
<td> <span class="subtract"></span> </td>
</tr>
</tbody>
</table>
<button id="calculate" onclick = "calculate()">calculate</button>
I have a table like below :
<table>
<th>Sl No</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount %</th>
<th>Total Price</th>
<tr>
<td>1</td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess_sum"></input></td>
</tr>
<tr>
<td>2</td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess" ></input></td>
<td><input class="expensess_sum"></input></td>
</tr>
</table>
Grand Total = <input id="grand_total">
I am trying to display the Total Price of each row using jquery keyup function.
and also want to display the grand total price of the each row.
the formula of finding the Total Price is given below :
discount_value = Price*(discount_percent/100)
discount_price = Price-discount_value
total_price = discount_price * quantity
How can I do this please help
i am trying simply just summing all value like this :
<script type="text/javascript">
$(document).ready(function(){
$(".expensess").each(function() {
$(document).on('keyup', '.expensess', function() {
sum($(this).parents("tr"));
});
});
});
function sum(parent){
var sum = 0;
$(parent).find(".expensess").each(function(){
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$(parent).find(".expensess_sum").val(sum.toFixed(2));
}
</script>
But m confused how to implement the above formula for calculate the total price.
$('input.qty,input.price,input.discount').on('change keyup',function(){
var $tr = $(this).closest('tr'),
$qty = $tr.find('input.qty') ,
$price= $tr.find('input.price'),
$discount= $tr.find('input.discount'),
$total= $tr.find('input.expensess_sum'),
$grand_total=$('#grand_total');
$total.val($qty.val()*($price.val()-($price.val()*($discount.val()/100))));
var grandTotal=0;
$('table').find('input.expensess_sum').each(function(){
if(!isNaN($(this).val()))
{grandTotal += parseInt($(this).val());
}
});
if(isNaN(grandTotal))
grandTotal =0;
$grand_total.val(grandTotal)
})
input{
width:80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table>
<tbody><tr>
<th>Sl No</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount %</th>
<th>Total Price</th>
</tr>
<tr>
<td>1</td>
<td><input class="expensess qty"></td>
<td><input class="expensess price"></td>
<td><input class="expensess discount"></td>
<td><input class="expensess_sum" disabled=""></td>
</tr>
<tr>
<td>2</td>
<td><input class="expensess qty"></td>
<td><input class="expensess price"></td>
<td><input class="expensess discount"></td>
<td><input class="expensess_sum" disabled=""></td>
</tr>
</tbody></table>
Grand Total = <input id="grand_total" disabled="">
</body>
Did it by using simple java script Code!
var sumExpenses = 0;
var tdBudget = document.getElementById('tableBudget').getElementsByTagName('td');
for (var i = 0; i < tdBudget.length; i++) {
if (tdBudget[i].className == "spanexpense") {
sumExpenses += isNaN(tdBudget[i].innerHTML) ? 0 : parseInt(tdBudget[i].innerHTML);
}
}
document.getElementById('sumExpenses').innerHTML = sumExpenses;
<table class="table table-bordered">
<thead>
<tr>
<td class="label-title">Value</td>
<td class="label-title">Value</td>
<td class="label-title">Value</td>
</tr>
</thead>
<tbody id="tableBudget">
<tr>
<td class="spanexpense">
12
</td>
<td class="spanexpense">
23
</td>
<td class="spanexpense">
23
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td id="sumExpenses"></td>
</tr>
</tfoot>
</table>
Fiddle https://jsfiddle.net/ey2gLp7t/
I am new to Js. I have a table that shows me 9 persons. I have added the number of days they are in the group. I am trying to create a function that counts per day +1 to this number. Has somebody an Idea how i can do that?
This is my Code:
<table style="width:100%">
<tr>
<th><input class="checkbox" type="checkbox"></th>
<th>Spieler</th>
<th>Rang</th>
<th>Tage</th>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>HELLFIRE944</td>
<td>Komandant</td>
<td>212</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>Backfischjoghurt</td>
<td>Ausführender Offizier</td>
<td>217</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>retoaba</td>
<td>Personaloffizier</td>
<td>210</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>chrisi_39</td>
<td>Rekrutierungsoffizier</td>
<td>210</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>salpo</td>
<td>Unteroffizier</td>
<td>212</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>Kaeltischerkriger</td>
<td>Unteroffizier</td>
<td>213</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>DnerYoo_sniper</td>
<td>Rekrut</td>
<td>39</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>panzerzockerundnoah</td>
<td>Rekrut</td>
<td>146</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>PanzaSintKuhlMinecraftLP</td>
<td>Rekrut</td>
<td>116</td>
</tr>
</table>
<footer class=footer>
<div class=footer>
<p class= footer-p>created by #Reto Keller</p>
</div>
</footer>
This will help you, it returns you the whole array of tableData values of Tage.
plunker link
function getAllTableDataValues() {
var row = $('table tr'); //get all table rows
var rowData = row.find('td:nth-child(4n)'); // get all the table data with Tage
var numberArray = [];
rowData.each(function() {
var value = $(this).html(); //get the value of td in string format array
value = Number(value);
value = value +1;
numberArray.push(value);
});
return numberArray;
}
getAllTableDataValues();
Actually how to automatically calculate subtotal depending the js spinner change, also sum them into grand total with jquery, I am newly to the jquery with operation function so any suggestion will be appreciated
Thanks
Warmly
Fiddle >>
<div class="table-responsive" id="bottom-table">
<table class="table table-striped">
<thead>
<tr>
<th>No</th>
<th>Part Number</th>
<th>Desc</th>
<th>Qty / Unit</th>
<th>Qty Needed</th>
<th>Het ( Rp )</th>
<th>Estimation Price</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>3DCam01</td>
<td>3D Camera</td>
<td>1</td>
<td><input class="spinner" value="1" readonly="readonly"></td>
<td>$1500.00</td>
<td><p class="subtotal"></p>Subtotal</td>
<td>Delete</td>
</tr>
<tr>
<td>2</td>
<td>USB02</td>
<td>External Hard Drive</td>
<td>1</td>
<td><input class="spinner" value="1" readonly="readonly"></td>
<td>$800.00</td>
<td>Subtotal</td>
<td>Delete</td>
</tr>
<tr>
<td>3</td>
<td>wristWear03</td>
<td>Wrist Watch</td>
<td>1</td>
<td><input class="spinner" value="1" readonly="readonly"></td>
<td>$300.00</td>
<td>Subtotal</td>
<td>Delete</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Total</td>
<td>Total Amount</td>
<td>Delete</td>
</tr>
</tbody>
</table>
</div>
Thanks
Warmly
you need to bind to the spin event to get the value entered then update the DOM accordingly
function quantity(price, multiplier) {
if (multiplier === 1) {
return '$' + price.toFixed(2);
}
return '$' + (price * multiplier).toFixed(2);
}
$( ".spinner" ).spinner({
min: 1,
spin: function (event, ui) {
var value = ui.value;
var $target = $(event.target);
var $priceCell = $target.parents('td').next('td');
var $subtotalCell = $priceCell.next('td');
$subtotalCell.text(quantity($priceCell.data('price'), value));
}
});
fiddle - http://jsfiddle.net/m6csdx51/1/
notice the addition of data-price to the price cells