how to make new table columns dynamically - javascript

At the moment only a cell is added to theclicked link's row and the bottom columns are not shown.
i would like the js code below to work such that if i click onany link say link 2 none of the top cells in the column are displayed apart from starting with the one inline with this link 2 and those below in the newly created column.
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = element.parentElement.parentElement;
var td = document.createElement("td");
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
tr.appendChild(td);
}
</script>
I have been trying out this code:
function appendColumn() {
var tbl = document.getElementById('my_table');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < tbl.rows.length; i++) {
var newcell = tbl.rows[i].insertCell(tbl.rows[i].cells.length);
for (var j = 0; j < colCount; j++) {
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
}
but it doesn't do it.
jquery is also welcome

jsFiddle
If I correctly understood you need something like this:
function addColumn(element) {
var tr = element.parentElement.parentElement;
var trs = tr.parentElement.querySelectorAll( "tr" );
var trN = nInArray( trs, tr );
var tds = trs[ trs.length - 1 ].querySelectorAll( "td" );
var tdNextN = parseInt( tds[ tds.length - 1 ].querySelector( "input" ).name.match( /BX(\d+)_NAME\[\]/ )[ 1 ] );
if ( trN == 0 ) {
tdNextN++;
}
for ( var i = 0; i < trs.length; i++ ) {
var td = document.createElement( "td" );
if ( i >= trN ) {
td.innerHTML = "<label>Name" + tdNextN + "</label>";
td.innerHTML += "<input type=\"text\" required=\"required\" name=\"BX" + tdNextN + "_NAME[]\" />";
}
trs[ i ].appendChild( td );
}
}
function nInArray( array, object ) {
for ( var i = 0; i < array.length; i++ ) {
if ( array[ i ] === object ) {
return i;
}
}
return -1;
}

And that's what I think is required:
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
}
item.appendChild(td);
});
}
Fiddle with this

Take a look of jquery
$('#datble').find('tbody').append('<tr><td>TD 1</td><td>TD 2</td></tr>');
//or you can prepend
$('#datble').find('tbody').prepend('<tr><td>TD 1</td><td>TD 2</td></tr>');

You can also try this throught jquery:
var html = "";
after
html += '<tr><td>TD</td></tr>';
or
html += '<tr>';
html += '<td>';
html += 'TD';
html += '</td>';
html += '</tr>';
and after all do this
$('#' + table_id ).append(html);

Related

rearrange/decrement row and cell id after deleting dynamically added rows javascript

I have a table with a default row and I am adding new rows dynamically with a button click, incrementing the ID of the tr and the innerText of the first td with a counter. I am trying to rearrange the ID's after deleting a row. Suppose I have 5 rows and I delete row nr 3, the 4th row should have the ID 3, and the 5th should have ID 4 etc. And also whena adding new rows it should rearrange the row ID's.
Here what I have so far. I have been trying but with no success or I dont get the desired results. Could anyone help me in the right direction?
<table class="table text-center table-borderless" id="rfqTable" style="font-size: 12px;">
<thead>
<tr>
<th>Item</th>
<th>Descr</th>
<th>Quantity</th>
<th>One Time</th>
<th>Supplier</th>
</tr>
</thead>
<tbody>
<tr id="1" class="tableRow">
<td class="item">1</td>
<td><textarea name="item[1]" rows="3" cols="90" maxlength="500"></textarea></td>
<td><input type="number" name="amount[1]"/></td>
<td><input type="checkbox" name="oneTime[1]" value="1"></td>
<td><input type="checkbox" name="supplier[1]" value="1"></td>
</tr>
</tbody>
</table>
Adding row:
var counter = 1;
var limit = 5;
document.getElementById("newItemBoxButton").addEventListener("click", function(){
if (counter == limit)
{
alert("Max row is 5!");
}
else
{
counter ++;
var table = document.getElementById("rfqTable");
var row = table.insertRow(-1);
row.setAttribute('id', counter );
var cell0 = row.insertCell(0);
cell0.innerHTML = counter;
cell0.setAttribute('id', 'item');
var cell1 = row.insertCell(1);
cell1.innerHTML = '<textarea name="item[' + counter + ']" rows="3" cols="90" maxlength="500"></textarea>';
var cell2 = row.insertCell(2);
cell2.innerHTML = '<input type="number" name="amount[' + counter + ']" style="width: 50px;"/>';
var cell3 = row.insertCell(3);
cell3.innerHTML = '<input type="checkbox" name="oneTime[' + counter + ']" value="1">';
var cell4 = row.insertCell(4);
cell4.innerHTML = '<input type="checkbox" name="supplier[' + counter + ']" value="1">';
var cell5 = row.insertCell(5);
cell5.innerHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
});
Deleting row:
function deleteRow(rowid)
{
var row = document.getElementById(rowid);
var table = row.parentNode;
while (table && table.tagName != 'TABLE')
{
table = table.parentNode;
if (!table)
{
return;
}
table.deleteRow(row.rowIndex);
counter--;
}
var table = document.getElementById('rfqTable');
var trRows = table.getElementsByTagName('tr');
var tdRows = table.getElementsByTagName('td');
for (var i = 0; i < trRows.length; i++)
{
trRows[i].id = counter;
}
for (var i = 0; i < tdRows.length; i++)
{
document.getElementById("item").innerText = counter;
}
}
After deleting a row, all the row id's turn into the same id, and the td item doesnt change at all.
In deleteRow function, why you have added this -
for (var i = 0; i < trRows.length; i++) {
trRows[i].id = counter;
}
You are assigning same value to all rows since your counter variable is not changing. It should be like this -
trRows[i].id = i + 1; // added + 1 since you want to start from 1 not 0
ok, I got a fix. I targeted the first column of every row and changed that value. For loop has to start at 1, else it will also target the first th. So now the IDs will be rearranged after deleting a row and the value will always start at 1.
var table = document.getElementById('rfqTable');
for (var i = 1; i < table.rows.length; i++)
{
var firstCol = table.rows[i].cells[0];
firstCol.innerText = i;
}

javascript to add rows to a table dynamically

I'm trying to figure out how to use javascript to add rows to a table dynamically. I tested without the table and can get the data but am stumped on populating the table.
I have a function call on a button that is supposed to populate the table. below is my code so far:
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody>
<!--<tr class="pure-table-odd">
<td>Jim</td>
<td>2</td>
</tr>-->
</tbody>
</table>
function getData()
{
var soData = JSON.parse(staffOrders);
var i = 0;
var c = getRowCount();
//build table
var table = document.getElementById("tblData");
while (i <= c) {
//alert(soData[i].staffName + " had " + soData[i].orders + " orders.");
//"<td>" + soData[i].staffName + "</td>"
//"<td>" + soData[i].orders + "</td>"
i++;
}
}
You need to use the DOM API for the HTML table element. It's documented at
http://www.w3schools.com/jsref/dom_obj_table.asp
Here's an example taken from http://www.w3schools.com/jsref/met_table_insertrow.asp :
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
function getData() {
var responseData = [{
"staffName": "Wilkerson Bowman",
"orders": 26
}, {
"staffName": "Finley Nunez",
"orders": 26
}, {
"staffName": "Katie Estrada",
"orders": 7
}];
var thead = document.querySelector('#tblData thead');
responseData.forEach(function(data) {
var row = document.createElement('tr');
row.innerHTML = '<td>' + data.staffName + '</td><td>' + data.orders + '</td>';
thead.appendChild(row);
});
}
getData();
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody></tbody>
</table>
try this code
window.onload = function(){
function getData() {
var soData = [{orders : 'order1', staffName : 'staffName1'}, {orders : 'order2', staffName : 'staffName2'}]
var i = 0;
var c = 2;
//build table
var table_body = document.getElementById("tblData").getElementsByTagName('tbody')[0];
while (i <= c) {
var tr = document.createElement('tr');
tr.className = "pure-table-odd"; // add class in tr
var td1 = document.createElement('td');
td1.innerHTML = soData[i].orders;
var td2 = document.createElement('td');
td2.innerHTML = soData[i].staffName;
tr.appendChild(td1);
tr.appendChild(td2);
table_body.appendChild(tr);
i++;
}
};
getData();
}
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody>
<!--<tr class="pure-table-odd">
<td>Jim</td>
<td>2</td>
</tr>-->
</tbody>
</table>

JavaScript loop won't separate <TD> elements

I am using JavaScript to fetch some XML data and loop it in a table. However the TD elements won't separate to a new line.
Here is my HTML:
<div id="gData">
<table class="tftable" border="1">
<tr><th>Date</th><th>Game</th><th>Home</th><th>Draw</th><th>Away</th></tr>
<tr>
<td class="gDate"></td>
<td class="gGame"></td>
<td class="gHome"></td>
<td class="gDraw"></td>
<td class="gAway"></td>
</tr>
</table>
</div>
and here is my JS:
window['gCallback'] = function(data) {
var game_data = data.query.results.rsp.fd.sports.sport.leagues.league.events.event;
for (var i = 0; i < game_data.length; i++) {
$('#gData .gGame').append( '<td>' + game_data[i].homeTeam.name + ' vs ' + game_data[i].awayTeam.name + '</td> ');
$('#gData .gDate').append( '<td>' + game_data[i].startDateTime) + '</td>';
$('#gData .gAway').append( '<td>' + game_data[i].periods.period[i].moneyLine.awayPrice) + '</td>';
$('#gData .gHome').append( '<td>' + game_data[i].periods.period[i].moneyLine.homePrice) + '</td>';
$('#gData .gDraw').append( '<td>' + game_data[i].periods.period[i].moneyLine.drawPrice) + '</td>';
}
};
The data comes back fine from the loop but displays all the dates in one TD, all the Games in the next TD.
You must also create your tr tags dynamically. Here's what I would suggest:
First make sure your table has a thead and tbody.
<table id="my-table">
<thead>
<th>Date</th>
<th>Game</th>
<th>Home</th>
<th>Draw</th>
<th>Away</th>
</thead>
<tbody></tbody>
<table>
Then you can generate your rows dynamically and append them to the tbody element. To save on writing i'll just give an example that isin't based on your code.
var $trs = $(document.createDocumentFragment()), //reduce DOM reflows
data = [{ a:1, b:2, c:3 }],
i = 0,
len = data.length,
rowData, $tr;
for (; i < len; i++) {
rowData = data[i];
$tr = $('<tr>'); //create your row
//append cells, you can also create a function to encapsulate
//that repetitive logic
$tr.append($('<td>').addClass('yourClass').text(rowData.a));
$tr.append($('<td>').addClass('yourOtherClass').text(rowData.b));
$tr.append($('<td>').addClass('yetAnotherClass').text(rowData.c));
//append the tr to the document fragment
$trs.append($tr);
}
//append the document fragment to the tbody
$('#my-table > tbody').append($trs);
It's remarkable how even the simplest task can be butchered by jQuery...
var table = document.getElementById('gData').children[0],
tbody = table.tBodies[0];
window['gCallback'] = function(data) {
var game_data = data.query.results.rsp.fd.sprts.sport.leages.leage.events.event,
len = game_data.length, i, tr;
table.removeChild(tbody);
for( i=0; i<len; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].homeTeam.name));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].startDateTime));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.awayPrice));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.homePrice));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.drawPrice));
tbody.appendChild(tr);
}
table.appendChild(tbody);
};
And this HTML:
<div id="gData">
<table class="tftable" border="1">
<thead>
<tr><th>Date</th><th>Game</th><th>Home</th><th>Draw</th><th>Away</th></tr>
</thead>
<tbody></tbody>
</table>
</div>
Note that you can simplify the above code with a helper function:
function addCellWithText(tr,text) {
return tr.appendChild(document.createElement('td')).appendChild(document.createTextNode(text));
}
Then your loop's contents become:
for(...) {
tr = document.createElement('tr');
addCellWithText(tr,game_data[i].homeTeam.name);
addCellWithText(tr,game_data[i].startDateTime);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.homePrice);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.awayPrice);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.drawPrice);
tbody.appendChild(tr);
}

Create table using Javascript

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.

Can't create 2 tables

I'm trying to dynamically create a table based on user input, and it's working perfectly, however, it is supposed to make a table based on the super input the user gives, so if super is 2, then it loops to create 2 tables. However it is doing everything but that, because if it was, then the tables would be next to each other, not one below each other as I have set the CSS that way. Any ideas?
<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;
var y = 1;
for( var i = 1; i <= num_super; i++){
var theader = '<div style="margin:0 auto;"><table border="1" style="border:1px solid black; float:left;">\n';
for(u = 1; u <= num_rows; u++){
tbody += '<tr>';
for( var j = 0; j < colStart; j++)
{
tbody += '<td style="width:80px; height:70px;">';
tbody += '<sub style="float:right; position:relative; top:24px; z-index:11; ">' + y + '</sub>';
tbody += '</td>';
y++;
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
</script>
<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>
How it should look
It resets the table it created to the new table in current iteration in this line:
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
You have to do something like this:
document.getElementById('wrapper').innerHTML += theader + tbody + tfooter;
In addition to your comment:
var colStart = num_cols / num_super;
Should mabe be:
var colStart = num_cols * num_super;

Categories