How to insert array values into a HTML table with javascript? - 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>

Related

create table from jsp in 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);

Convert table to key-value pair with plain JS

I have a large table consisting of row numbers and prices. I want to be able to look up a price by using the row number.
function buildtable(){
var tableObj = document.getElementById( 'table' );
var allTRs = tableObj.getElementsByTagName( 'tr' );
for ( var trCounter = 0; trCounter < allTRs.length; trCounter++ )
{
var tmpArr = [];
var allTDsInTR = allTRs[ trCounter ].getElementsByTagName( 'td' );
for ( var tdCounter = 0; tdCounter < allTDsInTR.length - 1; tdCounter++ )
{
tmpArr.push( allTDsInTR[ tdCounter ].innerHTML );
}
arr.push( tmpArr );
}
}
the following code creates a list of lists.
How can I change the function so its creates a single key pair store?
HTML FOR TABLE
foreach($res as $row) {
$seat = $row['RowNumber'];
$price = $row['Zone.PriceMultiplier * 15.00'];
echo "<tr>";
echo "<td>".$seat."</td>";
echo "<td>".$price."</td>";
echo "<td><input type='checkbox' name='check_list[]' value=\"$seat;\" onclick='javatest(this);' </td>";
echo "</tr>";
}
You can use an object as the key-value map (hash table).
function buildtable() {
var tableObj = document.getElementById('table');
var map = {};
var allTRs = tableObj.getElementsByTagName('tr');
for (var trCounter = 1; trCounter < allTRs.length; trCounter++) {
var tmpArr = [];
var allTDsInTR = allTRs[trCounter].getElementsByTagName('td');
if (allTDsInTR.length) {
map[allTDsInTR[0].innerHTML.trim()] = parseFloat(allTDsInTR[1].innerHTML.trim());
}
}
console.log(map);
}
buildtable();
<table id='table'>
<thead>
<tr>
<td>
RowNumber
</td>
<td>
Price
</td>
<tr>
</thead>
<tbody>
<tr>
<td>
U01
</td>
<td>
24.5
</td>
<tr>
<tr>
<td>
U02
</td>
<td>
22
</td>
<tr>
</tbody>
</table>
The result will be something like:
{
"U01": 24.5,
"U02": 22
}
Something like this?
var tableRows = Array.from(document.querySelectorAll('#myTable > tbody > tr'));
var result = {};
tableRows.forEach(row => {
var cols = Array.from(row.getElementsByTagName('td'));
var key = cols[0].innerHTML;
var value = cols[1].innerHTML;
if (!result[key]) {
result[key] = [value];
} else {
result[key].push(value);
}
});
console.log(result);
<table id="myTable">
<thead>
<tr>
<th>RowNumber</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>U01</td>
<td>26.999999284744263</td>
</tr>
<tr>
<td>U02</td>
<td>26.999999284744263</td>
</tr>
<tr>
<td>U01</td>
<td>26.999999284744263</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]];
}
}

table collapse (rows hide) not working Javascript

function tablecollapse()
{
var table = document.getElementById(tblbatting);
var rowCount = table.rows.length;
for(var i=4; i< rowCount; i++)
{
var row = table.rows[i];
row.display="none";
}
}
I have this code running onload() but the table's connect aren't hiding.
What is wrong with this code? or any other suggestions?
What Wayne said. He was a lot faster than me.
function tablecollapse(id) {
var table = document.getElementById(id);
var rows = table.rows;
for (var i = 4; i < rows.length; i++) {
rows[i].style.display = "none";
}
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<table id="foo">
<thead>
<td>Column</td>
<td>Column</td>
</thead>
<tr>
<td>one</td>
<td>one</td>
</tr>
<tr>
<td>two</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>three</td>
</tr>
<tr>
<td>four</td>
<td>four</td>
</tr>
<tr>
<td>five</td>
<td>five</td>
</tr>
</table>
<button onclick="tablecollapse('foo')">Collapse</button>
There are two errors in the code. First, you need to put quotes around the table element id in var table = document.getElementById(tblbatting);. So, this code becomes var table = document.getElementById("tblbatting");.
Second, to set the display style, you need to access the style property of the table row element. So row.display="none"; becomes row.style.display="none";.
var table = document.getElementById("tblbatting");
var rowCount = table.rows.length;
for(var i=4; i< rowCount; i++)
{
var row = table.rows[i];
row.style.display="none";
}
I am not sure if you have done it deliberately or not, but you should be aware that your code will not hide the first 4 rows of the table because you have used var i=4 to initialise your loop counter.

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