get count of second td for each tr in my code - javascript

Excuse me (I cant write good English!), i want to get sum of count product for each category and append to category column.
how i can get sum of count of product for each tr and append to current tr in this CODE?
$(function() {
function groupTable($rows, startIndex, total) {
if (total === 0) {
return;
}
var i, currentIndex = startIndex,
count = 1,
lst = [];
var tds = $rows.find('td:eq(' + currentIndex + ')');
var ctrl = $(tds[0]);
lst.push($rows[0]);
for (i = 1; i <= tds.length; i++) {
if (ctrl.text() == $(tds[i]).text()) {
count++;
$(tds[i]).addClass('deleted');
lst.push($rows[i]);
} else {
if (count > 1) {
ctrl.attr('rowspan', count);
groupTable($(lst), startIndex + 1, total - 1)
}
count = 1;
lst = [];
ctrl = $(tds[i]);
lst.push($rows[i]);
}
}
}
groupTable($('#myTable tr:has(td)'), 0, 3);
$('#myTable .deleted').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<table id="myTable" border="1" cellpadding="3" cellspacing="0">
<tr>
<th>Category</th>
<th>Product</th>
</tr>
<tr>
<td>Category-1</td>
<td>Product-1</td>
</tr>
<tr>
<td>Category-1</td>
<td>Product-1</td>
</tr>
<tr>
<td>Category-1</td>
<td>Product-2</td>
</tr>
<tr>
<td>Category-1</td>
<td>Product-2</td>
</tr>
<tr>
<td>Category-2</td>
<td>Product-3</td>
</tr>
<tr>
<td>Category-2</td>
<td>Product-3</td>
</tr>
<tr>
<td>Category-2</td>
<td>Product-3</td>
</tr>
<tr>
<td>Category-2</td>
<td>Product-4</td>
</tr>
<tr>
<td>Category-3</td>
<td>Product-5</td>
</tr>
<tr>
<td>Category-3</td>
<td>Product-5</td>
</tr>
<tr>
<td>Category-3</td>
<td>Product-5</td>
</tr>
<tr>
<td>Category-4</td>
<td>Product-6</td>
</tr>
<tr>
<td>Category-4</td>
<td>Product-6</td>
</tr>
</table>

Related

Using jQuery or javascript, I'd like to get that how many element 500 in each column (1-4) of an html table is ? How should I do it?

Using jquery or javascript, I'd like to get that how many element 500 in each column (1-4) of an html table is ? How should I do it ?
<html>
<table>
<thead>
<tr>
<th>Column-1</th>
<th>Column-2</th>
<th>Column-3</th>
<th>Column-4</th>
</tr>
</thead>
<tbody>
<tr>
<td>500</td>
<td>200</td>
<td>500</td>
<td>200</td>
</tr>
<tr>
<tr>
<td>501</td>
<td>500</td>
<td>500</td>
<td>200</td>
</tr>
</tbody>
</table>
</html>
The table is look like this format:
Column-1 Column-2 Column-3 Column-4
500 200 500 200
501 500 500 500
... ... .... ...
I would like to get : column-1: 1, column-2:1, column-3:2 column-4: 1
automatic display the numbers of "500" of each column .
Solution
filter the 's in row out
Store the column when the text of a td is 500
Count how often the column occurs
let trArr = $("table tr")
let res = [];
for (let i = 0; i < trArr.length; i++) {
let childs = trArr[i].children;
for (let j = 0; j < childs.length; j++) {
if(childs[j].tagName !== "TH"){
if (childs[j].textContent === "500" ) {
res.push({
"column": j+1
});
}
}
}
}
let result = new Set();
for (let i = 0; i < res.length; i++) {
let counter = 0;
for (let j = 0; j < res.length; j++) {
if (res[i].column === res[j].column) {
counter++;
}
}
result.add(`Column ${[res[i].column]}: ${counter} x 500`);
}
let resString = "";
for(let i of result){
resString += i + "\n";
}
document.getElementById("BLA").innerHTML = resString;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<table>
<thead>
<tr>
<th>Column-1</th>
<th>Column-2</th>
<th>Column-3</th>
<th>Column-4</th>
</tr>
</thead>
<tbody>
<tr>
<td>500</td>
<td>200</td>
<td>500</td>
<td>200</td>
</tr>
<tr>
<tr>
<td>501</td>
<td>500</td>
<td>500</td>
<td>200</td>
</tr>
</tbody>
</table>
<p id="BLA"></p>
</html>

How do I sum the price column from HTML table using JavaScript?

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>

Delete a column

I have a table and I want to delete the column of a table. I have written a code to delete a particular column.
function deleteColumn(index) {
var total_row = document.getElementById("testBenchTable").rows;
for (var i=0; i<total_row.length; i++) {
if (total_row[i].cells.length > 1) {
total_row[i].deleteCell(index);
}
}
Now What should do so that I could select a particular column(header) and click on delete so that that particular column gets deleted?
You can refer this link for delete column http://www.mredkj.com/tutorials/tableaddcolumn.html
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
// 2006-08-21 - Created
// 2006-11-05 - Modified - head and body
function addColumn(tblId)
{
var tblHeadObj = document.getElementById(tblId).tHead;
for (var h=0; h<tblHeadObj.rows.length; h++) {
var newTH = document.createElement('th');
tblHeadObj.rows[h].appendChild(newTH);
newTH.innerHTML = '[th] row:' + h + ', cell: ' + (tblHeadObj.rows[h].cells.length - 1)
}
var tblBodyObj = document.getElementById(tblId).tBodies[0];
for (var i=0; i<tblBodyObj.rows.length; i++) {
var newCell = tblBodyObj.rows[i].insertCell(-1);
newCell.innerHTML = '[td] row:' + i + ', cell: ' + (tblBodyObj.rows[i].cells.length - 1)
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
<form>
<p>
<input type="button" value="add column" onclick="addColumn('tblSample')" />
<input type="button" value="delete column" onclick="deleteColumn('tblSample')" />
</p>
<table id="tblSample" border="1">
<thead>
<tr>
<th>[th] row:0, cell: 0</th>
<th>[th] row:0, cell: 1</th>
<th>[th] row:0, cell: 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>[td] row:0, cell: 0</td>
<td>[td] row:0, cell: 1</td>
<td>[td] row:0, cell: 2</td>
</tr>
<tr>
<td>[td] row:1, cell: 0</td>
<td>[td] row:1, cell: 1</td>
<td>[td] row:1, cell: 2</td>
</tr>
<tr>
<td>[td] row:2, cell: 0</td>
<td>[td] row:2, cell: 1</td>
<td>[td] row:2, cell: 2</td>
</tr>
</tbody>
</table>
</form>
To delete a particular column, you can use the cellIndex of the element (see: TableData cellIndex Property)
function deleteColumn(element) {
var idx = element.cellIndex;
var total_row = document.getElementById("testBenchTable").rows;
for (var i=0; i<total_row.length; i++) {
if (total_row[i].cells.length > 1) {
total_row[i].deleteCell(idx);
}
}
}
<table id="testBenchTable">
<tr>
<th onclick="deleteColumn(this)">Month</th>
<th onclick="deleteColumn(this)">Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
function deleteColumn(event) {
var index = event.target.cellIndex;
var total_row = document.getElementById("testBenchTable").rows;
for (var i=0; i<total_row.length; i++) {
if (total_row[i].cells.length > 1) {
total_row[i].deleteCell(index);
}
}
}
<table style="width:100%" id="testBenchTable">
<tr>
<th onclick="deleteColumn(event)">Firstname</th>
<th onclick="deleteColumn(event)">Lastname</th>
<th onclick="deleteColumn(event)">Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>

Sort date in dd/mm/yyyy format in html table using jquery function

I have an HTML table and one column is date values.How to sort the values in descending order in the first click and in ascending order in the second click while clicking on column heading Date
function getVal(elm, n) {
var v = $(elm).find('td').eq(n).text().toUpperCase();
var num = v.split(/ /)[0].replace(/[^\d]/g, '')
num = parseFloat(num);
if ($.isNumeric(num)) {
v = parseInt(num, 10);
}
return v;
}
var f = 1;
$(".table-sortable .column-head").find('span,img').click(function(event) {
event.preventDefault();
table = $(this).closest('table');
th = $(this).parent();
$(th).find('span,img').toggleClass('rotate');
f *= -1;
var n = th.prevAll().length;
console.log(n);
var rows = table.find('tbody tr').get();
rows.sort(function(a, b) {
var A = getVal(a, n);
var B = getVal(b, n);
if (A < B) {
return -1 * f;
}
if (A > B) {
return 1 * f;
}
return 0;
});
$.each(rows, function(index, row) {
table.children('tbody').append(row);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-sortable">
<thead>
<tr>
<th scope="col" class="column-head"><span>Date</span></th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td class="column-values">20/01/2015</td>
</tr>
<tr class="table-row">
<td class="column-values">20/02/2016</td>
</tr>
<tr class="table-row">
<td class="column-values">10/01/2017</td>
</tr>
<tr class="table-row">
<td class="column-values">08/01/2017</td>
</tr>
<tr class="table-row">
<td class="column-values">12/04/2013</td>
</tr>
<tr class="table-row">
<td class="column-values">12/03/2013</td>
</tr>
</tbody>
</table>
https://jsfiddle.net/bb4659av/
You can convert your date in YYYY/MM/DD format and then sort it using localeCompare.
function getVal(elm, n) {
var v = $(elm).find('td').eq(n).text().toUpperCase();
v = v.replace(/(..)\/(..)\/(....)/, '$3/$2/$1');
return v;
}
var f = 1;
$(".table-sortable .column-head").find('span,img').click(function(event) {
event.preventDefault();
table = $(this).closest('table');
th = $(this).parent();
$(th).find('span,img').toggleClass('rotate');
f *= -1;
var n = th.prevAll().length;
var rows = table.find('tbody tr').get();
rows.sort(function(a, b) {
var A = getVal(a, n);
var B = getVal(b, n);
return f * A.localeCompare(B);
});
$.each(rows, function(index, row) {
table.children('tbody').append(row);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-sortable">
<thead>
<tr>
<th scope="col" class="column-head"><span>Date</span></th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td class="column-values">20/01/2015</td>
</tr>
<tr class="table-row">
<td class="column-values">20/02/2016</td>
</tr>
<tr class="table-row">
<td class="column-values">10/01/2017</td>
</tr>
<tr class="table-row">
<td class="column-values">08/01/2017</td>
</tr>
<tr class="table-row">
<td class="column-values">12/04/2013</td>
</tr>
<tr class="table-row">
<td class="column-values">12/03/2013</td>
</tr>
</tbody>
</table>
Just as a comparison, here's a version using POJS once you have a cell in the column to sort. I think it will be a lot more efficient that the jQuery alternative.
"Ascending order" is ambiguous to me, I guess you want the newest dates at the top. To reverse the order, just reverse the comparison in the sort function.
/* Given a table cell, find the parent table and sort the first tbody's
** rows by the given column as dates in format dd/mm/yyyy. Sorts most
** recent date to top, oldest to bottom.
*/
function sortAsDate(cell) {
var col = cell.cellIndex,
table = cell.parentNode.parentNode.parentNode,
tbody = table.tBodies[0],
formatter = row => row.cells[col].textContent.split(/\D/).reverse().join('');
Array.from(tbody.rows)
.sort((a, b) => formatter(a).localeCompare(formatter(b)))
.reduceRight((acc, row) => tbody.appendChild(row), null);
}
<table class="table-sortable">
<thead>
<tr>
<th scope="col" class="column-head"><span onclick="sortAsDate(this.parentNode)">Date</span></th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row"><td class="column-values">20/01/2015</td></tr>
<tr class="table-row"><td class="column-values">20/02/2016</td></tr>
<tr class="table-row"><td class="column-values">10/01/2017</td></tr>
<tr class="table-row"><td class="column-values">08/01/2017</td></tr>
<tr class="table-row"><td class="column-values">12/04/2013</td></tr>
<tr class="table-row"><td class="column-values">12/03/2013</td></tr>
</tbody>
</table>

JS - Compare first row to other rows in table

I'm a completely newbie and looking for help.
Given the following table:
<table id="table">
<thead>
# FIRST ROW
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
</tr>
<tbody>
# SECOND ROW
<tr>
<td>Apple</td> --> should end with 'success' class
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td> --> should end with 'success' class
</tr>
# THIRD ROW
<tr>
<td>Pizza</td> --> should end with 'success' class
<td>Chicken</td>
</tr>
</tbody>
</table>
I would like to add class 'success' to every td in SECOND and THIRD rows whenever it matches any td in FIRST row (and only in FIRST ROW).
For now I came up with adding <td> values of first row to array and I'm not sure what steps should I take next (filter? for loop and '===' comparison?):
function myFunction() {
var tHeadersValues = [];
var tHeaders = document.getElementById("table").rows[0].cells;
for (var i = 0; i < tHeaders.length; i++) {
tHeadersValues.push(tHeaders[i].textContent);
}
return tHeadersValues;
}
Object.keys(tHeaders).map(key => tHeaders[key].textContent) transforms the td objects to an array with the containing text. The rest is straight forward:
function toValues(tHeaders) {
return Object.keys(tHeaders).map(function(key){
return tHeaders[key].textContent;
});
}
function myFunction() {
var rows = document.getElementById("results-table").rows;
var tHeadersValues = toValues(rows[0].cells);
for (var i = 1; i < rows.length; i++) {
var rowCells = rows[i].cells;
var values = toValues(rowCells);
for(var j=0;j<values.length;j++) {
if(values[j].length > 0 && tHeadersValues.indexOf(values[j]) > -1) {
rowCells[j].className = "success";
}
}
}
}
myFunction();
<style>
.success {
background-color: green;
}
</style>
<table id="results-table">
<thead>
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td>
</tr>
<tr>
<td>Pizza</td>
<td>Chicken</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
function myFunc(){
var tds = document.getElementsByTagName("td");
var hds = document.getElementsByTagName("th");
for(var i=0; i<tds.length; i++) {
var tdContent = tds[i].innerHTML;
if(tdContent.length > 0){
for(var j = 0; j<hds.length; j++) {
if(tdContent === hds[j].innerHTML) {
document.getElementsByTagName("td")[i].className = "success";
}
}
}
}
}
myFunc();
<style>
.success {
background-color: green;
}
</style>
<table id="results-table">
<thead>
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td>
</tr>
<tr>
<td>Pizza</td>
<td>Chicken</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>

Categories

Resources