How do I use themes with jsPDF-AutoTable? - javascript

I don't get how I use the themes for jsPDF-AutoTable. . .
This is my Code to generate the PDF:
function tbl1ToPDF(){
var table = tableToJson($('#tbl1').get(0));
var doc = new jsPDF('l','pt','letter',true);
$.each(table, function(i, row){
$.each(row, function(j,cell){
if(i == 0)
{
doc.cell(10,10,150,50,cell,i, 'center');
}
else
{
doc.cell(10,10,150,120,cell,i,'center');
}
});
});
doc.save('Sofort.pdf');
}
And this is my tableToJson function:
function tableToJson(table) {
var data = [];
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}
data.push(headers);
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
My Table is dynamic. I generate it after pressing a Button but the struct of the Table looks like this:
<h3>Header</h3>
<table id="tbl1">
<thead>
<tr>
<th>Nr</th>
<th>Name</th>
<th>Unit</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>test</td>
<td>test</td>
</tr>
<tr>
<td>2</td>
<td>test</td>
<td>test</td>
</tr>
</tbody>
</table>
<input type="button" onclick="tbl1ToPDF" value="download">
Can you please help me applying a theme to my PDF? I never did this before and I really need help!
Thanks you!

In order to use jsPDF-Autotable plugin you need to call it inside the code like so:
var doc = new jsPDF();
doc.autoTable();
Once you called autoTable, you can apply some option to it like "theme" this way:
doc.autoTable({theme: 'grid'});
For example, I have an HTML table (3 columns) with id = "table-report-p2p"
I get the data from it with autoTableHtmlToJson() and then I applied some options.
This is the code that works for me:
var elem = document.getElementById("table-report-p2p");
var res = doc.autoTableHtmlToJson(elem);
doc.autoTable(res.columns, res.data, {
theme: 'grid',
startY: 150,
margin: {horizontal: 10},
pageBreak: 'auto',
rowPageBreak: 'avoid',
columnStyles: {0: {cellWidth: 35, minCellHeight: 53},1: {cellWidth: 70},2: {cellWidth: 84}}
});

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>

How do I insert certain values of an array as a CSS style property for a <td> in a dynamic table?

I have a script that collects data from an array and uses these to generate a dynamic table. Some of these values in the array are Font Awesome styles.
My existing script inserts all the values in the array into each table cell.
The intention is for the Font Awesome style values to be inserted as a cell style, during the rendering of the table.
In the code below, notice that the array properties for paymentStatus stores a CSS Font Awesome style value.
var array = [{
amount: 12,
payersNumber: 1245,
paymentStatus: class="fas fa-exclamation-triangle"
}];
table = document.getElementById("table");
var currentTransaction;
var keys = ["payersNumber", "amount", "paymentStatus"];
for (var i = 0; i < array.length; i++) {
console.log("Number of transactions: " + array.length);
var newRow = table.insertRow(table.length);
currentTransaction = array[i];
for (var b = 0; b < keys.length; b++) {
var cell = newRow.insertCell(b);
cell.innerText = currentTransaction[keys[b]];
}
}
How do I get the paymentStatus values to get inserted into the table as the style for each <th>Status</th> column?
Find below the HTML table that my existing code geneates:
<table id="table" border="1">
<tr>
<th>Amount</th>
<th>Number</th>
<th>Status</th>
</tr>
</table>
<tr>
<td> 12 </td>
<td> 1245 </td>
<td> class="fas fa-exclamation-triangle" </td>
</tr>
For the Font Awesome style to successfully be put in effect, it needs to be inserted into the <td> </td> as a class style.
The desired effect would, therefore, look like this:
<table id="table" border="1">
<tr>
<th>Amount</th>
<th>Number</th>
<th>Status</th>
</tr>
<tr>
<td>12</td>
<td>1245</td>
<td class="fas fa-exclamation-triangle"></td>
</tr>
</table>
Inside the nested for-loop you can make a distinction based on the current value of keys[b]. If it's paymentStatus add an <i> tag with the css for the font awesome exclamation mark and use the .innerHTML property of the cell. If it's something else just assign the appropriate text to the .innerText proeprty.
var array = [{
amount: 12,
payersNumber: 1245,
paymentStatus: "okay"
}, {
amount: 24,
payersNumber: 3345,
paymentStatus: "okay"
}, {
amount: 45,
payersNumber: 4534,
paymentStatus: "not okay"
}];
table = document.getElementById("table");
var currentTransaction;
var keys = ["payersNumber", "amount", "paymentStatus"];
for (var i = 0; i < array.length; i++) {
var newRow = table.insertRow(table.length);
currentTransaction = array[i];
for (var b = 0; b < keys.length; b++) {
var cell = newRow.insertCell(b);
if (keys[b] == "paymentStatus") {
cell.innerHTML = "<i class='fas fa-exclamation-triangle'></i>" + currentTransaction[keys[b]];
} else {
cell.innerText = currentTransaction[keys[b]];
}
}
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.10.0/css/all.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.10.0/css/v4-shims.css">
<table id="table" border="1">
<tr>
<th>Number</th>
<th>Amount</th>
<th>Status</th>
</tr>
</table>
You can use classList.add method to add css class to HTML element as follows:
for (var b = 0; b < keys.length; b++) {
var cell = newRow.insertCell(b);
if (keys[b] == 'paymentStatus') {
let className = '';
// it is assumed that paymentStatus value format is consistent
const classNameArr = currentTransaction[keys[b]].split('=');
if (classNameArr.length === 2) {
className = classNameArr[1];
cell.classList.add(className);
}
} else {
cell.innerText = currentTransaction[keys[b]];
}
}

Conversion of javascript to jquery (getelementbyid, tagname, innertext, innerhtml)

I have some code written in javascript n when I am trying to convert in jQuery I am getting error.
var holder = document.getElementById('filedetails')
, rows = holder.getElementsByTagName('tr')
setSuccess = function(filename) {
if (holder != null) {
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (cells[0].innerText == filename && cells[3].innerText != "error!") {
cells[3].innerHTML = "<a href='#' class='file-delete ss-delete no-click'></a>";
}
}
}
}
I tried
var holder = $('#filedetails"),
rows = $('#filedetails tr")
I am not sure what to do with innertext and innerhtml.
<div data-behavior="delete-process" id="holder">
<table>
<thead>
<tr>
<th class="medium-5">Name</th>
<th class="medium-3">Size</th>
<th class="medium-3">Type</th>
<th class="medium-1"></th>
</tr>
</thead>
<tbody id="filedetails">
<tr data-filesize="1.4" data-filename="Sample Image.jpg">
<td><strong>Sample_Image</strong></td>
<td class="nodesize">1.4 MB</td>
<td>JPG</td>
<td class="file-loading"></td></tr>
</tbody>
</table>
<div class="margin bottom large text-center drag-desc">drag and drop files here.</div>
</div>
Here is a "jqueryized" version of your code
var holder = $('#filedetails'),
rows = holder.find('tr');
var setSuccess = function(filename) {
rows.each(function() {
var cells = $(this).find('td');
if (cells.eq(0).text() == filename && cells.eq(3).text() != "error!") {
cells.eq(3).html("<a href='#' class='file-delete ss-delete no-click'></a>");
}
});
};
setSuccess("Sample_Image");
Alternate that just uses the rows:
var rows = $('#filedetails').find('tr');
var setSuccess = function(filename,useme) {
useme.each(function() {
var cells = $(this).find('td');
if (cells.eq(0).text() == filename && cells.eq(3).text() != "error!") {
cells.eq(3).html("<a href='#' class='file-delete ss-delete no-click'>freebeer</a>");
}
});
};
setSuccess("Sample_Image", rows);
To NOT use a positional table element, use a class and filter by that within the TD cells as here: This assumes one use of a class per row.
var rows = $('#filedetails').find('tr');
var setSuccess = function(filename, useme) {
useme.each(function() {
var cells = $(this).find('td');
if (cells.filter('.file-name').text() == filename
&& cells.filter('.file-loading').text() != "error!") {
cells.filter('.file-loading')
.html("<a href='#' class='file-delete ss-delete no-click'>noclick</a>");
}
});
};
setSuccess("Sample_Image", rows);
Fiddl https://jsfiddle.net/MarkSchultheiss/0fx2jms7/2/
Check the following code snippet
$(document).ready(function(){
var holder = $("#filedetails")
, rows = holder.find('tr');
var rowsLength=rows.Length;
var setSuccess = function(filename) {
if (holder != null) {
var j=rows.length;
for (var i=0; i < j; ++i) {
var cells = $(rows[i]).find('td');
var filename=$('.filename');
var file=$('.file');
if (filename.text() == filename && file.text() != "error!")
{
var aElement=$("<a/>");
aElement.href="#";
aElement.class="file-delete ss-delete no-click";
file.html(aElement);
}
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-behavior="delete-process" id="holder">
<table>
<thead>
<tr>
<th class="medium-5">Name</th>
<th class="medium-3">Size</th>
<th class="medium-3">Type</th>
<th class="medium-1"></th>
</tr>
</thead>
<tbody id="filedetails">
<tr data-filesize="1.4" data-filename="Sample Image.jpg">
<td class="filename"><strong>Sample_Image</strong></td>
<td class="nodesize">1.4 MB</td>
<td>JPG</td>
<td class="file-loading file"></td></tr>
</tbody>
</table>
<div class="margin bottom large text-center drag-desc">drag and drop files here.</div>
</div>
Hope this helps

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