Javascript table td's index - javascript

I use this code to get the index of a td in a table:
var tdIndex = this || (e || event).target;
var index = tdIndex.cellIndex;
The problem is that each row's index starts again at 0;
For example, the index of the first cell of the first row is 0. Similarly, The index of the first cell in the second row is also 0, and so on. I don't want the index to be reset to 0 for each row in a table. I want the index number to continue where it left off in the last cell of the previous row.

Ask your cell for it's parent row then get the rowIndex.
var rowIndex = e.target.parentElement.rowIndex;
The above code assumes that e is your event and target is your cell. Your (e || event) code isn't really necessary since you decide what your event object is named based on how your declare your event handler.

You'll need take into account the rowIndex property to get unique number for the cell in each.
Ideally each cell is defined in JS as a unique pair of (rowIndex,cellIndex)
var tdIndex = this || (e || event).target;
var index = tdIndex.cellIndex + 1000 * tdIndex.rowIndex;
note that you can use any number instead of 1000. It should just be greater than the maximum number of columns in the table

Something like this may do the trick and will work even if the number of cells is not the same on every row:
const table = document.querySelector('#table__base');
const cellOne = document.querySelector('#cellOne');
const cellTwo = document.querySelector('#cellTwo');
function getIndex(table, cell) {
let counter = 0;
for (let i = 0, len = cell.parentNode.rowIndex; i <= len; i += 1) {
let numberOfCellsInThisRow = (i === cell.parentNode.rowIndex) ? cell.cellIndex : table.rows[i].cells.length;
counter += numberOfCellsInThisRow;
}
return counter;
}
console.log(getIndex(table, cellOne));
console.log(getIndex(table, cellTwo));
<table id="table__base">
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
<td id="cellOne">9</td>
<td>10</td>
<td>11</td>
</tr>
<tr>
<td>12</td>
<td>13</td>
<td id="cellTwo">14</td>
<td>15</td>
<td>16</td>
<td>17</td>
</tr>
</table>

Related

How to find the largest count of <td>'s in a tree having multiple tables-JS

I have multiple tables in a dOM tree and I want to calculate the count of cells in every table.
code:
function tree() {
var table = document.getElementsByTagName('table');
for (var p = 0, tr; tr= table[p]; p++) {
for (var i =0, row; row = tr.rows[i]; i++) {
console.log(row.cells.length)
}
}
}
console.log(tree())
html:
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
<tr>
<td>and</td>
<td>second</td>
</tr>
</table>
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
</table>
In the first there are 4 cells and second there are 2 cells I want to print out the cells with largest count in a table. Hence the o/p will be:
4
my above js code, returns the total length of all the cells in a table. How can I traverse through the tables in a tree and find the largest count of cells?
thx!
Use querySelectorAll() to simplify this.
The below code will output 4 as in your OP. It's a simple modification to get the table with the most cells, which I suspect is what you meant (it's unclear).
// Get your list of all tables in the document.
const tables = document.querySelectorAll('table');
// Map list of tables to list of number of <td> elements.
const lengths =
Array.from(tables)
.map(table => table.querySelectorAll('td').length)
// Get the max of the list of lengths and log to console.
const max = Math.max(...lengths);
console.log(max);
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
<tr>
<td>and</td>
<td>second</td>
</tr>
</table>
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
</table>
You can try this to if you want :
const maxTdTable = ()=>{
var object;
var maxCol = 0;
$('table').each(function(element){
$(element).each(function(elem){
max = $(elem).childNodes.length;
maxCol = max>=maxCol ? max : maxCol ;
});
});
return {element : object,max : maxCol};
}

Javascript - Add new row to an HTML table that sums columns

With JavaScript, how can I add a new row to an HTML table that sums the values following the 2nd row.
Here's an example of what the above depicts:
Expected outcome:
Here is the html markup:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!DOCTYPE html>
<html>
<body>
<table border="1" style="width:100%">
<tr>
<td>Branch</td>
<td>Division</td>
<td>TallyA</td>
<td>TallyB</td>
<td>TallyC</td>
</tr>
<tr>
<td>Alpha</td>
<td>A101</td>
<td>6</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>Bravo</td>
<td>B102</td>
<td>16</td>
<td>8</td>
<td>10</td>
</tr>
<tr>
<td>Charlie</td>
<td>C103</td>
<td>11</td>
<td>17</td>
<td>21</td>
</tr>
</table>
</body>
</html>
</body>
</html>
Here is my solution. It may look verbose, but that's necessary with the complexity of this task.
First, I referenced the button and table elements. To prevent repeated clicks that will add more rows, and destroy the code, I created a boolean variable that checks whether the rows have already been summed. The code only runs the first time inside the if(!summedItems) conditional.
I then created new td elements for all five columns in the table and created text nodes for all but the division one.
I then created selectors and this is where it got tricky. The first row does not contain numerical value, so I had to query all rows from the second further. I did that with tr:nth-child(n+2).
I then need to find the third cell in each of these rows. The descendant or child selectors can be used for this. The full selector is tr:nth-child(n+2) td:nth-child(3). Repeat that for the next two, only increment the values inside td:nth-child.
Since we need to iterate through all these values, I created three separate arrays to store the values inside the third, fourth and fifth columns respectively. It's important to note that these values are of type string and they need to be converted to integers. To do that simply add a + sign before the string. Iterating over the number of elements in each query, I populated the arrays.
Now we need to add up all of these items, and we can do that with the reduce method.
Now add the textnodes to the cells, the cells to the row and finally the row to the table. Finally, set the summedItems variable to true to prevent crazy behavior.
var button = document.getElementById("total-items");
var table = document.getElementById("my-table");
var summedItems = false;
function sumItems() {
if (!summedItems) {
var row = document.createElement("tr");
var branch = document.createElement("td");
var division = document.createElement("td");
var tallyA = document.createElement("td");
var tallyB = document.createElement("td");
var tallyC = document.createElement("td");
var branchText = document.createTextNode("Total");
var sumA = document.querySelectorAll("tr:nth-child(n+2) td:nth-child(3)");
var sumB = document.querySelectorAll("tr:nth-child(n+2) td:nth-child(4)");
var sumC = document.querySelectorAll("tr:nth-child(n+2) td:nth-child(5)");
var aSums = [], bSums = [], cSums = [];
for (var i = 0; i < sumA.length; i++) {
aSums.push(+(sumA[i].innerHTML));
}
for (var i = 0; i < sumB.length; i++) {
bSums.push(+(sumB[i].innerHTML));
}
for (var i = 0; i < sumC.length; i++) {
cSums.push(+(sumC[i].innerHTML));
}
aSums = aSums.reduce((a,b) => a + b)
bSums = bSums.reduce((a,b) => a + b)
cSums = cSums.reduce((a,b) => a + b)
var tallyAText = document.createTextNode(aSums);
var tallyBText = document.createTextNode(bSums);
var tallyCText = document.createTextNode(cSums);
branch.appendChild(branchText);
tallyA.appendChild(tallyAText);
tallyB.appendChild(tallyBText);
tallyC.appendChild(tallyCText);
[branch, division, tallyA, tallyB, tallyC].forEach((e) => row.appendChild(e)
)
table.appendChild(row);
summedItems = true;
}
}
button.addEventListener("click", function() {
sumItems();
});
<table id="my-table" border="1" style="width:100%">
<tr>
<td>Branch</td>
<td>Division</td>
<td>TallyA</td>
<td>TallyB</td>
<td>TallyC</td>
</tr>
<tr>
<td>Alpha</td>
<td>A101</td>
<td>6</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>Bravo</td>
<td>B102</td>
<td>16</td>
<td>8</td>
<td>10</td>
</tr>
<tr>
<td>Charlie</td>
<td>C103</td>
<td>11</td>
<td>17</td>
<td>21</td>
</tr>
</table>
<button id="total-items">Total Items</button>
with jQuery:
$("table").each(function() {
var $table = $(this);
$row = $("<tr>")
$row.append("<td>Totale</td>")
var sums = [];
$table.find("tr").each(function(){
var index = 0;
$(this).find("td").each(function() {
if (!sums[index]) sums[index] = 0;
sums[index] += parseInt($(this).html());
index++;
})
})
for(var i=1;i<sums.length;i++) {
var el = sums[i];
if (isNaN(el)) el = "";
$row.append("<td>"+el+"</td>")
}
$table.append($row)
})
jsFiddle

for each table push to array

I'm a beginner with code,
I'm trying to run on this table and get the text from each .winner class and push it to an Array, so instead of getting:
["aa","aa","dd"]
I'm getting
["aaaadd","aaaadd","aaaadd"]
$(document).ready(function(){
var arr = [];
var winner = $('.winner').text() ;
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
console.log(arr);
});
HTML:
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">dd</td>
<td>cc</td>
<td>bb</td>
<td>aa</td>
</tr>
</table>
I guess something is wrong with my for loop
var arr = [];
$('table .winner').each(function () {
arr.push($(this).text());
})
Example
or version without class .winner
$('table').each(function () {
arr.push($(this).find('tr').eq(0).find('td').eq(1).text());
});
Example
$('table .winner') - returns 3 td's with class .winner
$(this).text() - get text from current element.
In your example $('.winner').text() returns text "aaaadd", then you get $('table').length (will be 3) and three times push the same text to arr
The sentence
var winner = $('.winner')
will give you an array of objects, so you need to loop each of them and call text() method for each one.
With this:
var winner = $('.winner').text();
You are getting a combined texts from all the td elements marked as winner (see docs here).
Then, for each table, to push this value to the array:
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
This is actually not necessary.
What you want is probably:
var winners = $('.winner');
for (var i = 0; i < winners.length(); ++i) {
arr.push(winners.eq(i).text());
}

table sorting - I want to move Child rows along with parent while sorting the parent row

Question is : I want to move Child rows along with parent while I sort the parent row.
I am using this js for sorting my table data. my html is like
<table>
<tr class="parent">
<th id="apple">Apple</th>
<th id="orange">Orange</th>
<th>Banana</th>
</tr>
<tr class="parent">
<td>Apple</td>
<td>Orange</td>
<td>Banana</td>
</tr>
<tr class="child">
<td>Apple 1</td>
<td>Orange 1</td>
<td>Banana 1</td>
</tr>
<tr class="child">
<td>Apple 2</td>
<td>Orange 2</td>
<td>Banana 2</td>
</tr>
<tr class="parent">
<td>Table</td>
<td>cHAIR</td>
<td>Mouse</td>
</tr>
<tr class="child">
<td>Table 1</td>
<td>cHAIR 1</td>
<td>Mouse 1</td>
</tr>
<tr class="child">
<td>Table 2</td>
<td>cHAIR 2</td>
<td>Mouse 2</td>
</tr>
</table>
js is like this:
jQuery.fn.sortElements = (function(){
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function(){return this;};
var placements = this.map(function(){
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing its original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i){
placements[i].call(getSortable.call(this));
});
};
})();
Adding another JS:
$('#apple, #orange')
.each(function(){
var th = $(this),
thIndex = th.index(),
inverse = false;
th.click(function() {
// sorting classes don't work here b/c this function gets called repeatedly - moved to afterRequest: function
table.find('tr.parent td').filter(function(){
return $(this).index() === thIndex;
}).sortElements(function(a, b){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function(){
// parentNode is the element we want to move
return this.parentNode;
// this.parentNode
});
inverse = !inverse;
});
});
Assume your sortElements work correctly.Create a association before you sort,and append behind the parent after sort:
//the sort logic
//add association before sort
$(".parent").each(function(i,node){
var child=$(this).nextUntil('.parent');
$(this).data("child-node",child);
//sort
}).sortElements(function(a,b){
var lengthb= $(b).children("td").first().text().length
var lengtha= $(a).children("td").first().text().length
return lengthb-lengtha;
//append child
}).each(function(i,node){
var child=$(this).data("child-node");
$(this).after(child);
});
check code http://jsfiddle.net/zHbDm/
I'm not sure if I understand your question correctly.
This can be used to select all of the next rows that are children.
$(".parent").nextUntil($("tr").not(".child"))
You can also include the parent in the selector by adding .addBack()
$(".parent").nextUntil($("tr").not(".child")).addBack()
Since you are already building on to jQuery, I would suggest you look into DataTables jQuery plugin since they already do much of this type of work for you. You just have to do configuration.

How to append a row in table using javascript

I want to append a new row in my table using Javascript but the new row should be like my previous rows.
I am using CSS to format my rows.
If you are using jQuery it will be something like this:
$(document).ready(function() {
$("table tr:last").clone().appendTo("table");
})
Replacing table with the id or class of your table (unless you only plan to have one table).
Using good old Node.cloneNode(deep) along with HTMLTableElement.rows:
HTML:
<table id="foo">
<tbody id="bar">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
JS:
var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var rows = foo.rows;
var lastRow = rows[rows.length-1];
var newRow = cloneRow(lastRow, true, bar);
function cloneRow(row, append, parent)
{
var newRow = row.cloneNode(true);
if(append)
{
if(parent)
{
parent.appendChild(newRow);
}
}
return newRow;
}
For comparison's sake, here's my code juxtaposed against the jQuery answer: http://jsperf.com/dom-methods-vs-jquery-with-tables
Let's say that your row has a css style of .row
So you could just use DOM methods to create a new tr, add the class="row" then add the appropriate amount of td
Here is a solution that avoids the use of the cloneNode method, and that do not copy the content, data or events of the previous last row, just its CSS attributes and class names.
The new row will have the same number of cell as the previous last row.
var lastRow = myTable.rows[myTable.rows.length-1];
var newRow = myTable.insertRow();
newRow.className = lastRow.className;
newRow.style.cssText = lastRow.style.cssText;
for (var i = 0; i < lastRow.cells.length; i++) {
var newCell = newRow.insertCell(i);
newCell.className = lastRow.cells[i].className;
newCell.style.cssText = lastRow.cells[i].style.cssText;
}

Categories

Resources