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)
Related
<table>
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
In the above code, I want to know the position of Aman using its id
You can try something like this:
html:
<table id="myTable">
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
js:
function getIdFromTable(searchValue)
{
var t = document.getElementById("myTable");
var trs = t.getElementsByTagName("tr");
var tds = null;
for (var i=0; i<trs.length; i++)
{
tds = trs[i].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
if (tds[n].innerText === searchValue) {
return tds[n].id;
}
}
}
}
getIdFromTable('Aman'); // will return 2
Easiest way to find position by id would be using prevAll().length. Something like this:
function findPositionById(id){
return $('#mytable').find('#'+id).prevAll().length
}
console.log('Adi Position', findPositionById(1));
console.log('Aman Position', findPositionById(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<table id="mytable">
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
I am new in Javascript, I have an array, and want to print it in the table td.
This is my array:
array = [100, 200, 300];
This is my table:
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
I want to print my array in the td with class name 'result'
You can use querySelectorAll() and Node.textContent:
const array = [100, 200, 300];
const elements = [...document.querySelectorAll('.result')];
for(let i = 0; i < array.length; i++) {
elements[i].textContent = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Just iterate over the array and use the current index for the HTML element as well.
Possible ES5-only solution:
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
document.getElementsByClassName("result")[i].innerHTML = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Note: You need an equal amount of array elements and elements with the .result class.
Assign an id attribute to the table tag, id = "tab". Then add the below javascript code
pointer=0
arr=[100,200,300];
// selecting all the tags having result as class name
var nodes=document.getElementById("tab").getElementsByClassName("result");
arr.forEach((ele)=>{nodes[pointer].innerHTML=ele;pointer+=1});
Look at this example:
I use querySelectorAll
It considers the case if the array elements and the quantity of rows are diffrerent.
Also added '.myTable' to prevent target other '.result' nodes out of the selected table.
Hope it helps.
<table class="myTable">
<th> Result</th>
<tbody>
<tr><td> My result 1</td><td class='result'></td></tr>
<tr><td> My result 2</td><td class='result'></td></tr>
<tr><td> My result 3</td><td class='result'></td></tr>
<tr><td> My result 4</td><td class='result'></td></tr>
</tbody>
</table>
<script>
const array = [100, 200, 300];
const rows = document.querySelectorAll('.myTable .result') // <-- I added '.myTable' to prevent target other '.result' nodes out of the selected table
rows.forEach((row, i) => {
if (array[i]) row.innerHTML = array[i] // <-- I replace the innerHTML if the array has content at that index
});
</script>
You can do this,
var result = document.getElementsByClassName("result")
var array = [100,200,300]
for (var i=0;i<result.length;i++){
result[i].innerHTML = array[i];
}
Demo
Hope this helps you... No need to update table according to array data....
Table code:
<table>
<th colspan="2" >Result</th>
<tbody id="myTableBody"></tbody>
</table>
JavaScript code:
<script>
var tableRef = document.getElementById('myTableBody');
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
tableChild = document.createElement('tr');
tableChild.innerHTML = "<td> My result "+(i+1)+"</td><td class='result'>"+array[i]+"</td>";
tableRef.appendChild(tableChild);
}
</script>
Example: https://codepen.io/Nishanth_V/pen/rEZmxN
var el = document.getElementsByClassName('result');
var array = [100, 200, 300];
for(var i =0 ; i < el.length && i < array.length; ++i) {
el[i].innerHTML = array[i];
}
You have to replace ' by " and add numbers to your class , after that your code with look like this:-
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class="result1"></td>
</tr>
<tr>
<td> My result 2</td>
<td class="result2"></td>
</tr>
<tr>
<td> My result 3</td>
<td class="result3"></td>
</tr>
</tbody>
</table>
Your JavaScript code will look like this:-
<script>
var array = [100, 200, 300];
array.foreach(function (item, index){
var resultNum = index + 1;
document.getElementByClassName("result" + resultNum).innerHTML = item;
});
</script>
Edit
So many good answers and all of them work! Thanks a lot guys :) I wish I could mark all of them as solved!
----
Good day
Let's say I have these 2 text inputs:
<input type="text" id="plt_quantity_sum"/> <!-- this should calculate the "#quantity" where each "#uom_value" is "PLT" -->
<input type="text" id="crt_quantity_sum"/><!-- this should calculate the "#quantity" where each "#uom_value" is "CRT" -->
Let's assume the following scenario:
<table>
<tbody>
<tr>
<th>Item Name</th>
<th id="uom_value">UOM</th>
<th id="qty">Quantity</th>
</tr>
<tr>
<td>Item 1</td>
<td id="uom_value">PLT</td>
<td id="qty">5</td>
</tr>
<tr>
<td>Item 2</td>
<td class="uom_value">PLT</td>
<td id="qty">3</td>
</tr>
<tr>
<td>Item 3</td>
<td id="uom_value">CRT</td>
<td id="qty">2</td>
</tr>
<tr>
<td>Item 4</td>
<td id="uom_value">CRT</td>
<td id="qty">3</td>
</tr>
</tbody>
</table>
<input type="text" id="plt_quantity_sum" />
<input type="text" id="crt_quantity_sum" />
What needs to happen:
When the document loads, or via a button click; the quantity of "#plt_quantity_sum" and "#crt_quantity_sum" should be calculated based on their respective quantities and "UOM" values.
Some Javascript I had in mind which should clarify what exactly needs to happen:
$(document).ready(function(){
if (document.getElementById("#uom_value").value == "PLT"){
document.getElementById("#plt_quantity_sum").value == (sum of #qty);
}
else if (document.getElementById("#uom_value").value == "CRT"){
document.getElementById("#crt_quantity_sum").value == (sum of #qty);
}
});
Thanks for reading and I would greatly appreciate any help.
You just need declare two variables crtQtySum and pltQtySum for the two sums and initialize them to 0, then loop over the tds and check if it's crt or plt and updtae your variables accordingly:
$(document).ready(function() {
var crtQtySum = 0;
var pltQtySum = 0;
$(".uom_value").each(function() {
if ($(this).text() === "CRT") {
crtQtySum += parseInt($(this).next("td.qty").text());
} else if ($(this).text() === "PLT") {
pltQtySum += parseInt($(this).next("td.qty").text());
}
});
$("#plt_quantity_sum").val(pltQtySum);
$("#crt_quantity_sum").val(crtQtySum);
});
$(document).ready(function() {
var crtQtySum = 0;
var pltQtySum = 0;
$(".uom_value").each(function() {
if ($(this).text() === "CRT") {
crtQtySum += parseInt($(this).next("td.qty").text());
} else if ($(this).text() === "PLT") {
pltQtySum += parseInt($(this).next("td.qty").text());
}
});
$("#plt_quantity_sum").val(pltQtySum);
$("#crt_quantity_sum").val(crtQtySum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Item Name</th>
<th class="uom_value">UOM</th>
<th class="qty">Quantity</th>
</tr>
<tr>
<td>Item 1</td>
<td class="uom_value">PLT</td>
<td class="qty">5</td>
</tr>
<tr>
<td>Item 2</td>
<td class="uom_value">PLT</td>
<td class="qty">3</td>
</tr>
<tr>
<td>Item 3</td>
<td class="uom_value">CRT</td>
<td class="qty">2</td>
</tr>
<tr>
<td>Item 4</td>
<td class="uom_value">CRT</td>
<td class="qty">3</td>
</tr>
</tbody>
</table>
PLT:<input type="text" id="plt_quantity_sum" readonly/></br>
CRT:<input type="text" id="crt_quantity_sum" readonly/>
Note:
I used readonly attribute with the inputs, as they're just used to display the sums so they can't be modified, but we could just used a block element for that like div or span.
You can try this code. I ve didnt test it.
var plt_count = 0;
var crt_count = 0;
$(".uom_value").each(function() {
if($(this).html === 'PLT'){
plt_count += parseInt($(this).closest('.qty').html());
}
if($(this).html === 'CRT'){
crt_count += parseInt($(this).closest('.qty').html());
}
});
$("#plt_quantity_sum").val(plt_count);
$("#crt_quantity_sum").val(crt_count);
Apart from correcting the spelling mistakes that Hamza pointed out, I'd say you should basically iterate through the elements given its class name document.getElementsByClassName('.someclass') and then store and sum the value of each one of its siblings with class '.qty'.
Then you take that value and use it to populate the input you want.
Hope that helps ;)
This can be done using so many method, this is one of them :
$(document).ready(function(){
var sum_PLT = 0, sum_CRT = 0;
$('table > tbody > tr').each(function() {
tr = $(this)[0];
cells = tr.cells;
if(cells[0].textContent != "Item Name"){//To exclude the <th>
if(cells[1].textContent == "PLT")
sum_PLT += parseInt(cells[2].textContent);
else
sum_CRT += parseInt(cells[2].textContent);
}
});
$("#plt_quantity_sum").val(sum_PLT);
$("#crt_quantity_sum").val(sum_CRT);
});
This is a working jsFiddle.
You might want to try this code.
<script>
$(document).ready(function(){
var plt_qty = 0;
var crt_qty = 0;
$('.uom_value').each(function(){
if ($(this).text() === 'PLT' ) {
plt_qty = plt_qty + parseInt($(this).parent().find('.qty').text());
}else if ($(this).text() === 'CRT' ) {
crt_qty = crt_qty + parseInt($(this).parent().find('.qty').text());
}
});
$("#plt_quantity_sum").val(plt_qty);
$("#crt_quantity_sum").val(crt_qty);
});
</script>
Note : remove class uom_value in <th class="uom_value">UOM</th>.
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);
});
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