Javascript array to html table - javascript

I want to make a html table from an array. I want to use the loop function to do this. But I struggle to find out how I can loop an array to a html table. I want have the name of the countries in the first section and "country" on top of the countries. In the last section I want to have the Capitals and "Capital" on top.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm" , "Copenhagen"]
</script>
</body>
</html>

You can do this by looping through the country list and creating an HTML string. Then you can put that inside the tbody using a class or id selector. Here is an example-
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm" , "Copenhagen"]
var bodyString = '';
$.each(country, function(index, ctry) {
bodyString += ('<tr><td>'+ctry+'</td><td>'+capital[index]+'</td></tr>');
});
$('.countriesTable tbody').html(bodyString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table class="countriesTable">
<thead>
<tr><th>Country</th><th>Capital</th>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>

I think you want something like this, which is pure javascript (Run the snippet)--
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm" , "Copenhagen"]
var table= document.createElement('table'),
thead = document.createElement('thead'),
tbody = document.createElement('tbody'),
th,
tr,
td;
th = document.createElement('th'),
th.innerHTML="County";
table.appendChild(th);
th = document.createElement('th');
th.innerHTML= "Capital"
table.appendChild(th);
table.appendChild(thead);
table.appendChild(tbody);
document.body.appendChild(table);
for(var i=0;i<country.length;i++){
tr = document.createElement('tr'),
//for county
td= document.createElement('td');
td.innerHTML=country[i];
tr.appendChild(td);
//for capital
td = document.createElement('td');
td.innerHTML=capital[i];
tr.appendChild(td);
tbody.appendChild(tr);
}
table{
border-collapse: collapse;
}
th,td{
border:1px solid #000;
}

I made an easy tool for this - https://github.com/dszakal/ArrayToTable
Example:
var tableGen = new ArrayToTable();
// optional
tableGen.tableclasses = 'bluetable table-with-oddeven'; // for css
tableGen.tableid = 'something-unique';
dataArray = [
{
country: 'Norway',
capital: 'Oslo'
}
,
{
country: 'Sweden',
capital: 'Stockholm'
}
,
{
country: 'Denmark',
capital: 'Copenhagen'
}
];
tableGen.putTableHtmlToId(dataArray, 'tableHere');

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm" , "Copenhagen"];
var bodyString = '';
$.each(country, function(index, country) {
bodyString += ('<tr><td>'+country+'</td><td>'+capital[index]+'</td></tr>');
});
$('.country tbody').html(bodyString);
});
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<table class="table table-striped country">
<thead>
<tr><th>Country</th><th>Capital</th>
</thead>
<tbody></tbody>
</table>
</body>
</html>

it´s a nice way to use template literals
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Array2Table</title>
</head>
<body>
<div id="tableContent"></div>
<script>
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm" , "Copenhagen"]
const tmpl = (country,capital) => `
<table><thead>
<tr><th>Country<th>Capital<tbody>
${country.map( (cell, index) => `
<tr><td>${cell}<td>${capital[index]}</tr>
`).join('')}
</table>`;
tableContent.innerHTML=tmpl(country, capital);
</script>
</body>
</html>
for Internet Explorer:
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm", "Copenhagen"];
var tmpl = function tmpl(country, capital) {
return "<table><thead><tr><th>Country<th>Capital<tbody>" +
country.map(function (cell, index) {
return "<tr><td>" + cell + "<td>" +
capital[index] + "</tr>";
}).join('') + "</table>";
};
tableContent.innerHTML = tmpl(country, capital);

Related

How to make HTML table to Datatable?

I followed the below code to make a normal table into data table.. i included all the links responsible to make data table.. but still data table is not showing up.. pls resolve the error anyone?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASSESSMENT 2</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap4.min.css">
<script>
$(document).ready(function () {
$('#example').DataTable();
});
</script>
</head>
<body>
<div id="" class="container">
<!-- <button type="button" onclick="run()"> Click Me </button> -->
<h1 class="text-center">Table of Data</h1>
<!--id="example" -->
<table id="example" class="table ">
<tr>
<th>NO</th>
<th>API</th>
<th>Description</th>
</tr>
</table>
</div>
<script>
const table = document.getElementById("example")
function run() {
var xhr = new XMLHttpRequest();
var url = 'https://api.publicapis.org/entries';
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// getting res and to convert in json
let res = this.responseText;
let data = JSON.parse(res);
// console.log(data);
//traverse data
let NO =[]
let API = []
let Description = []
for (let i = 0; i < 100; i++) {
NO.push([i]);
API.push(data["entries"][i]["API"])
Description.push(data["entries"][i]["Description"])
}
// to create a table
for (let i = 0; i < 100; i++) {
let row = table.insertRow(i + 1);
//add cells
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
// to insert the data
cell0.innerHTML = NO [i]
cell1.innerHTML = API[i];
cell2.innerHTML = Description[i];
}
}
}
xhr.send();
}
run()
</script>
</body>
</html>
shall i need to put some specific links are the above things is enough? the output shows a normal table.. i have also called the table's id in script tag also.. is anything need to be done

Table data export with identifier

How can I export this HTML table data in a way, that the exported data look exactly as the initial data.
The array data[] is the source for the table below. The button dataToArray exports this HTML table data back to an array. I struggle with the format as I need the data identifier, in the array, too.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Table Test</title>
<!-- d3.js framework -->
<script src="https://d3js.org/d3.v6.js"></script>
<!-- jquery import-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- fontawesome stylesheet https://fontawesome.com/ -->
<script src="https://kit.fontawesome.com/39094309d6.js" crossorigin="anonymous"></script>
</head>
<style>
#myTable {
border-collapse: collapse;
}
#myTable td {
border: 1px solid black;
padding: 8px;
}
#delRow {
width: auto;
height: 30px;
}
</style>
<body>
<table id="myTable">
<th>
Property
</th>
<th>
Value
</th>
<tbody>
<!-- filled by script -->
</tbody>
</table>
<button id="dataToArray">dataToArray</button>
<script>
data = [
{
"property": "animal",
"value": "dog"
},
{
"property": "car",
"value": "audi"
},
{
"property": "snacks",
"value": "chips"
}
]
//populate table
var myTable = document.getElementById("myTable")
for (var i = 0; i < data.length; i++ ) {
var row = `<tr>
<td>${data[i].property}</td>
<td>${data[i].value}</td>
</tr>`
myTable.innerHTML += row
}
//get table data
var dataToArray = document.getElementById("dataToArray")
dataToArray.addEventListener("click", function() {
console.clear()
console.log("data before export:")
console.log(data)
var exportData = []
$("table#myTable tr").each(function() {
var rowDataArray = []
var actualData = $(this).find("td");
if (actualData.length > 0) {
actualData.each(function() {
rowDataArray.push($(this).text());
});
exportData.push(rowDataArray)
};
})
console.log("data after export:")
console.log(exportData)
})
</script>
</body>
</html>
Here is dynamic way (works even for more than two headers without changing the export code):
First get all headers dynamically (not hard code) by this line:
var headers = $("table#myTable th").map(function () {
return this.innerText;
}).get();
And then in export time do like this:
var object = {};
headers.forEach((data, index) => {
object[data] = actualData[index].innerText;
})
exportData.push(object)
data = [
{
"property": "animal",
"value": "dog"
},
{
"property": "car",
"value": "audi"
},
{
"property": "snacks",
"value": "chips"
}
]
//populate table
var myTable = document.getElementById("myTable")
for (var i = 0; i < data.length; i++) {
var row = `<tr>
<td>${data[i].property}</td>
<td>${data[i].value}</td>
</tr>`
myTable.innerHTML += row
}
//get table data
var dataToArray = document.getElementById("dataToArray")
dataToArray.addEventListener("click", function () {
var headers = $("table#myTable th").map(function () {
return this.innerText;
}).get();
console.clear()
console.log("data before export:")
console.log(data);
var exportData = []
$("table#myTable tr").each(function (e,i) {
var rowDataArray = []
var actualData = $(this).find("td");
if (actualData.length > 0) {
var object = {};
headers.forEach((data, index) => {
object[data] = actualData[index].innerText;
})
exportData.push(object)
};
})
console.log("data after export:")
console.log(exportData)
})
#myTable {
border-collapse: collapse;
}
#myTable td {
border: 1px solid black;
padding: 8px;
}
#delRow {
width: auto;
height: 30px;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<table id="myTable">
<th>
Property
</th>
<th>
Value
</th>
<tbody>
<!-- filled by script -->
</tbody>
</table>
<button id="dataToArray">dataToArray</button>
You must define rowDataArray as new Object
I change your code only at this part:
var exportData = []
$("table#myTable tr").each(function() {
var rowDataArray = []
var actualData = $(this).find("td");
if (actualData.length > 0) {
actualData.each(function() {
rowDataArray.push($(this).text());
});
exportData.push(rowDataArray)
};
})
and change it with:
var exportData = []
$("table#myTable tr").each(function() {
var rowDataObject= new Object;
var actualData = $(this).find("td");
if (actualData.length > 0) {
rowDataObject.property = actualData[0].innerText;
rowDataObject.value= actualData[1].innerText;
exportData.push(rowDataObject)
};
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Table Test</title>
<!-- d3.js framework -->
<script src="https://d3js.org/d3.v6.js"></script>
<!-- jquery import-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- fontawesome stylesheet https://fontawesome.com/ -->
<script src="https://kit.fontawesome.com/39094309d6.js" crossorigin="anonymous"></script>
</head>
<style>
#myTable {
border-collapse: collapse;
}
#myTable td {
border: 1px solid black;
padding: 8px;
}
#delRow {
width: auto;
height: 30px;
}
</style>
<body>
<table id="myTable">
<th>
Property
</th>
<th>
Value
</th>
<tbody>
<!-- filled by script -->
</tbody>
</table>
<button id="dataToArray">dataToArray</button>
<script>
data = [
{
"property": "animal",
"value": "dog"
},
{
"property": "car",
"value": "audi"
},
{
"property": "snacks",
"value": "chips"
}
]
//populate table
var myTable = document.getElementById("myTable")
for (var i = 0; i < data.length; i++ ) {
var row = `<tr>
<td>${data[i].property}</td>
<td>${data[i].value}</td>
</tr>`
myTable.innerHTML += row
}
//get table data
var dataToArray = document.getElementById("dataToArray")
dataToArray.addEventListener("click", function() {
console.clear()
console.log("data before export:")
console.log(data)
var exportData = []
$("table#myTable tr").each(function() {
var rowDataObject= new Object;
var actualData = $(this).find("td");
if (actualData.length > 0) {
rowDataObject.property = actualData[0].innerText;
rowDataObject.value= actualData[1].innerText;
exportData.push(rowDataObject)
};
})
console.log("data after export:")
console.log(exportData)
})
</script>
</body>
</html>

how to add data dynamically using for each loop

I am trying to add data dynamically in table from array object, and also I need to add serial number and icons (approve and reject) in action column. But right now am only able to add employee names for array object. How to add serial number and icons in column in this table. plz check image.
https://i.stack.imgur.com/sJDWK.png
Javascript -
const button = document.getElementById('btn2');
const employee = [
{
name:'shubham',
company:'google'
},
{
name:'yash',
company:'facebook'
},
{
name:'saurabh',
company:'hcl'
}
]
const mydiv = document.getElementById('mydiv');
employee.forEach(event =>{
const td = document.createElement('td');
const tr = document.createElement('tr');
tr.appendChild(td);
mydiv.appendChild(tr);
td.innerHTML = event.name
})
button.addEventListener('click', () =>{
const username = document.getElementById('username');
const userpass = document.getElementById('userpass');
if((username.value == "admin" && userpass.value == "admin") && (username.value != "" && userpass.value != "")){
console.log('yes')
window.location.pathname = 'dashboard.html';
}
})
HTML -
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" >
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<h2>Welcome</h2>
<div >
<table class="table table-bordered" id="mydiv">
<tr>
<th>Sr.No.</th>
<th>Employee Name</th>
<th>Action</th>
</tr>
</table>
</div>
</div>
<script type="text/javascript" src="function.js"></script>
</body>
</html>
You can try something like this:
const employee = [
{
name:'shubham',
company:'google',
action: 'some action'
},
{
name:'yash',
company:'facebook',
action: 'some action'
},
{
name:'saurabh',
company:'hcl',
action: 'some action'
}
]
const mydiv = document.getElementById('mydiv');
employee.forEach((event, key) =>{
const serialTd = document.createElement('td');
const nameTd = document.createElement('td');
const actionTd = document.createElement('td');
const tr = document.createElement('tr');
tr.appendChild(serialTd);
tr.appendChild(nameTd);
tr.appendChild(actionTd);
mydiv.appendChild(tr);
nameTd.innerHTML = event.name
serialTD.innerHTML = key
actionTd.innerHTML = event.action
})

Scripts conflict

The scripts are working on the first load. However,when I select on the dropdown and the page will reload for the new data on the table based on what I have selected that's the time I won't be able to gather the data when I click in a row. See code below:
code.gs
function doGet()
{
var html=HtmlService.createTemplateFromFile('index');
return html.evaluate();
}
function getSelect() {
var list = SpreadsheetApp.openById('spreadssheetID').getSheetByName("VL Slots").getDataRange().getValues();
var lane = 1;
var select="";
for (var l = 3; l < list.length; l++) {
select+='<option value="' + list[l][lane] + '">'+ list[l][lane] + ' </option>';
}
return select;
}
function getTable(lob) {
var data = SpreadsheetApp.openById('spreadssheetID').getSheetByName("VL Request").getDataRange().getValues();
var rid = 0;
var request = 1;
var table="";
table+='<tr>';
for (var i = 1; i < data.length; i++) {
if (data[i][rid] == lob) {
table+='<td>' + data[i][request] + '</td>';
}
}
table+='</tr>';
return table;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
function populateSelect(){
google.script.run.withSuccessHandler(onSuccess).getSelect();
}
function onSuccess(select){
document.getElementById("mySelect").innerHTML=select;
}
function polling(){
setInterval(myFunction,2000);
}
function myFunction(){
var lob = document.getElementById("mySelect").value;
google.script.run.withSuccessHandler(onSuccess2).getTable(lob);
}
function onSuccess2(table){
document.getElementById("myTable").innerHTML=table;
}
</script>
<body onload="populateSelect()">
<select id="mySelect" onchange="polling()">
</select>
<table id="myTable">
</table>
<form id="logForm">
<label>Request <span class="required">*</span></label><input type="text" id="request" name="request" class="field-long" placeholder="Request" readonly />
</form>
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
//rIndex = this.rowIndex;
document.getElementById("request").value = this.cells[0].innerHTML.trim();
};
}
</script>
</body>
</html>
What I want to happen is that I can select on the dropdown and the data will be gathered on the table based on what I have selected and I can click on the row to pass the information in the form.
If I understood correctly, your goal is to click on the value retrieved from the spreadsheet by polling and set this value as a content of your input field "request".
If this is the case, you should incorporate your request inside the onSuccess2 function, so it will occur after the table has been populated with contents from the spreadsheet
Keep in mind that since you retrieve only one value from the sheet, you do not need to loop through row
Modify the html part of your code as following:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
function populateSelect(){
google.script.run.withSuccessHandler(onSuccess).getSelect();
}
function onSuccess(select){
document.getElementById("mySelect").innerHTML=select;
}
function polling(){
setInterval(myFunction,2000);
}
function myFunction(){
var lob = document.getElementById("mySelect").value;
google.script.run.withSuccessHandler(onSuccess2).getTable(lob);
}
function onSuccess2(table){
document.getElementById("myTable").innerHTML=table;
var myTable = document.getElementById('myTable');
var row = myTable.getElementsByTagName("tr")[0];
var cell = row.getElementsByTagName("td")[0];
var request= cell.innerHTML;
row.onclick = createClickHandler(request);
}
var createClickHandler = function(request) {
return function(){
document.getElementById("request").value = request;
};
}
</script>
<body onload="populateSelect()">
<select id="mySelect" onchange="polling()">
</select>
<table id="myTable">
</table>
<form id="logForm">
<label>Request <span class="required">*</span></label><input type="text" id="request" name="request" class="field-long" placeholder="Request" readonly />
</form>
</body>
</html>

Prevent Blank Page and Display Data in Table

I have a working code in Google Script that is compost on Index.HTML and code.gs actually this code is working if you will test it in your google app script and here it is
Index.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length; // total elements of results
var table = document.getElementById('output');
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
}
document.writeln("End of results...");
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
Search: <input type="text" id="idSrchTerm" name="search">
<input type="button" value="Search" name="submitButton" onclick="displayMessage()"/>
</div>
<table id ="output">
<tr>
<th>File Details</th>
</tr>
<tr>
<td>
<script>
function handleResults(results){
var length=results.length; // total elements of results
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|"); // split the line |~|, position 0 has the filename and 1 the file URL
document.writeln("<b><a href='"+item[1]+"' target='_blank'>"+item[0]+"</b></a> (Last modified: "+item[2]+")<br/><br/>"); // write result
}
document.writeln("End of results...");
}
</script>
</td>
</tr>
</table>
</body>
</html>
and this is Code.GS
function doGet(e) { // main function
var template = HtmlService.createTemplateFromFile('index.html');
return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'";
var names = [];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
var lm = file.getLastUpdated();
var owner = file.getOwner().getName();
var filesize = file.getSize();
var name = file.getName() +"|~|"+file.getUrl()+"|~|"+lm+"|~|"+owner+"|~|"+filesize;
names.push(name);
Logger.log(file.getUrl());
}
return names;
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn;
}
This code is working perfectly but the output of this is everytime i searched a data it transfers me to a new page with the search result.
My Question is How can I display the data in my Table Tag?
Here is the image of where should be the data will put.
Image Link

Categories