I'm trying to put in options to be able to input column/row/width/height for my Javascript table..but can't seem to get it work. I have absolutely no coding background.. just got into this course 1 month ago..
I tried looking up everywhere but I can't make sense of what is happening..
<html>
<body>
<form>
<p>No. of Cols: <input type="text" name="cols" id="cols" value="3" />
</p>
<p> No. of Rows<input type="text" name="rows" id="rows" value="3" />
Sample Cell Data <input type="text" id="sample" /> </p>
<p> Cell Height (in pixels)<input type="text" id="height" />
Cell wdith in pixels<input type="text" id="wdith" /> </p>
<Button onClick="generate()">Generate Table</button>
<button onClick="deleteTable()">Clear Table</button>
</form>
<hr />
<p id=generatedTable> </p>
</body>
<script>
function generate()
var myTable = document.getElementById("generatedTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.create Element('TBODY');
table.appendChild(tableBody);
for (var y=0; y<num_rows; y++)
{
var num_rows = document.getElementById('rows').value;
tableBody.appendChild(tr);
var num_cols = document.getElementById('cols').value;
for (var x=0; x<num_cols; x++)
{
var td = document.createElement('TD');
td.width = 10; td.height = 10; td.align = "center";
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id",cellID.toString());
td.addEventListener("click", function(){cellClicked(this);});
// ... research and add other mouse events!!!
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
}
myTable.appendChild(table);
}
}
</script>
</html>
In the code, you provided the num_rows and num_cols is the number of column/row, width/height is related styles; so, you don't want to do it in javascript, you can provide some styles like this:
.custom-width{
/* some style */
}
then in your code after creating a td:
var td = document.createElement('TD');
td.classList.add('custom-width')
// do other stuff and append it
I think that the best solution to your problem is to use Bootstrap 4 grid; it permit to create responsive tables using only div as rows and columns. In this way you can manage very easily width and height with col-size class.
Install: https://getbootstrap.com/docs/4.3/getting-started/introduction/
Bootstrap grid: https://getbootstrap.com/docs/4.0/layout/grid/
var num_rows and var num_rows should be out of both the for loop.
tr should be declared inside the first for loop because you cannot append to it till it is declared.
for simplicity, I have set the num_rows and 'num_rows' to 5.
for guidance in future how to work with tables you can refer
Traversing an HTML table with JavaScript
var element = document.getElementById("div1");
debugger;
var tableBody = document.createElement('TBODY');
var table= document.createElement('table')
table.appendChild(tableBody);
var num_rows = 5;
var num_cols =5;
for (var y=0; y<5; y++)
{
//document.getElementById('rows').value;
var tr =document.createElement('tr')
//document.getElementById('cols').value;
for (var x=0; x<5; x++)
{
var td = document.createElement('TD');
td.width = 10; td.height = 10; td.align = "center";
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id",cellID.toString());
td.addEventListener("click", function(){cellClicked(this);});
// ... research and add other mouse events!!!
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
tableBody.appendChild(tr);
}
//myTable.appendChild(table);
element.appendChild(table)
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
td
{
border:1px solid;
}
<div id="div1">
</div>
How can I create an array from this table/form? The onclick function formData() from the dynamic table only returns a concatenated string. I need to create an associative array in JSON using the 'device' variable as key, however I'll settle for any sort of array at all. Clearly, I'm not very good at this...
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementById("form");
//var device = document.getElementById('device').value;
//var j;
var obj = [];
for(j=0; j< cellData.length; j++)
{
obj += cellData[j].value;
}
var json = JSON.stringify(obj);
alert (json);
//document.getElementById('result').innerHTML = json;
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
1) This my answer how do this on VueJS and jQuery
2) Vanilla js - CODEPEN - DEMO
// Get DOM elements
const $el = [
'#tmpl',
'#user-count',
'#people-count',
'#form-items',
'#btn-add',
'#form',
].reduce((res, item) => {
const method = item.startsWith('#')
? 'querySelector'
: 'querySelectorAll'
const key = item
.replace(/\W/ig, ' ').trim()
.replace(/\s+\w/g, v => v.trim().toUpperCase())
res[key] = document[method](item)
return res
}, {})
// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()
// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
const peopleCount = +$el.peopleCount.value
const html = Array(peopleCount)
.fill(tmpl)
.join('')
$el.formItems.insertAdjacentHTML('beforeend', html)
})
// Submit form
$el.form.addEventListener('submit', e => {
e.preventDefault()
alert('Submit form by ajax or remove this method for default behavior')
})
// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
// Delete behaviors
if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
e.target.closest('.row').remove()
}
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
I have edited your code,
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementsByTagName("tr");
var obj = [];
for(var i=0;i<cellData.length-1;i++){
obj.push(document.getElementById("i"+i).value);
obj.push(document.getElementById("o"+i).value);
}
alert(JSON.stringify(obj));
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
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() {
//body reference
var body = document.getElementsByTagName("body")[0];
// create elements <table> and a <tbody>
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// cells creation
for (var j = 0; j <= 2; j++) {
// table row creation
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// create element <td> and text node
//Make text node the contents of <td> element
// put <td> at end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row " + j + ", column " + i);
cell.appendChild(cellText);
row.appendChild(cell);
}
//row added to end of table body
tblBody.appendChild(row);
}
// append the <tbody> inside the <table>
tbl.appendChild(tblBody);
// put <table> in the <body>
body.appendChild(tbl);
// tbl border attribute to
tbl.setAttribute("border", "2");
}
<table width="100%" border="1">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td rowspan="2"> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
Slightly shorter code using insertRow and insertCell:
function tableCreate() {
const body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '1px solid black';
for (let i = 0; i < 3; i++) {
const tr = tbl.insertRow();
for (let j = 0; j < 2; j++) {
if (i === 2 && j === 1) {
break;
} else {
const td = tr.insertCell();
td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
td.style.border = '1px solid black';
if (i === 1 && j === 1) {
td.setAttribute('rowSpan', '2');
}
}
}
}
body.appendChild(tbl);
}
tableCreate();
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];
This should work (from a few alterations to your code above).
function tableCreate() {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.style.width = '100%';
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
for (var i = 0; i < 3; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
if (i == 2 && j == 1) {
break
} else {
var td = document.createElement('td');
td.appendChild(document.createTextNode('\u0020'))
i == 1 && j == 1 ? td.setAttribute('rowSpan', '2') : null;
tr.appendChild(td)
}
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
}
tableCreate();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
<div id="myDynamicTable"></div>
Here is the latest method using the .map function in javascript.
You create a table in html and then insert body with javascript.
const data = [{Name:'Sydney', Day: 'Monday', Time: '10:00AM'},{Name:'New York', Day: 'Monday',Time: '11:00AM'},]; // any json data or array of objects
const tableData = data.map(value => {
return (
`<tr>
<td>${value.Name}</td>
<td>${value.Day}</td>
<td>${value.Time}</td>
</tr>`
);
}).join('');
const tableBody = document.querySelector("#tableBody");
tableBody.innerHTML = tableData;
<table border="2">
<thead class="thead-dark">
<tr>
<th scope="col">Tour</th>
<th scope="col">Day</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<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>
This solution will be perfect when you want rows and columns dynamic. You can accept rows and columns as arguments.
function tableCreate(row, col){
let body = document.body;
let tbl = document.createElement('table');
tbl.style.width = '200px';
tbl.style.border = '1px solid black';
for(let i = 0; i < row; i++){
let tr = tbl.insertRow();
for(let j = 0; j < col; j++){
let td = tr.insertCell();
td.appendChild(document.createTextNode(`${i},${j}` ));
td.style.border = '1px solid black';
}
}
body.appendChild(tbl);
}
tableCreate(4,4);
Output -
<!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>
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) {
let body = document.getElementsByTagName('body')[0];
let tbl = document.createElement('table');
let thead = document.createElement('thead');
let thr = document.createElement('tr');
fieldTitles.forEach((fieldTitle) => {
let th = document.createElement('th');
th.appendChild(document.createTextNode(fieldTitle));
thr.appendChild(th);
});
thead.appendChild(thr);
tbl.appendChild(thead);
let tbdy = document.createElement('tbody');
let tr = document.createElement('tr');
objectArray.forEach((object) => {
let tr = document.createElement('tr');
fields.forEach((field) => {
var td = document.createElement('td');
td.appendChild(document.createTextNode(object[field]));
tr.appendChild(td);
});
tbdy.appendChild(tr);
});
tbl.appendChild(tbdy);
body.appendChild(tbl)
return tbl;
}
createTable([
{name: 'Banana', price: '3.04'},
{name: 'Orange', price: '2.56'},
{name: 'Apple', price: '1.45'}
],
['name', 'price'], ['Name', 'Price']);
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);
This is how to loop through a javascript object and put the data into a table, code modified from #Vanuan's answer.
<body>
<script>
function createTable(objectArray, fields, fieldTitles) {
let body = document.getElementsByTagName('body')[0];
let tbl = document.createElement('table');
let thead = document.createElement('thead');
let thr = document.createElement('tr');
for (p in objectArray[0]){
let th = document.createElement('th');
th.appendChild(document.createTextNode(p));
thr.appendChild(th);
}
thead.appendChild(thr);
tbl.appendChild(thead);
let tbdy = document.createElement('tbody');
let tr = document.createElement('tr');
objectArray.forEach((object) => {
let n = 0;
let tr = document.createElement('tr');
for (p in objectArray[0]){
var td = document.createElement('td');
td.setAttribute("style","border: 1px solid green");
td.appendChild(document.createTextNode(object[p]));
tr.appendChild(td);
n++;
};
tbdy.appendChild(tr);
});
tbl.appendChild(tbdy);
body.appendChild(tbl)
return tbl;
}
createTable([
{name: 'Banana', price: '3.04'}, // k[0]
{name: 'Orange', price: '2.56'}, // k[1]
{name: 'Apple', price: '1.45'}
])
</script>
<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: AnilAmbani#gmail.com"/>
</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>
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 );
var btn = document.createElement('button');
btn.innerHTML = "Create Table";
document.body.appendChild(btn);
btn.addEventListener("click", createTable, true);
function createTable(){
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>'
};
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>'
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 creatTable(row = 10, col = 6) {
var table = "<table style ='margin-left: auto;margin-right: auto; border-collapse: collapse; width: 70%; ' >";
document.write(table);
for (var h = 1; h < parseInt(col); h++) {
th = "<th style='border: 3px solid #ddd;padding: 8px; padding-top: 12px;padding-bottom: 12px;text-align: center;background-color: #f5cf78;color: white;'>" + "I\'m Header";
document.write(th);
th += "</th>";
}
for (var i = 1; i < parseInt(row); i++) {
tr = "<tr style='background: ; :hover{background: #ffff99}'>";
document.write(tr);
tr += "</tr>";
for (var j = 1; j < parseInt(col); j++) {
td = "<td style='border: 3px solid #ddd; padding: 8px;'>" + "I\'m cell no." + i + "," + j;
document.write(td);
td += "</td>";
}
tr += "</tr>";
}
table = "</table>";
}
console.log(creatTable())
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>JavaScript...</h1>
<h2>Hello!</h2>
<h3>This Table Created by JavaScript ©
<font color=# ff0026>Geologist / Mohamed Yasser</font>
</h3>
<script src="main.js"></script>
</body>
</html>
You might find this very helpful
<html>
<head>
<title>tABLE IN JS</title>
</head>
<body>
<table border = "1">
<tr>
<th>Plug-in Name</th>
<th>Filename</th>
<th>Description</th>
</tr>
<script language = "JavaScript" type = "text/javascript">
for (i = 0; i<3; i++) {
document.write("<tr><td>");
document.write("Hello world");
document.write("</td><td>");
document.write("Hello China");
document.write("</td><td>");
document.write("Hello USA");
document.write("</td></tr>");
}
</script>
</table>
</body>
</html>
So you create the table head according to the number of columns you want and the rows will depend on the number you specified in the iteration..... i.e this one will be 3.
I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}