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>
Related
I want to use the specifications shown in this video, but it does not work.
Please confirm it.
https://gyazo.com/0dd4feeea3f7a27aefe6d2160944c65e
Conditions:
You can delete the task when you press the delete button
ID is reassigned when deleting a task
After deleting, when adding a new task, the IDs are serialized
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel ="stylesheet" href="css/style.css">
<title>Todoリスト</title>
</head>
<body>
<h1>Todoリスト</h1>
<p>
<input type="radio" name="status" value="1" checked="checked">全て
<input type="radio" name="status" value="2">作業中
<input type="radio" name="status" value="3">完了
</p>
<p></p>
<table>
<thead>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
<th></th>
</thead>
<tbody class ="addTask-target"></tbody>
</table>
<h2>新規タスクの追加</h2>
<input class="addTask-value" type="text" />
<button class="addTask-trigger" type="button">追加</button>
<script src="js/main.js"></script>
</body>
</script>
</html>
document.addEventListener('DOMContentLoaded', function() {
const addTaskTrigger = document.getElementsByClassName('addTask-trigger')[0];
const addTaskTarget = document.getElementsByClassName('addTask-target')[0];
const addTaskValue = document.getElementsByClassName('addTask-value')[0];
let nextId = 0;
const todos = [];
const addTask = (task,id) => {
//テーブル要素を生成する td要素を作る
const tableItem = document.createElement('tr');
const addButtonTd = document.createElement('td');
const idSpanTd = document.createElement('td');
const taskSpanTd = document.createElement('td');
const removeButtonTd = document.createElement('td');
//Button要素を生成する
const addButton = document.createElement('button')
const removeButton = document.createElement('button')
//要素内のHTML文章を変更する
addButton.innerText = '作業中';
removeButton.innerText = '削除';
idSpanTd.innerText = id;
taskSpanTd.innerText = task;
//生成したテーブル要素をブラウザに表示する
tableItem.append(idSpanTd);
tableItem.append(taskSpanTd);
tableItem.append(addButtonTd);
tableItem.append(removeButtonTd);
addTaskTarget.appendChild(tableItem);
//生成したbutton要素を生成する
addButtonTd.append(addButton);
removeButtonTd.append(removeButton);
const todo = {
task: 'taskSpanTd',
status: '作業中'
};
todos.push(todo);
};
addTaskTrigger.addEventListener('click',() => {
const task = addTaskValue.value;
addTask(task,nextId ++);
addTaskValue.value = '';
});
const element = document.querySelector('td')
document.getElementById("removebutton").onclick = function() {
element.remove();
};
});
Define your buttons click actions upon buttons creation
Use Object.defineProperty() to handle your todo "status" property and reactively apply changes to the TR element classList
Use String.prototype.trim() - you don'w want empty spaces to become new todo tasks.
preferably use always Element.textContent instead of Element.innerText
When deleting your TR element, don't forget to update the todos Array by removing that item using todos.splice(todos.indexOf(todo), 1);
// Helper functions
const ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});
const EL = (sel, EL) => (EL || document).querySelector(sel);
// Todo App
const EL_list = EL('#todo-list');
const EL_task = EL('#todo-task');
const EL_add = EL('#todo-add');
const todos = [];
let id = 0;
const addTask = () => {
const task = EL_task.value.trim(); // Always trim!
if (!task) return; // Do nothing
EL_task.value = "";
id += 1;
const todo = {
id: id,
task: task,
status: "",
};
// Make "status" reactive
Object.defineProperty(todo, "__status", {
set(val) {
this.status = val;
TR.classList.remove("is-done", "is-doing");
TR.classList.add(`is-${this.status}`);
}
});
todos.push(todo);
// New Elements
const TR = ELNew("tr");
const TD_id = ELNew("td", {textContent: id});
const TD_task = ELNew("td", {textContent: task});
const TD_status = ELNew("td");
const TD_remove = ELNew("td");
const EL_btn_doing = ELNew("button", {
className: "todo-btn-doing",
textContent: "Doing",
type: "button",
onclick() {
todo.__status = "doing";
}
});
const EL_btn_done = ELNew("button", {
className: "todo-btn-done",
textContent: "Done",
type: "button",
onclick() {
todo.__status = "done";
}
});
const EL_btn_remove = ELNew("button", {
textContent: "×",
title: "Remove this task",
type: "button",
onclick() {
if (!confirm(`Remove task ID:${id} "${task}"`)) return; // Do nothing
TR.remove(); // Remove element
todos.splice(todos.indexOf(todo), 1); // Remove from todos list
}
});
// Insertions
TD_status.append(EL_btn_doing, EL_btn_done);
TD_remove.append(EL_btn_remove);
TR.append(TD_id, TD_task, TD_status, TD_remove);
EL_list.append(TR);
};
EL_add.addEventListener("click", addTask);
/*QuickReset*/* {margin:0; box-sizing:border-box;}
table {
border-collapse: collapse;
border-spacing: 0;
}
table th,
table td {
padding: 5px 10px;
}
#todo-list tr.is-doing td {
background: #fb0;
}
#todo-list tr.is-done td {
background: #0fb;
text-decoration: line-through;
}
#todo-list tr.is-doing .todo-btn-doing {
color: #fb0;
}
#todo-list tr.is-done .todo-btn-done {
color: #0fb;
}
<table>
<thead>
<th>ID</th>
<th>Description</th>
<th>Status</th>
<th></th>
</thead>
<tbody id="todo-list"></tbody>
</table>
<h2>Add new Todo</h2>
<input id="todo-task" type="text" />
<button id="todo-add" type="button">Add</button>
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
})
i just hit a demo api with link and created a dynamic table and in every click of parameter a new row is inserted with it, i just want to resitrict duplicate entry from table.
$(document).ready(function () {
//count = 1;
var counter=1,flag=0;
$("#api").click(function () {
var index = ($("#para").val());
if (index == "") {
alert("Please input data");
return false;
}
else{
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/'+index,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data, textStatus, xhr) {
console.log(data);
var tr = [];
if(flag==0){
mytable = $('<table></table>').attr({ id: "basicTable", class:"basicTable1" });
//for (var i = 0; i < count; i++) {
let ab = $('<h1>API Data</h1>').appendTo("#h");
let row = $('<tr></tr>').appendTo(mytable);
let row1 = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<th></th>').text(key).appendTo(row);
$('<td></td>').text(val).appendTo(row1);
});
let row2 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row1);
flag=1;
counter++;
//}
mytable.appendTo("#data");
}
else{
//for (var i = 0; i < count; i++) {
let row = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<td></td>').text(val).appendTo(row);
});
let row1 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row);
counter++;
//}
mytable.appendTo("#data");
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
alert("No Record Found");
}
});
}
});
});
function removeFun(a){
$("#row"+a).remove();
}
var textbox = $("#data");
textbox.change(function() {
$("#basicTable").find("td").each(function(){
if($(this).html()==textbox.val()){
alert(textbox.val());
};
})
});
.h1{
color: orange;
margin:30px;
}
.h2{
margin-top: 20px;
}
table, th, td {
border: 2.5px solid black;
align-content: center;
}
table{
width: 80%;
text-align: center;
}
th{
height: 50px;
align-content: right;
background-color: orange;
}
th:hover {background-color: #3e8e41}
th,td{
width: 30%;
}
.button1 {
padding: 10px 15px;
font-size: 14px;
text-align: center;
cursor: pointer;
outline: none;
color: #fff;
background-color: orange;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
}
.button1:hover {background-color: #3e8e41}
.button1:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
<!DOCTYPE html>
<html>
<head>
<title>Api hit with JSON</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<center><u class="h1">AJAX</u> api with JSON</center>
<center>
<div class="h2">
<label>Enter the parameter</label>
<input type="number" name="" id="para">
<button id="api">Submit</button>
</div>
<div id="h"></div>
<div id="data"></div>
</center>
</body>
</html>
This is my file, I hit the demo api with link and get the data to dynamic table but I want to restrict duplicate files in the dynamic table.
$(document).ready(function () {
//count = 1;
var counter=1,flag=0;
$("#api").click(function () {
var index = ($("#para").val());
if (index == "") {
alert("Please input data");
return false;
}
else{
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/'+index,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data, textStatus, xhr) {
console.log(data);
var tr = [];
if(flag==0){
mytable = $('<table></table>').attr({ id: "basicTable", class:"basicTable1" });
//for (var i = 0; i < count; i++) {
let ab = $('<h1>API Data</h1>').appendTo("#h");
let row = $('<tr></tr>').appendTo(mytable);
let row1 = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<th></th>').text(key).appendTo(row);
$('<td></td>').text(val).appendTo(row1);
});
let row2 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row1);
flag=1;
counter++;
//}
mytable.appendTo("#data");
}
else{
//for (var i = 0; i < count; i++) {
let row = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<td></td>').text(val).appendTo(row);
});
let row1 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row);
counter++;
//}
mytable.appendTo("#data");
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
alert("No Record Found");
}
});
}
});
});
function removeFun(a){
$("#row"+a).remove();
}
first you need to remove duplicates from your "data"
var GroupByColumn = function (SourceData, columnName) {
var Unique = {};
var groupByColumn = columnName;
var tempData = SourceData;
for (var i = 0; i < tempData.length; i++) {
if (!Unique[tempData[i][groupByColumn]])
Unique[tempData[i][groupByColumn]] = [];
Unique[tempData[i][groupByColumn]].push(tempData[i]);
}
return Unique;
}
by using above function you can find a unique data
var z= [
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
]
GroupByColumn(z,"id")
GroupByColumn(z,"title")
GroupByColumn(z,"completed")
GroupByColumn(z,"userId")
depepends on your need it will return your data. hope this will be helpful
I am trying to import *.csv using the init-from-csv.html (from the demo files). I downloaded the GetOrgChart zip files and I changed the link to the actual .js and .css files.
This my code:
<!DOCTYPE html> <html> <head>
<title>OrgChart | Initialize From XML</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="D:/Tools/GetOrgChart/getorgchart/getorgchart.js"></script>
<link href="D:/Tools/GetOrgChart/getorgchart/getorgchart.css" rel="stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
html, body {
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
overflow: hidden;
}
#people {
width: 100%;
height: 100%;
}
</style> </head> <body>
<div id="people"></div>
<script type="text/javascript">
function convertToCsvJson(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 1; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = {};
for (var j = 0; j < headers.length; j++) {
tarr[headers[j]] = data[j];
}
lines.push(tarr);
}
}
return lines;
}
$.get("D:/Tools/GetOrgChart/ORG_Data.txt", function (source) {
source = convertToCsvJson(source);
var peopleElement = document.getElementById("people");
var orgChart = new getOrgChart(peopleElement, {
theme: "helen",
primaryFields: ["name", "Job Title"],
photoFields: ["Photo"],
linkType: "M",
enableEdit: false,
enableDetailsView: false,
dataSource: source
});
});
</script> </body> </html>
After I open the HTML file, it will not load. I am not sure what I did wrong.
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);