Sort table from side menu - javascript

It might sounds weird.
I would like to know if it's possible to sort a table by clicking on the side menu link and not from the table header.
I know that we can sort, make pagination... inside the table by using some jQuery libraries.
But my request here is to sort from the side menu and not from the table header.
<table>
<thead>
<tr>
<th>blabla</th>
<th>blabla</th>
</tr>
</thead>
<tbody>
<tr>
<td>blabla</td>
<td>blabla</td>
</tr>
</tbody>
</table>

This might give u a idea on how to do it mate..
function sortColumn(c,n){
var rows = $('#mytable tbody tr').get();
rows.sort(function(a, b) {
var A = $(a).children('td').eq(n).text().toUpperCase();
var B = $(b).children('td').eq(n).text().toUpperCase();
if(A < B) {
return -1*c;
}
if(A > B) {
return 1*c;
}
return 0;
});
$.each(rows, function(index, row) {
$('#mytable').children('tbody').append(row);
});
}
var sln = 1;
$("ul li").click(function(){
sln *= -1;
var n = $("ul li").index(this);
sortColumn(sln,n);
});
Fiddle here

You can use tablesorter's sorton event:
$(document).ready(function() {
$("#mysortable").tablesorter();
$("#navigator div").click(function() {
var column = $(this).data("column") - 1;
$("#mysortable").trigger("sorton", [[[column, 0]]]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.19.1/js/jquery.tablesorter.min.js">
</script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.19.1/css/theme.default.css"/>
<div id="navigator" style="float:left; max-width:200px;">
<div data-column="1">Sort Column One</div>
<div data-column="2">Sort Column Two</div>
<div data-column="3">Sort Column Three</div>
</div>
<table id="mysortable" class="tablesorter" style="float:right; max-width:400px;">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>2</td>
<td>Z</td>
</tr>
<tr>
<td>C</td>
<td>3</td>
<td>Y</td>
</tr>
<tr>
<td>B</td>
<td>1</td>
<td>X</td>
</tr>
</tbody>
</table>

here is how
function sort_rows(col_num, ascending) {
var $rows = $('#'+table_id+' tr').not( function(i,e) {
return $(e).find('th').length > 0;
} );
var sort_values = [];
var indx_values = [];
$rows.each( function (i,e) {
sort_values.push( $(e).find('td:nth-child('+col_num+')').text() );
indx_values.push(sort_values.length-1);
} );
var ordering;
if (ascending) {
ordering = function (a,b) { return a < b; };
} else {
ordering = function (a,b) { return a > b; };
}
var k = 0, val = sort_values[0];
for(var i = sort_values.length-1; i > 0; i-=1) {
for(var j = i; j >= 0; j-=1) {
if (ordering(sort_values[j], val))
val = sort_values[j];
k = j;
}
}
var temp = sort_values[j];
sort_values[j] = sort_values[i];
sort_values[i] = temp;
var temp = indx_values[j];
indx_values[j] = sort_values[i];
indx_values[i] = temp;
}
list_$rows = [];
$rows.each( function (i,e) { list_rows.push($(e).clone()); } );
$rows.remove();
for(var i = 0; i < sort_values.length; i+=1) {
$('#'+table_id).append( list_$rows[indx_values[i]] );
}
}

Related

Re-order table columns in HTML dynamically with Javascript

I've a table in HTML looks like this:
Subjects
n1
n2
n3
subject1
10
0
0
subject2
0
5
20
<table>
<thead>
<tr>
<th class="subject">Subjects</th>
<th>n1</th>
<th>n2</th>
<th>n3</th>
</tr>
</thead>
<tbody>
<tr>
<th class="subject">subject1</th>
<td>10</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<th class="subject">subject2</th>
<td>0</td>
<td>5</td>
<td>20</td>
</tr>
</tbody>
</table>
Is there any thought or approach with javascript I could re-order columns in a specific order let order = ['n2','n1','n3']:
Subjects
n2
n1
n3
subject1
0
10
0
subject2
5
0
20
I've solved by turning the table into 2-dimensional array and sort it and turn it back into table HTML:
function tableToArray(tbl, opt_cellValueGetter) {
opt_cellValueGetter = opt_cellValueGetter || function(td) {
return td.textContent || td.innerText;
};
var twoD = [];
for (var rowCount = tbl.rows.length, rowIndex = 0; rowIndex < rowCount; rowIndex++) {
twoD.push([]);
}
for (var rowIndex = 0, tr; rowIndex < rowCount; rowIndex++) {
var tr = tbl.rows[rowIndex];
for (var colIndex = 0, colCount = tr.cells.length, offset = 0; colIndex < colCount; colIndex++) {
var td = tr.cells[colIndex],
text = opt_cellValueGetter(td, colIndex, rowIndex, tbl);
while (twoD[rowIndex].hasOwnProperty(colIndex + offset)) {
offset++;
}
for (var i = 0, colSpan = parseInt(td.colSpan, 10) || 1; i < colSpan; i++) {
for (var j = 0, rowSpan = parseInt(td.rowSpan, 10) || 1; j < rowSpan; j++) {
twoD[rowIndex + j][colIndex + offset + i] = text;
}
}
}
}
return twoD;
}
let order = ['n2', 'n1', 'n3', "Subjects"];
const sort2dArrayColumsByFirstRow = (array) => {
if (!Array.isArray(array)) return [];
const sortedFirstRow = array[0]
.map((item, i) => ({
v: item,
i: i
}))
.sort((a, b) => {
return order.indexOf(a.v) - order.indexOf(b.v);
});
return array.map((row) => row.map((_, i) => row[sortedFirstRow[i].i]));
};
function arrayToTable(columnNames, dataArray) {
var myTable = document.createElement('table');
var y = document.createElement('tr');
myTable.appendChild(y);
for (var i = 0; i < columnNames.length; i++) {
var th = document.createElement('th'),
columns = document.createTextNode(columnNames[i]);
th.appendChild(columns);
y.appendChild(th);
}
for (var i = 0; i < dataArray.length; i++) {
var row = dataArray[i];
var y2 = document.createElement('tr');
for (var j = 0; j < row.length; j++) {
myTable.appendChild(y2);
var th2 = document.createElement('td');
var date2 = document.createTextNode(row[j]);
th2.appendChild(date2);
y2.appendChild(th2);
}
}
document.querySelector('#tableEl').innerHTML = myTable.innerHTML;
}
let arr = tableToArray(document.querySelector('#tableEl'))
console.log('before:', arr)
let arrOrdered = sort2dArrayColumsByFirstRow(arr);
console.log('after:', arrOrdered);
arrayToTable(arrOrdered[0], arrOrdered.slice(1))
<table id="tableEl">
<thead>
<tr>
<th class="subject">Subjects</th>
<th>n1</th>
<th>n2</th>
<th>n3</th>
</tr>
</thead>
<tbody>
<tr>
<th class="subject">subject1</th>
<td>10</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<th class="subject">subject2</th>
<td>0</td>
<td>5</td>
<td>20</td>
</tr>
</tbody>
</table>
This is a good DOM question.
Tables are modified by the TABLE API.
https://html.spec.whatwg.org/multipage/tables.html
The TABLE element has THEAD, TFOOT, and TBODY elements. Use of these elements provides structure for your javascript. (Good job so far).
<table id="s-table">
<thead>
<tr>
<th class="subject">Subjects</th>
<th>n1</th>
<th>n2</th>
<th>n3</th>
</tr>
</thead>
<tbody>
<tr>
<th class="subject">subject1</th>
<td>10</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<th class="subject">subject2</th>
<td>0</td>
<td>5</td>
<td>20</td>
</tr>
</tbody>
</table>
Next, you'll need some javascript.
You'll also find insertBefore, and possibly before, and after Element methods handy.
https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
Get the TBODY element.
For each row, reorder(cell[i], cell[j]).
Let's start with
function resortTBody(tBody) {
const rows = tBody.rows;
for(let i = 0; i < tBody.rows.length; i++) {
reorderRow(rows[i]);
}
}
function reorderRow(row) {
let cells = row.cells;
row.insertBefore(cells[2], cells[1]);
}
This code has a hard-coded swap of cells. To reorder the cells to match a specific order, you'll need to modify reorderRow:
reorderRow(row, newOrder);
The TH's can be similarly reordered.
Design Notes: It's a good idea to minimize scope of identifiers. That is, put them in scope only as broad as it can be maximally justified.
If reorderRow is only needed for resortTbody, it can be restricted to private access.
let resortTBody = function(tBody) {
function resortTBodyInner(tBody) {
const rows = tBody.rows;
for(let i = 0; i < tBody.rows.length; i++) {
reorderRow(rows[i]);
}
}
function reorderRow(row) {
let cells = row.cells;
row.insertBefore(cells[2], cells[1]);
}
resortTBodyInner(tBody);
resortTBody = resortTBodyInner;
};
It might be desirable to maintain the column headers but resort their contents. That would require a subtle change to the approach.
It might be desirable to reset the table to its original state. All of that can be done.
The following one-liner will reorganize the columns in the desired order:
document.querySelectorAll("#tableEl tr").forEach(tr=>[...tr.children].forEach((_,i,a)=>tr.append(a[[0,2,1,3][i]])));
<table id="tableEl">
<thead>
<tr>
<th class="subject">Subjects</th>
<th>n1</th>
<th>n2</th>
<th>n3</th>
</tr>
</thead>
<tbody>
<tr>
<th class="subject">subject1</th>
<td>10</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<th class="subject">subject2</th>
<td>0</td>
<td>5</td>
<td>20</td>
</tr>
</tbody>
</table>

Wrong array method sort() logic

I Cannot understand the array method sort() logic. I had to write an eventListener for the two elements Age and Letter. By clicking on them we can sort our table by age and letter.
All works fine, but I see something strange in the sort() logic. By clicking on the Letter - table must sort by alphabet for elements in the column Letter. By clicking on the Age - table must sort by digits order for elements in the column Age. But it does not sort right.
tbody = document.getElementById('grid');
function tableSort(event) {
var target = event.target;
var action = target.getAttribute('data-type');
var arr = [].slice.call(grid.rows, 1);
var self = this;
this.number = function() {
arr.sort(function(a, b) { // sort by digits in the column "Age"
a.cells[0].innerHTML;
b.cells[0].innerHTML;
return a - b;
});
grid.appendChild(...arr);
}
this.string = function() {
arr.sort(function(a, b) { // sort by words in the column "Letter"
a.cells[1].innerHTML;
b.cells[1].innerHTML;
return a > b;
});
grid.appendChild(...arr);
}
if (action) {
self[action]();
}
}
tbody.addEventListener('click', tableSort);
th {
cursor: pointer;
}
<table id="grid">
<thead>
<tr>
<th data-type="number">Age</th>
<th data-type="string">Letter</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>BBBBB</td>
</tr>
<tr>
<td>12</td>
<td>AAAAA</td>
</tr>
<tr>
<td>1</td>
<td>DDDDD</td>
</tr>
<tr>
<td>9</td>
<td>CCCCC</td>
</tr>
<tr>
<td>2</td>
<td>KKKKK</td>
</tr>
</tbody>
</table>
<script>
</script>
Modified your code and got it working. Here if you need it:
function tableSort(event) {
var target = event.target;
var action = target.getAttribute("data-type");
var arr = [].slice.call(grid.rows, 1);
var self = this;
this.number = function() {
arr.sort(function(a, b) {
// sort by digits in the column "Age"
return Number(a.cells[0].innerHTML) - Number(b.cells[0].innerHTML);
});
arr.forEach(function(item, index) {
grid.appendChild(item);
});
};
this.string = function() {
arr.sort(function(a, b) {
// sort by words in the column "Letter"
var str1 = a.cells[1].innerHTML;
var str2 = b.cells[1].innerHTML;
return str1.localeCompare(str2);
});
arr.forEach(function(item, index) {
grid.appendChild(item);
});
};
if (action) {
self[action]();
}
}
tbody.addEventListener("click", tableSort);
How about this stackoverflow post Sorting HTML table with JavaScript for clarification and the original external article in which I found it with a full example?
Sorting tables with VanillaJS or JQuery
Example:
/**
* Modified and more readable version of the answer by Paul S. to sort a table with ASC and DESC order
* with the <thead> and <tbody> structure easily.
*
* https://stackoverflow.com/a/14268260/4241030
*/
var TableSorter = {
makeSortable: function(table){
// Store context of this in the object
var _this = this;
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th){
i = th.length;
}else{
return; // if no `<thead>` then do nothing
}
// Loop through every <th> inside the header
while (--i >= 0) (function (i) {
var dir = 1;
// Append click listener to sort
th[i].addEventListener('click', function () {
_this._sort(table, i, (dir = 1 - dir));
});
}(i));
},
_sort: function (table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
// Sort rows
tr = tr.sort(function (a, b) {
// `-1 *` if want opposite order
return reverse * (
// Using `.textContent.trim()` for test
a.cells[col].textContent.trim().localeCompare(
b.cells[col].textContent.trim()
)
);
});
for(i = 0; i < tr.length; ++i){
// Append rows in new order
tb.appendChild(tr[i]);
}
}
};
window.onload = function(){
TableSorter.makeSortable(document.getElementById("myTable"));
};
table thead th {
cursor: pointer;
}
<table id="myTable">
<thead>
<th data-type="string">Name</th>
<th data-type="number">Age</th>
</thead>
<tbody>
<tr>
<td>John</td>
<td>42</td>
</tr>
<tr>
<td>Laura</td>
<td>39</td>
</tr>
<tr>
<td>Fred</td>
<td>18</td>
</tr>
<tr>
<td>Bod</td>
<td>26</td>
</tr>
</tbody>
</table>

jquery .each loop odd behaviour

Hi I have the following code
html
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
<tr>
<td>3</td>
<td>Test3</td>
</tr>
</table>
script
var trArray = [];
var tdArray = [];
var reruiredObj = {"UserID":null,
"UserName":null
};
var first;
var second;
$('#tbPermission tr').each(function () {
$(this).find('td').each(function (index) {
//alert(index+'-'+ $(this).html());
//alert(index);
if(index == 0){
first = $(this).html();
}
else{
second = $(this).html();
}
//alert(JSON.stringify(reruiredObj));
});
alert(first+'-'+second)
reruiredObj['UserID'] = first;
reruiredObj['UserName'] = second;
trArray.push(reruiredObj);
});
alert(JSON.stringify(trArray));
Demo Here
My question why first and second in undefined in first alert, and why it is
[{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"},{"UserID":"3","UserName":"Test3"}]
my desired output is
[{"UserID":"1","UserName":"Test1"},{"UserID":"2","UserName":"Test2"},{"UserID":"3","UserName":"Test3"}]
The scope of your reruiredObj object is incorrect which is why you get the same object three times. Try this instead:
var trArray = [];
var tdArray = [];
var first;
var second;
$('#tbPermission tr:gt(0)').each(function () {
var reruiredObj = {
"UserID": null,
"UserName": null
};
first = $(this).find('td').eq(0).html();
second = $(this).find('td').eq(1).html();
reruiredObj['UserID'] = first;
reruiredObj['UserName'] = second;
trArray.push(reruiredObj);
});
console.log(JSON.stringify(trArray));
jsFiddle example
And the undefined values come from iterating over the first row which you don't want, and can ignore with tr:gt(0)
The first alert gives undefined because the first row of the table does not contain any td element.
To exclude the first row from the loop:
$('#tbPermission tr').each(function (i) {
if (i != 0) {
// execute ..
}
});
As for the array, try this in each loop:
var reruiredObj = { "UserID": first , "UserName":second };
Check the DEMO
Below works fine for me.
Since your first tr doesnt have td it gives undefined error. Try below one
<table id="tbPermission">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
<tr>
<td>3</td>
<td>Test3</td>
</tr>
</tbody>
</table>
<script>
$(function () {
var trArray = [];
var tdArray = [];
var reruiredObj = {"UserID":null,
"UserName":null
};
jsonObj = [];
var first;
var second;
$('#tbPermission tbody tr').each(function () {
$(this).find('td').each(function (index) {
//alert(index+'-'+ $(this).html());
//alert(index);
if(index == 0){
first = $(this).html();
}
else{
second = $(this).html();
}
//alert(JSON.stringify(reruiredObj));
});
alert(first+'-'+second)
item = {}
item ["UserID"] = first;
item ["UserName"] = second;
jsonObj.push(item);
});
console.log(jsonObj);
});
</script>
alert jsonObj. This gives the required result.

Iterate over table cells, re-using rowspan values

I have a simple HTML table, which uses rowspans in some random columns. An example might look like
A | B |
---|---| C
D | |
---| E |---
F | | G
I'd like to iterate over the rows such that I see rows as A,B,C, D,E,C, then F,E,G.
I think I can probably cobble together something very convoluted using cell.index() to check for "missed" columns in later rows, but I'd like something a little more elegant...
without jquery:
function tableToMatrix(table) {
var M = [];
for (var i = 0; i < table.rows.length; i++) {
var tr = table.rows[i];
M[i] = [];
for (var j = 0, k = 0; j < M[0].length || k < tr.cells.length;) {
var c = (M[i-1]||[])[j];
// first check if there's a continuing cell above with rowSpan
if (c && c.parentNode.rowIndex + c.rowSpan > i) {
M[i].push(...Array.from({length: c.colSpan}, () => c))
j += c.colSpan;
} else if (tr.cells[k]) {
var td = tr.cells[k++];
M[i].push(...Array.from({length: td.colSpan}, () => td));
j += td.colSpan;
}
}
}
return M;
}
var M = tableToMatrix(document.querySelector('table'));
console.table(M.map(r => r.map(c => c.innerText)));
var pre = document.createElement('pre');
pre.innerText = M.map(row => row.map(c => c.innerText).join('\t')).join('\n');
document.body.append(pre);
td {
border: 1px solid rgba(0,0,0,.3);
}
<table>
<tr>
<td colspan=2>A</td>
<td rowspan=2>B</td>
</tr>
<tr>
<td>C</td>
<td rowspan=3>D</td>
</tr>
<tr>
<td rowspan=2>E</td>
<td rowspan=4>F</td>
</tr>
<tr></tr>
<tr>
<td rowspan=2 colspan=2>G</td>
</tr>
<tr></tr>
<tr>
<td rowspan=3 colspan=3>H</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td colspan=3>I</td>
</tr>
</table>
Try this:
<table id="tbl">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="2" rowspan="2">A</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
Script:
var finalResult = '';
var totalTds = $('#tbl TR')[0].length;
var trArray = [];
var trArrayValue = [];
var trIndex = 1;
$('#tbl TR').each(function(){
var currentTr = $(this);
var tdIndex = 1;
trArray[trIndex] = [];
trArrayValue[trIndex] = [];
var tdActuallyTraversed = 0;
var colspanCount = 1;
$('#tbl TR').first().children().each(function(){
if(trIndex > 1 && trArray[trIndex - 1][tdIndex] > 1)
{
trArray[trIndex][tdIndex] = trArray[trIndex - 1][tdIndex] - 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex - 1][tdIndex];
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
else
{
if(colspanCount <= 1)
{
colspanCount = currentTr.children().eq(tdActuallyTraversed).attr('colspan') != undefined ? currentTr.children().eq(tdActuallyTraversed).attr('colspan') : 1;
}
if(colspanCount > 1 && tdIndex > 1)
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex][tdIndex - 1];
colspanCount--;
}
else
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).html();
tdActuallyTraversed++;
}
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
tdIndex++;
});
trIndex++;
});
alert(finalResult);
Fiddle
i am not sure about the performance, but it works well.
what I understood with your question is: You want to split the merged cell with same value and then iterate the table simply by row.
I've created a JSFiddle that will split the merged cells with the same value. Then you'll have a table that can be iterated simply by rows to get the desired output that you specified.
See it running here http://jsfiddle.net/9PZQj/3/
Here's the complete code:
<table id="tbl" border = "1">
<tr>
<td>A</td>
<td>B</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td>D</td>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
<br>
<div id="test"> </div>
Here's the jquery that is used to manipulate the table's data.
var tempTable = $('#tbl').clone(true);
var tableBody = $(tempTable).children();
$(tableBody).children().each(function(index , item){
var currentRow = item;
$(currentRow).children().each(function(index1, item1){
if($(item1).attr("rowspan"))
{
// copy the cell
var item2 = $(item1).clone(true);
// Remove rowspan
$(item1).removeAttr("rowspan");
$(item2).removeAttr("rowspan");
// last item's index in next row
var indexOfLastElement = $(currentRow).next().last().index();
if(indexOfLastElement <= index1)
{
$(currentRow).next().append(item2)
}
else
{
// intermediate cell insertion at right position
$(item2).insertBefore($(currentRow).next().children().eq(index1))
}
}
});
console.log(currentRow)
});
$('#test').append(tempTable);
You can use this Gist. It supports all the requirements by W3C, even "rowspan=0" (which seems to be only supported by Firefox).

Click table row and get value of all cells

I don't know JQuery, so I'm hoping there is a way to do this in pure Javascript.
I need to click on a table row and get the value of each cell in that row. Here is the format of my table:
<table class='list'>
<tr>
<th class='tech'>OCB</th>
<th class='area'>Area</th>
<th class='name'>Name</th>
<th class='cell'>Cell #</th>
<th class='nick'>Nickname</th>
</tr>
<tr onclick="somefunction()">
<td>275</td>
<td>Layton Installation</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
</table>
Is there anyway short of putting a unique ID to each cell?
There is no need to add ids or add multiple event handlers to the table. One click event is all that is needed. Also you should use thead and tbody for your tables to separate the heading from the content.
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
<table class='list'>
<thead>
<tr>
<th class='tech'>OCB</th>
<th class='area'>Area</th>
<th class='name'>Name</th>
<th class='cell'>Cell #</th>
<th class='nick'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>275</td>
<td>Layton Installation</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
</tbody>
</table>
Example:
http://jsfiddle.net/ZpCWD/
Check this fiddle link
HTML:
<table id="rowCtr" class='list'>
<thead>
<tr>
<th class='tech'>OCB</th>
<th class='area'>Area</th>
<th class='name'>Name</th>
<th class='cell'>Cell #</th>
<th class='nick'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>275</td>
<td>Layton Installation</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
</tbody>
</table>
JAVASCRIPT:
init();
function init(){
addRowHandlers('rowCtr');
}
function addRowHandlers(tableId) {
if(document.getElementById(tableId)!=null){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName('tr');
var ocb = '';
var area = '';
var name = '';
var cell = '';
var nick = '';
for ( var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
ocb = table.rows[this.i].cells[0].innerHTML;
area = table.rows[this.i].cells[1].innerHTML;
name = table.rows[this.i].cells[2].innerHTML;
cell = table.rows[this.i].cells[3].innerHTML;
nick = table.rows[this.i].cells[4].innerHTML;
alert('ocb: '+ocb+' area: '+area+' name: '+name+' cell: '+cell+' nick: '+nick);
};
}
}
}
var elements = document.getElementsByTagName('td');
for (var i =0; i < elements.length; i++) {
var cell_id = 'id' + i;
elements[i].setAttribute('id', cell_id);
}
Maybe put something like this in function your onclick links to from the tr?
$("tr").click(function () {
var rowItems = $(this).children('td').map(function () {
return this.innerHTML;
}).toArray();
});
This shows the row's first cell which is clicked according to dataTr.querySelectorAll("td")[0].innerText;
document.querySelector("#myTable").addEventListener("click",event => {
let dataTr = event.target.parentNode;
let dataRes = dataTr.querySelectorAll("td")[0].innerText;
console.log(dataRes);
});

Categories

Resources