create table from jsp in javascript - javascript

I have the following table with the columns shown in the code below (in jsp).
I want this same table to be done in javascript, where list in my case will be a json array of objects.
Can you kindly help me with this?
<table border="1" width="90%">
<tr>
<th>Id</th>
<th>Name</th>
<th>Password</th>
<th>Email</th>
<th>Sex</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th></tr>
<c:forEach items="${list}" var="u">
<tr><td>${u.getId()}</td>
<td>${u.getName()}</td>
<td>${u.getPassword()}</td>
<td>${u.getEmail()}</td>
<td>${u.getSex()}</td>
<td>${u.getCountry()}</td>
<td>Edit</td>
<td>Delete</td></tr>
</c:forEach>
</table>

The most simplest thing you can try is something like that (if i understood you correctly):
let table = document.getElementById("my-table");
let list = [{
"id":1,
"name":"Jhon",
"password":"doejhon#",
"email":"jhondoe#doe.com",
"sex":"male",
"country":"USA"
},
{
"id":2,
"name":"Lisa",
"password":"w87e8c8787%",
"email":"lisa#doe.com",
"sex":"female",
"country":"UK"
}];
list.forEach(item=>{
let child = document.createElement("tr");
child.innerHTML = `<td>${item.id}</td><td>${item.name}</td><td>${item.password}</td><td>${item.email}</td><td>${item.sex}</td><td>${item.country}</td><td>-</td><td>-</td>`;
table.appendChild(child);
})
<table border="1" width="90%" id="my-table">
<tr>
<th>Id</th>
<th>Name</th>
<th>Password</th>
<th>Email</th>
<th>Sex</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th></tr>
</table>
<!--
<c:forEach items="${list}" var="u">
<tr><td>${u.getId()}</td>
<td>${u.getName()}</td>
<td>${u.getPassword()}</td>
<td>${u.getEmail()}</td>
<td>${u.getSex()}</td>
<td>${u.getCountry()}</td>
<td>Edit</td>
<td>Delete</td></tr>
</c:forEach>
-->

Here is one approach, demoing with a smaller set of fields.
It is not entirely clear what the links for Edit/Delete are supposed to be. Here, we leave it as a link to a JSP.
let table = document.createElement('TABLE');
let header = document.createElement('TR');
let fields = [ 'Id', 'Name', 'Password', 'Edit' ];
let cell;
for (var i=0; i<fields.length; i++) {
cell = document.createElement('TH');
cell.innerHTML = fields[i];
header.appendChild(cell);
}
table.appendChild(header);
let data = [
{
'Id': 'someId',
'Name': 'some name',
'Password': 'some encrypted password',
'Edit': "<a href='editform.jsp?id=someId'>Edit</a>"
},
{
'Id': 'anotherId',
'Name': 'some other name',
'Password': 'some other encrypted password',
'Edit': "<a href='editform.jsp?id=anotherId'>Edit</a>"
}
];
let rowData;
let fieldName;
for (i=0 ; i<data.length ; i++) {
let row = document.createElement('TR');
rowData = data[i];
for (var j=0; j<fields.length; j++) {
fieldName = fields[j];
cell = document.createElement('TD');
cell.innerHTML = rowData[fieldName];
row.appendChild(cell);
}
table.appendChild(row);
}
let body = document.querySelector('BODY');
body.appendChild(table);

Related

Javascript loop table row working with rowspan and tr

I have table that need to custom with my JS in loop.
Below is the demo. What I need the final result is like this:
Is there any trick how to achieve as my result needed?
var jsonStr = {
  "data": [
    {
      "data2": [
        {
          "partNo": "ABC",
          "plan": "120"
        },
        {
          "partNo": "DEF",
          "plan": "50"
        }
      ],
      "lineID": "1"
    },
    {
      "data2": [
        {
          "partNo": "FAB",
          "plan": "75"
        }
      ],
"lineID": "2"
    }
  ]
};
for(var i=0; i<jsonStr.data.length; i++) {
var line = "LINE " + jsonStr.data[i].lineID;
var element = `<tr><td>${line}</td></tr>`;
$(".tbl1 tbody").append(element);
for(var j=0; j<jsonStr.data[i].data2.length; j++) {
var partNo = jsonStr.data[i].data2[j].partNo;
//console.log(partNo);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tbl1" border="1">
<thead>
<th>Line</th>
<th>Part No.</th>
</thead>
<tbody></tbody>
</table>
<p>
It should be like this:
<table border="1">
<thead>
<th>Line</th>
<th>Part No.</th>
</thead>
<tbody>
<tr>
<td rowspan="2">LINE 1</td>
<td>ABC</td><tr>
<td>DEF</td>
</tr>
<tr>
<td rowspan="1">LINE 2</td>
<td>FAB</td>
</tr>
</tbody>
</table>
This is an approach using Array.forEach over the obj.data property to feed a target table tbody using the rowspan strategy.
Each time a new entry is visited in the new array, a new row is created and is given a rowspan value equal to the number of elements in its own data2 property array (partNo).
Then for each pf those, a new row is added, starting from the second one, holding the current partNo alone.
I didn't see you were using jQuery so I went for vanilla js. Anyway this is the MDN reference to the topics faced here:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#attr-rowspan
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
var obj = {  
"data": [
{ 
"lineID": "1",
"data2": [{"partNo": "ABC","plan": "120"},{"partNo": "DEF","plan": "50"}],
},
{      
"lineID": "2",
"data2": [{"partNo": "FAB","plan": "75"}],
}
]
};
//target tbody
const tbody = document.querySelector('#tbl1 tbody');
//for each entry in obj.data
obj.data.forEach( entry => {
//create a new currentRow
let currentRow = document.createElement('tr');
//create a cell for the current line and append it to the currentRow
const tdLine = document.createElement('td');
tdLine.textContent = `LINE ${entry.lineID}`;
if(entry.data2.length > 1)
tdLine.setAttribute('rowspan', entry.data2.length);
currentRow.append(tdLine);
//for each partNo
entry.data2.forEach( (part, i) => {
//if the index of the current partNo is > 0, commit the currentRow and make a new one
if(i > 0){
tbody.append(currentRow);
currentRow = document.createElement('tr');
}
//create the cell for the current partNo and append it to the currentRow
const tdPart = document.createElement('td');
tdPart.textContent = part.partNo;
currentRow.append(tdPart);
});
//append the currentRow to the table
tbody.append(currentRow);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl1" class="tbl1" border="1">
<thead>
<th>Line</th>
<th>Part No.</th>
</thead>
<tbody></tbody>
</table>
Just set rowspan for the first cell of first group based on data2 length. Then render rest of group's rows with single cell with data2.
const jsonStr = {
"data": [
{
"data2": [
{
"partNo": "ABC",
"plan": "120"
},
{
"partNo": "DEF",
"plan": "50"
}
],
"lineID": "1"
},
{
"data2": [
{
"partNo": "FAB",
"plan": "75"
}
],
"lineID": "2"
}
]
};
const tbody = $(".tbl1").find("tbody");
for(let i=0; i<jsonStr.data.length; i++) {
const label = "LINE " + jsonStr.data[i].lineID;
let tr = document.createElement("tr");
tbody.append(tr);
let td = document.createElement("td");
td.innerHTML = label;
td.rowSpan = jsonStr.data[i].data2.length;
tr.appendChild(td);
td = document.createElement("td");
td.innerHTML = jsonStr.data[i].data2[0].partNo;
tr.appendChild(td);
for(let j=1; j<jsonStr.data[i].data2.length; j++) {
const partNo = jsonStr.data[i].data2[j].partNo;
tr = document.createElement("tr");
tbody.append(tr);
td = document.createElement("td");
td.innerHTML = partNo;
tr.appendChild(td);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tbl1">
<tbody></tbody>
</table>

How to insert array values into a HTML table with javascript?

I am trying to put an array in a HTML table with javascript function but i dont khont how to insert this array? The idea is when i click on button Insert, it'll add one person's information into row.
This's my table
<script>
//Array
var a = [
{name:"Micheal", age:20, hometown:"New York"},
{name:"Santino", age:25, hometown:"Los Angeles"},
{name:"Fredo", age:29, hometown:"California"},
{name:"Hagen", age:28, hometown:"Long Beach"},
]
//Insert data function
function Insert_Data() {
var table = document.getElementById("myTable");
//Help......
}
</script>
<!--Button Insert-->
<input type="button" onclick="Insert_Data" value="Insert" />
<!--Table-->
<table id="myTable">
<tr>
<th>Full Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
You declare both thead and tbody and in function in loop fill the table
var a = [
{name:"Micheal", age:20, hometown:"New York"},
{name:"Santino", age:25, hometown:"Los Angeles"},
{name:"Fredo", age:29, hometown:"California"},
{name:"Hagen", age:28, hometown:"Long Beach"},
]
//Insert data function
function Insert_Data() {
var table = document.getElementById("datas");
table.innerHTML="";
var tr="";
a.forEach(x=>{
tr+='<tr>';
tr+='<td>'+x.name+'</td>'+'<td>'+x.age+'</td>'+'<td>'+x.hometown+'</td>'
tr+='</tr>'
})
table.innerHTML+=tr;
//Help......
}
<input type="button" onclick="Insert_Data()" value="Insert" />
<!--Table-->
<table id="myTable">
<thead>
<tr>
<th>Full Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tbody id="datas">
</tbody>
</table>
Demo proof: https://jsfiddle.net/psw41g6k/
function Insert_Data() {
var table = document.getElementById("myTable");
var rows = table.querySelectorAll('tr');
console.log(rows)
for (let i = 1; i < rows.length; i++) {
rows[i].children[0].textContent = a[i-1].name
rows[i].children[1].textContent = a[i-1].age
rows[i].children[2].textContent = a[i-1].hometown
}
}
For dynamic tables if you gonna change your array frequently
let tableBody = a.reduce((rows, nextRow) =>{
return rows +=
'<tr>' +
Object.keys(nextRow).reduce((cols, nextCol) => {
return cols += '<th>' + nextRow[nextCol] + '</th>'
}, '') +
'</tr>'
}, '')
Create a dynamic element tr and td at the click of the button and append it to the table element in the document.
Use https://www.w3schools.com/jsref/met_node_appendchild.asp as a reference to understand how to create a dynamic element.
Here is a completely generic method, you can add a new key and it adds a new column to the data, no problem:
//Array
var myData = [
{name:"Micheal", age:20, hometown:"New York", example: "extra"},
{name:"Santino", age:25, hometown:"Los Angeles", example: "extra"},
{name:"Fredo", age:29, hometown:"California", example: "extra"},
{name:"Hagen", age:28, hometown:"Long Beach", example: "extra"},
]
//get references to the table and the head and body:
const myTable = document.getElementById('myTable');
const myTable_header = myTable.querySelector('thead')
const myTable_body = myTable.querySelector('tbody')
//Insert data function
function Insert_Data() {
//Help...... :
myTable_header.innerHTML = '';
var tr = document.createElement('tr');
const headers_data = Object.keys(myData[0]);
headers_data.forEach((key) => {
var th = document.createElement('th')
th.innerHTML = key
tr.appendChild(th);
})
myTable_header.appendChild(tr);
myTable_body.innerHTML = '';
for (let i = 0; i < myData.length; i++){
var tr = document.createElement('tr');
headers_data.forEach((key) => {
var td = document.createElement('td');
td.innerHTML = myData[i][key]
tr.appendChild(td);
});
myTable_body.appendChild(tr);
}
}
<!--Button Insert-->
<input type="button" onclick="Insert_Data()" value="Insert" />
<!--Table-->
<table id="myTable">
<thead>
<!-- Data is injected here -->
</thead>
<tbody>
<!-- Data is injected here -->
</tbody>
</table>

How adding a table with js?

I want add a table on my html table via JavaScript.
I've already tried using the appendChild and insertBefore methods, but those didn't work.
Here is my JavaScript:
var utilisateur = [{
id: 51,
checked: false,
prenom: "Dolores",
date: "Fermière",
examen: "host",
note: "ww.dolores#gmail.com"
}, {
id: 52,
checked: true,
prenom: "Bernard",
date: "Robopsycologue",
examen: "human",
note: "ww.bernard#gmail.com"
}
// {
// id: 3,
// name: "Robert",
// job: "Directeur",
// specie: "human",
// email: "ww.robert#gmail.com"
// },
// {
// id: 4,
// name: "Maeve",
// job: "Maquerelle",
// specie: "host",
// email: "ww.maeve#gmail.com"
// },
// {
// id: 5,
// name: "Teddy",
// job: "Inconnu",
// specie: "host",
// email: "ww.teddy#gmail.com"
// },
// {
// id: 6,
// name: "William",
// job: "Actionnaire",
// specie: "human",
// email: "ww.william#gmail.com"
// },
// {
// id: 7,
// name: "Elsie",
// job: "Programmeuse",
// specie: "human",
// email: "ww.elsie#gmail.com"
// },
// {
// id: 8,
// name: "Nathanael",
// job: "Dev",
// specie: "human",
// email: "s.nathanael#outlook.fr"
// }
];
for (let i = 0; i < 100; i++) {
var row = document.createElement("tr");
var cell0 = document.createElement("td");
var cell1 = document.createElement("td");
var atr = document.createAttribute("class");
atr.value = "bs-checkbox";
cell1.setAttributeNode(atr);
var para = document.createElement("input");
var para1 = document.createAttribute("data-index");
var para2 = document.createAttribute("name");
var para3 = document.createAttribute("type");
para1.value = "0";
para2.value = "btSelectItem";
para3.value = "checkbox";
para.setAttributeNode(para1);
para.setAttributeNode(para2);
para.setAttributeNode(para3)
cell1.appendChild(para);
// var cell1 = '<td class="bs-checkbox"></td>'
//alert(cell1).innerText;
var cell2 = document.createElement("td");
var cell3 = document.createElement("td");
var cell4 = document.createElement("td");
var cell5 = document.createElement("td");
var cell6 = document.createElement("td");
var cell7 = document.createElement("td");
var cell8 = document.createElement("td");
cell0.innerText = utilisateur[i].id;
cell1.innerText = utilisateur[i].checked
cell2.innerText = utilisateur[i].prenom;
cell3.innerText = utilisateur[i].date;
cell4.innerText = utilisateur[i].examen;
cell5.innerText = utilisateur[i].note;
row.appendChild(cell0);
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
row.appendChild(cell4);
row.appendChild(cell5);
// row.appendChild(cell6);
// row.appendChild(cell7);
// row.appendChild(cell8);
// document.getElementsById("tbody")[0].appendChild(row);
// var elem = document.getElementsById("tabs1");
// var mychild = document.getElementById("")
// elem.insertBefore(mypara, mychild);
// elem.appendChild(row);
var element = document.getElementById("tabs1")[0];
element.appendChild(row);
}
$(document).ready(function() {
$(cell1).toggleClass("bs-checkbox");
});
Here is my HTML:
<div class="tabs" id="tabs1">
<!-- <table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th class="col">Name</th>
<th class="col">Job</th>
<th class="col">Attribut</th>
<th class="col">Email</th>
</tr>
</thead>
</table> -->
</div>
<table class="table" data-click-to-select="true" data-filter-control="true" data-search="true" data-show-export="true" data-toggle="table" data-toolbar="#toolbar" id="table">
<thead>
<tr>
<th id="0" style="visibility: hidden; display: none;"></th>
<th data-checkbox="true" data-field="state"></th>
<th data-field="prenom" data-filter-control="input" data-sortable="true">Prénom</th>
<th data-field="date" data-filter-control="select" data-sortable="true">Date</th>
<th data-field="examen" data-filter-control="select" data-sortable="true">Examen</th>
<th data-field="note" data-sortable="true">Note</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td id="1" style="visibility: hidden; display: none;"></td>
<td class="bs-checkbox"><input data-index="0" name="btSelectItem" type="checkbox"></td>
<td>Valérie</td>
<td>01/09/2015</td>
<td>Français</td>
<td>12/20</td>
</tr>
</tbody>
</table>
I want add my table JavaScript on my div on tbody, but he always go after my tbody.
The problem is, even if i create another div for my JavaScript, he never go on this div, so i want put my JavaScript on my div tabs1.
You cannot add a <div> inside a table body, so it is placed outside it, and so are your inserts. If you change this code:
var element = document.getElementById("tabs1")[0];
element.appendChild(row);
to this:
var element = document.getElementById("tbody");
element.appendChild(row);
it seems to work, somewhat. See: https://jsfiddle.net/KIKO_Software/kqr48uxj/4/
New rows are now added to the table body.
A number of issues...
You can't have a <div> as the child of a <tbody> because that is invalid HTML... so I would suggest you remove the <div> (also remember you can have multiple <tbody> tags within a <table> meaning you can split them up into section with separate id attributes, etc).
The function call of document.getElementById("tabs1") will return a single object, not an array - so you don't need the [0] at the end...
var element = document.getElementById("tabs1");
And lastly, you're going from 0 to 99 in your for loop, but the data you've provided only goes from 0 to 1 (or 0 to 7 with the commented out data)... however, you're trying to access utilisateur[i] and if the value of i is more than the number of items of data in the array, you will get an error in your developer console. So you need to check that there are enough items in utilisateur.length...
if (i < utilisateur.length) {
cell0.innerText = utilisateur[i].id;
cell1.innerText = utilisateur[i].checked
...
}
var utilisateur = [
{
id: 51,
checked: false,
prenom: "Dolores",
date: "Fermière",
examen: "host",
note: "ww.dolores#gmail.com"
},
{
id: 52,
checked: true,
prenom: "Bernard",
date: "Robopsycologue",
examen: "human",
note: "ww.bernard#gmail.com"
}
];
for (let i = 0; i < 100; i++) {
var row = document.createElement("tr");
var cell0 = document.createElement("td");
var cell1 = document.createElement("td");
var atr = document.createAttribute("class");
atr.value = "bs-checkbox";
cell1.setAttributeNode(atr);
var para = document.createElement("input");
var para1 = document.createAttribute("data-index");
var para2 = document.createAttribute("name");
var para3 = document.createAttribute("type");
para1.value = "0";
para2.value = "btSelectItem";
para3.value = "checkbox";
para.setAttributeNode(para1);
para.setAttributeNode(para2);
para.setAttributeNode(para3)
cell1.appendChild(para);
// var cell1 = '<td class="bs-checkbox"></td>'
//alert(cell1).innerText;
var cell2 = document.createElement("td");
var cell3 = document.createElement("td");
var cell4 = document.createElement("td");
var cell5 = document.createElement("td");
var cell6 = document.createElement("td");
var cell7 = document.createElement("td");
var cell8 = document.createElement("td");
if (i < utilisateur.length) {
cell0.innerText = utilisateur[i].id;
cell1.innerText = utilisateur[i].checked
cell2.innerText = utilisateur[i].prenom;
cell3.innerText = utilisateur[i].date;
cell4.innerText = utilisateur[i].examen;
cell5.innerText = utilisateur[i].note;
}
row.appendChild(cell0);
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
row.appendChild(cell4);
row.appendChild(cell5);
// row.appendChild(cell6);
// row.appendChild(cell7);
// row.appendChild(cell8);
// document.getElementsById("tbody")[0].appendChild(row);
// var elem = document.getElementsById("tabs1");
// var mychild = document.getElementById("")
// elem.insertBefore(mypara, mychild);
// elem.appendChild(row);
var element = document.getElementById("tbody");
element.appendChild(row);
}
$(document).ready(function(){
$(cell1).toggleClass("bs-checkbox");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" class="table"
data-toggle="table"
data-search="true"
data-filter-control="true"
data-show-export="true"
data-click-to-select="true"
data-toolbar="#toolbar">
<thead>
<tr>
<th id="0" style="visibility: hidden; display: none;"></th>
<th data-field="state" data-checkbox="true"></th>
<th data-field="prenom" data-filter-control="input" data-sortable="true">Prénom</th>
<th data-field="date" data-filter-control="select" data-sortable="true">Date</th>
<th data-field="examen" data-filter-control="select" data-sortable="true">Examen</th>
<th data-field="note" data-sortable="true">Note</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td id="1" style="visibility: hidden; display: none;"></td>
<td class="bs-checkbox "> <input data-index="0" name="btSelectItem" type="checkbox"> </td>
<td>Valérie</td>
<td>01/09/2015</td>
<td>Français</td>
<td>12/20</td>
</tr>
</tbody>
</table>
You can use a simple solution, using ES6 string interpolation
For example we have an array of objects
employees: [
{
name: 'John Doe',
phone: '00000000',
},
{
name: 'George Daniels',
phone: '11111111',
}
]
and a table html object.
you can append rows like this:
for (let employee of employees) {
let row = document.createElement("tr");
row.innerHTML = `<td>${employee.name}</td>
<td>${employee.phone}</td>`;
table.appendChild(row);
}

How do I use themes with jsPDF-AutoTable?

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}}
});

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