I have a JavaScript function which creates a table with 3 rows 2 cells.
Could anybody tell me how I can create the table below using my function (I need to do this for my situation)?
Here is my javascript and html code given below:
function tableCreate() {_x000D_
//body reference _x000D_
var body = document.getElementsByTagName("body")[0];_x000D_
_x000D_
// create elements <table> and a <tbody>_x000D_
var tbl = document.createElement("table");_x000D_
var tblBody = document.createElement("tbody");_x000D_
_x000D_
// cells creation_x000D_
for (var j = 0; j <= 2; j++) {_x000D_
// table row creation_x000D_
var row = document.createElement("tr");_x000D_
_x000D_
for (var i = 0; i < 2; i++) {_x000D_
// create element <td> and text node _x000D_
//Make text node the contents of <td> element_x000D_
// put <td> at end of the table row_x000D_
var cell = document.createElement("td");_x000D_
var cellText = document.createTextNode("cell is row " + j + ", column " + i);_x000D_
_x000D_
cell.appendChild(cellText);_x000D_
row.appendChild(cell);_x000D_
}_x000D_
_x000D_
//row added to end of table body_x000D_
tblBody.appendChild(row);_x000D_
}_x000D_
_x000D_
// append the <tbody> inside the <table>_x000D_
tbl.appendChild(tblBody);_x000D_
// put <table> in the <body>_x000D_
body.appendChild(tbl);_x000D_
// tbl border attribute to _x000D_
tbl.setAttribute("border", "2");_x000D_
}
_x000D_
<table width="100%" border="1">_x000D_
<tr>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> </td>_x000D_
<td rowspan="2"> </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> </td>_x000D_
</tr>_x000D_
</table>
_x000D_
This question is related to
javascript
html-table
var div = document.createElement('div');
div.setAttribute("id", "tbl");
document.body.appendChild(div)
document.getElementById("tbl").innerHTML = "<table border = '1'>" +
'<tr>' +
'<th>Header 1</th>' +
'<th>Header 2</th> ' +
'<th>Header 3</th>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>'
_x000D_
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table id="myTable" cellpadding="2" cellspacing="2" border="1" onclick="tester()"></table>
<script>
var student;
for (var j = 0; j < 10; j++) {
student = {
name: "Name" + j,
rank: "Rank" + j,
stuclass: "Class" + j,
};
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = student.name,
cell2.innerHTML = student.rank,
cell3.innerHTML = student.stuclass;
}
</script>
</body>
</html>
var btn = document.createElement('button');_x000D_
btn.innerHTML = "Create Table";_x000D_
document.body.appendChild(btn);_x000D_
btn.addEventListener("click", createTable, true);_x000D_
function createTable(){_x000D_
var div = document.createElement('div');_x000D_
div.setAttribute("id", "tbl");_x000D_
document.body.appendChild(div)_x000D_
document.getElementById("tbl").innerHTML = "<table border = '1'>" +_x000D_
'<tr>' +_x000D_
'<th>Header 1</th>' +_x000D_
'<th>Header 2</th> ' +_x000D_
'<th>Header 3</th>' +_x000D_
'</tr>' +_x000D_
'<tr>' +_x000D_
'<td>Data 1</td>' +_x000D_
'<td>Data 2</td>' +_x000D_
'<td>Data 3</td>' +_x000D_
'</tr>' +_x000D_
'<tr>' +_x000D_
'<td>Data 1</td>' +_x000D_
'<td>Data 2</td>' +_x000D_
'<td>Data 3</td>' +_x000D_
'</tr>' +_x000D_
'<tr>' +_x000D_
'<td>Data 1</td>' +_x000D_
'<td>Data 2</td>' +_x000D_
'<td>Data 3</td>' +_x000D_
'</tr>' _x000D_
};
_x000D_
Here is the latest method using the .map
function in javascript.
Simple table code..
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Tour</th>
<th scope="col">Day</th>
<th scope="col">Time</th>
<th scope="col">Highlights</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
and here is javascript code to append something in the table body.
const data = "some kind of json data or object of arrays";
const tableData = data.map(function(value){
return (
`<tr>
<td>${value.Name}</td>
<td>${value.Day}</td>
<td>${value.Time}</td>
<td>${value.Highlights}</td>
<td class="text-center"><a class="btn btn-primary" href="route.html?id=${value.ID}" role="button">Details</a></td>
</tr>`
);
}).join('');
const tabelBody = document.querySelector("#tableBody");
tableBody.innerHTML = tableData;
This is how to loop through a javascript object and put the data into a table, code modified from @Vanuan's answer.
<body>_x000D_
<script>_x000D_
function createTable(objectArray, fields, fieldTitles) {_x000D_
let body = document.getElementsByTagName('body')[0];_x000D_
let tbl = document.createElement('table');_x000D_
let thead = document.createElement('thead');_x000D_
let thr = document.createElement('tr');_x000D_
_x000D_
for (p in objectArray[0]){_x000D_
let th = document.createElement('th');_x000D_
th.appendChild(document.createTextNode(p));_x000D_
thr.appendChild(th);_x000D_
_x000D_
}_x000D_
_x000D_
thead.appendChild(thr);_x000D_
tbl.appendChild(thead);_x000D_
_x000D_
let tbdy = document.createElement('tbody');_x000D_
let tr = document.createElement('tr');_x000D_
objectArray.forEach((object) => {_x000D_
let n = 0;_x000D_
let tr = document.createElement('tr');_x000D_
for (p in objectArray[0]){_x000D_
var td = document.createElement('td');_x000D_
td.setAttribute("style","border: 1px solid green");_x000D_
td.appendChild(document.createTextNode(object[p]));_x000D_
tr.appendChild(td);_x000D_
n++;_x000D_
};_x000D_
tbdy.appendChild(tr); _x000D_
});_x000D_
tbl.appendChild(tbdy);_x000D_
body.appendChild(tbl)_x000D_
return tbl;_x000D_
}_x000D_
_x000D_
createTable([_x000D_
{name: 'Banana', price: '3.04'}, // k[0]_x000D_
{name: 'Orange', price: '2.56'}, // k[1]_x000D_
{name: 'Apple', price: '1.45'}_x000D_
])_x000D_
</script>
_x000D_
I wrote a version that can parse through a list of objects dynamically to create the table as a string. I split it into three functions for writing the header columns, the body rows, and stitching it all together. I exported as a string for use on a server. My code uses template strings to keep things elegant.
If you want to add styling (like bootstrap), that can be done by adding more html to HEAD_PREFIX
and HEAD_SUFFIX
.
// helper functions
const TABLE_PREFIX = '<div><table class="tg">';
const TABLE_SUFFIX = '</table></div>';
const TABLE_HEAD_PREFIX = '<thead><tr>';
const TABLE_HEAD_SUFFIX = '</tr></thead>';
const TABLE_BODY_PREFIX = '<tbody><tr>';
const TABLE_BODY_SUFFIX = '</tr></tbody>';
function generateTableHead(cols) {
return `
${TABLE_HEAD_PREFIX}
<td>#</td>
${cols.map((col) => `<td>${col}</td>`).join('')}
${TABLE_HEAD_SUFFIX}`;
}
function generateTableBody(cols, data) {
return `
${TABLE_BODY_PREFIX}
${data.map((object, index) => `
<tr><td>${index}</td>
${cols.map((col) => `<td>${object[col]}</td>`).join('')}
</tr>`).join('')}
${TABLE_BODY_SUFFIX}`;
}
/**
* generate an html table from an array of objects with the same values
*
* @param {array<string>} cols array of object columns used in order of columns on table
* @param {array<object>} data array of objects containing data in a single depth
*/
function generateTable(data, defaultCols = false) {
let cols = defaultCols;
if (!cols) cols = Object.keys(data[0]); // auto generate columns if not defined
return `
${TABLE_PREFIX}
${generateTableHead(cols)}
${generateTableBody(cols, data)}
${TABLE_SUFFIX}`;
}
Here's an example use:
const mountains = [
{ height: 200, name: "Mt. Mountain" },
{ height: 323, name: "Old Broken Top"},
]
const htmlTableString = generateTable(mountains );
Slightly shorter code using insertRow
and insertCell
:
function tableCreate(){_x000D_
var body = document.body,_x000D_
tbl = document.createElement('table');_x000D_
tbl.style.width = '100px';_x000D_
tbl.style.border = '1px solid black';_x000D_
_x000D_
for(var i = 0; i < 3; i++){_x000D_
var tr = tbl.insertRow();_x000D_
for(var j = 0; j < 2; j++){_x000D_
if(i == 2 && j == 1){_x000D_
break;_x000D_
} else {_x000D_
var td = tr.insertCell();_x000D_
td.appendChild(document.createTextNode('Cell'));_x000D_
td.style.border = '1px solid black';_x000D_
if(i == 1 && j == 1){_x000D_
td.setAttribute('rowSpan', '2');_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
body.appendChild(tbl);_x000D_
}_x000D_
tableCreate();
_x000D_
Also, this doesn't use some "bad practices", such as setting a border
attribute instead of using CSS, and it accesses the body
through document.body
instead of document.getElementsByTagName('body')[0]
;
<style>
body{
background: radial-gradient(rgba(179,255,0.5),rgba(255,255,255,0.5),rgba(0,0,0,0.2));
text-align: center;
}
#name{
margin-top: 50px;
}
.input{
font-size: 25px;
color: #004d00;
font-weight: 700;
font-family: cursive;
}
#entry{
width: 150px;
height: 40px;
font-size: 23px;
font-family: cursive;
background-color: #001a66;
color: whitesmoke;
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5);
margin: 20px;
}
table{
border-collapse: collapse;
width: 50%;
margin: 50px auto;
background-color: burlywood;
}
table,th,td{
border: 2px solid black;
padding:5px;
}
th{
font-size: 30px;
font-weight: 700;
font-family: Arial;
color: #004d00;
}
td{
font-size: 25px;
color: crimson;
font-weight: 400;
font-family: Georgia;
}
.length{
width: 20%;
}
</style>
<body>
<!-- Code to get student details -->
<div id="container" >
<div class="input">
Name: <input type="text" id="name" class="length" placeholder="eg: Anil Ambani"/>
</div>
<div class="input">
Email: <input type="text" id="mail" class="length" placeholder="eg: [email protected]"/>
</div>
<div class="input">
Phone: <input type="text" id="phn" class="length" placeholder="eg: 9898989898"/>
</div>
<div class="input">
SLNO: <input type="number" id="sln" class="length" placeholder="eg: 1"/>
</div>
<br>
<button id="entry"> I/P ENTRY</button>
</div>
<table id="tabledata">
<tr>
<th> Name</th>
<th> Email</th>
<th> Phone</th>
<th> Slno</th>
</tr>
</table>
</body>
<script>
var entry = document.getElementById('entry');
entry.addEventListener("click",display);
var row = 1;
function display(){
var nam = document.getElementById('name').value;
var emal = document.getElementById('mail').value;
var ph = document.getElementById('phn').value;
var sl = document.getElementById('sln').value;
var disp = document.getElementById("tabledata");
var newRow = disp.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = nam;
cell2.innerHTML = emal;
cell3.innerHTML = ph;
cell4.innerHTML = sl;
row++;
}
</script>
Here is an example of drawing a table using raphael.js. We can draw tables directly to the canvas of the browser using Raphael.js Raphael.js is a javascript library designed specifically for artists and graphic designers.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id='panel'></div>
</body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
paper = new Raphael(0,0,500,500);// width:500px, height:500px
var x = 100;
var y = 50;
var height = 50
var width = 100;
WriteTableRow(x,y,width*2,height,paper,"TOP Title");// draw a table header as merged cell
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");// draw table header as individual cells
y= y+height;
for (i=1;i<=4;i++)
{
var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);//prepare table contents as random data
WriteTableRow(x,y,width,height,paper,i+","+ k + "");// draw a row
y= y+height;
}
function WriteTableRow(x,y,width,height,paper,TDdata)
{ // width:cell width, height:cell height, paper: canvas, TDdata: texts for a row. Separated each cell content with a comma.
var TD = TDdata.split(",");
for (j=0;j<TD.length;j++)
{
var rect = paper.rect(x,y,width,height).attr({"fill":"white","stroke":"red"});// draw outline
paper.text(x+width/2, y+height/2, TD[j]) ;// draw cell text
x = x + width;
}
}
</script>
</html>
Please check the preview image: https://i.stack.imgur.com/RAFhH.png
function addTable() {_x000D_
var myTableDiv = document.getElementById("myDynamicTable");_x000D_
_x000D_
var table = document.createElement('TABLE');_x000D_
table.border = '1';_x000D_
_x000D_
var tableBody = document.createElement('TBODY');_x000D_
table.appendChild(tableBody);_x000D_
_x000D_
for (var i = 0; i < 3; i++) {_x000D_
var tr = document.createElement('TR');_x000D_
tableBody.appendChild(tr);_x000D_
_x000D_
for (var j = 0; j < 4; j++) {_x000D_
var td = document.createElement('TD');_x000D_
td.width = '75';_x000D_
td.appendChild(document.createTextNode("Cell " + i + "," + j));_x000D_
tr.appendChild(td);_x000D_
}_x000D_
}_x000D_
myTableDiv.appendChild(table);_x000D_
}_x000D_
addTable();
_x000D_
<div id="myDynamicTable"></div>
_x000D_
Might not solve the problem described in this particular question, but might be useful to people looking to create tables out of array of objects:
function createTable(objectArray, fields, fieldTitles) {_x000D_
let body = document.getElementsByTagName('body')[0];_x000D_
let tbl = document.createElement('table');_x000D_
let thead = document.createElement('thead');_x000D_
let thr = document.createElement('tr');_x000D_
fieldTitles.forEach((fieldTitle) => {_x000D_
let th = document.createElement('th');_x000D_
th.appendChild(document.createTextNode(fieldTitle));_x000D_
thr.appendChild(th);_x000D_
});_x000D_
thead.appendChild(thr);_x000D_
tbl.appendChild(thead);_x000D_
_x000D_
let tbdy = document.createElement('tbody');_x000D_
let tr = document.createElement('tr');_x000D_
objectArray.forEach((object) => {_x000D_
let tr = document.createElement('tr');_x000D_
fields.forEach((field) => {_x000D_
var td = document.createElement('td');_x000D_
td.appendChild(document.createTextNode(object[field]));_x000D_
tr.appendChild(td);_x000D_
});_x000D_
tbdy.appendChild(tr); _x000D_
});_x000D_
tbl.appendChild(tbdy);_x000D_
body.appendChild(tbl)_x000D_
return tbl;_x000D_
}_x000D_
_x000D_
createTable([_x000D_
{name: 'Banana', price: '3.04'},_x000D_
{name: 'Orange', price: '2.56'},_x000D_
{name: 'Apple', price: '1.45'}_x000D_
],_x000D_
['name', 'price'], ['Name', 'Price']);
_x000D_
I hope you find this helpful.
HTML :
<html>
<head>
<link rel = "stylesheet" href = "test.css">
<body>
</body>
<script src = "test.js"></script>
</head>
</html>
JAVASCRIPT :
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < 101; row += 1) {
tableString += "<tr>";
for (col = 1; col < 11; col += 1) {
tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
<!DOCTYPE html>
<html>
<body>
<p id="p1">
<b>Enter the no of row and column to create table:</b>
<br/><br/>
<table>
<tr>
<th>No. of Row(s) </th>
<th>No. of Column(s)</th>
</tr>
<tr>
<td><input type="text" id="row" value="4" /> X</td>
<td><input type="text" id="col" value="7" />Y</td>
</tr>
</table>
<br/>
<button id="create" onclick="create()">create table</button>
</p>
<br/><br/>
<input type="button" value="Reload page" onclick="reloadPage()">
<script>
function create() {
var row = parseInt(document.getElementById("row").value);
var col = parseInt(document.getElementById("col").value);
var tablestart="<table id=myTable border=1>";
var tableend = "</table>";
var trstart = "<tr bgcolor=#ff9966>";
var trend = "</tr>";
var tdstart = "<td>";
var tdend = "</td>";
var data="data in cell";
var str1=tablestart + trstart + tdstart + data + tdend + trend + tableend;
document.write(tablestart);
for (var r=0;r<row;r++) {
document.write(trstart);
for(var c=0; c<col; c++) {
document.write(tdstart+"Row."+r+" Col."+c+tdend);
}
}
document.write(tableend);
document.write("<br/>");
var s="<button id="+"delete"+" onclick="+"deleteTable()"+">Delete top Row </button>";
document.write(s);
var relod="<button id="+"relod"+" onclick="+"reloadPage()"+">Reload Page </button>";
document.write(relod);
}
function deleteTable() {
var dr=0;
if(confirm("It will be deleted..!!")) {
document.getElementById("myTable").deleteRow(dr);
}
}
function reloadPage(){
location.reload();
}
</script>
</body>
</html>
Source: Stackoverflow.com