i wanted to create an html table using this function to generate a table . in order to test it if it gives any result i made a smaller test using numbers ( instead of my own data ) but it doest work.
here is my code :
function showFinalTable()
{
let finalTableHeading = document.createElement("h3");
finalTableHeading.innerHTML = "Table finale";
let table = document.createElement("table");
table.classList.add("final-table");
let thead = table.createTHead();
let row = thead.insertRow(0);
let headings = [
"Process",
"Arrival Time",
"Total Burst Time",
"Completion Time",
"Turn Around Time",
"Waiting Time",
"Response Time",
];
headings.forEach((element, index) => {
let cell = row.insertCell(index);
cell.innerHTML = element;
});
let tbody = table.createTBody();
for (let i = 0; i < 5; i++) {
let row = tbody.insertRow(i);
let cell = row.insertCell(0);
cell.innerHTML = "P" + (i + 1);
cell = row.insertCell(1);
cell.innerHTML = 5;
cell = row.insertCell(2);
cell.innerHTML = 7;
cell = row.insertCell(3);
cell.innerHTML = 8;
cell = row.insertCell(4);
cell.innerHTML = 15;
cell = row.insertCell(5);
cell.innerHTML = 13;
cell = row.insertCell(6);
cell.innerHTML = 17;
}
}
You need to also appendChild the elements you create with createElement.
Adding this line at the end makes it work: document.body.appendChild(table);
Full snippet, click "Run" to see output:
function showFinalTable() {
let finalTableHeading = document.createElement("h3");
finalTableHeading.innerHTML = "Table finale";
document.body.appendChild(finalTableHeading);
let table = document.createElement("table");
table.classList.add("final-table");
let thead = table.createTHead();
let row = thead.insertRow(0);
let headings = [
"Process",
"Arrival Time",
"Total Burst Time",
"Completion Time",
"Turn Around Time",
"Waiting Time",
"Response Time",
];
headings.forEach((element, index) => {
let cell = row.insertCell(index);
cell.innerHTML = element;
});
let tbody = table.createTBody();
for (let i = 0; i < 5; i++) {
let row = tbody.insertRow(i);
let cell = row.insertCell(0);
cell.innerHTML = "P" + (i + 1);
cell = row.insertCell(1);
cell.innerHTML = 5;
cell = row.insertCell(2);
cell.innerHTML = 7;
cell = row.insertCell(3);
cell.innerHTML = 8;
cell = row.insertCell(4);
cell.innerHTML = 15;
cell = row.insertCell(5);
cell.innerHTML = 13;
cell = row.insertCell(6);
cell.innerHTML = 17;
}
document.body.appendChild(table);
}
showFinalTable()
Related
I am building a table with JavaScript. If you check the link you can see it is all in one column, but I need the name. prices, and images in separate columns. I am honestly not sure where to start to do this, so I'm looking for some help.
https://jsfiddle.net/wL28gd10/
JS
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto =
["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table"),
row = table.insertRow();
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
// Brreak into next row
var next = i + 1;
if (next%perrow==0 && next!=itemName.length) {
row = table.insertRow();
}
}
// Loop through itemPrice array
for (var i = 0; i < itemPrice.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPrice.length) {
row = table.insertRow();
}
}
// Loop through itemPhoto array
for (var i = 0; i < itemPhoto.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPhoto.length) {
row = table.insertRow();
}
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
Just create all of your columns in one loop, like:
for (var i = 0; i < itemName.length; i++) {
var row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Add cell
cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
You only really need one loop.
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto = ["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table");
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
let row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
table { border-collapse: collapse; }
table tr td {
border: 1px solid black;
padding: 10px;
background-color: white;
}
<div id="menu-table"></div>
I'm doing a school project in which I'm creating web pages to allow users to input and then display it on another page. I am only using JavaScript, HTML and CSS for the web pages.
On the "Create An Event" page there is a form. I have saved all the input into local storage but now I am not sure how to retrieve the data to display it on the "Events Created" page (which shows the past events that the user has created).
Here is my JavaScript code:
document.addEventListener("DOMContentLoaded", docIsReady);
var eventHist;
function docIsReady() {
eventHist = localStorage.getItem("createEvent");
if (eventHist == null) {
eventHist = [];
} else {
eventHist = JSON.parse(eventHist);
}
//building of the table
for (var i = 0; i < eventHist.length; i++) {
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = eventHist[i].name;
cell2.innerHTML = eventHist[i].positions;
cell3.innerHTML = eventHist[i].venue;
cell4.innerHTML = eventHist[i].date;
cell5.innerHTML = eventHist[i].timeStart;
cell6.innerHTML = eventHist[i].timeEnd;
}
}
function addHistory() {
var obj;
var name = document.getElementById("name").value;
if (!checkExisting(name)) {
var positions = document.getElementById("pos").value;
var venue = document.getElementById("venue").value;
var date = document.getElementById("date").value;
var starttime = document.getElementById("timeStart").value;
var endtime = document.getElementById("timeEnd").value;
obj = {
"name": name,
"venue": venue,
"date": date,
"timeStart": starttime,
"timeEnd": endtime
};
eventHist.push(obj)
localStorage.setItem("createEvent", JSON.stringify(obj));
}
//add to table
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = obj.name;
cell2.innerHTML = obj.positions;
cell3.innerHTML = obj.venue;
cell4.innerHTML = obj.date;
cell5.innerHTML = obj.timeStart;
cell6.innerHTML = obj.timeEnd;
}
function sortTable() {
eventHist.sort(function(obj1, obj2) {
if (obj1.date > obj2.date)
return 1;
else if (obj1.date < obj2.date)
return -1;
else
return 0;
});
console.log("Sorted");
//reload table
var tableRow = document.querySelectorAll("#list tr");
console.log(tableRow);
console.log("no of rows=" + tableRow.length);
for (var i = 0; i < eventHist.length; i++) {
var row = document.getElementById("list").insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = eventHist[i].name;
cell2.innerHTML = eventHist[i].positions;
cell3.innerHTML = eventHist[i].venue;
cell4.innerHTML = eventHist[i].date;
cell5.innerHTML = eventHist[i].timeStart;
cell6.innerHTML = eventHist[i].timeEnd;
}
document.getElementById("list").style.display = "table";
}
Here is my HTML code:
<table border="1px" id="list" onload="addRow();">
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<!--<th>Points Awarded</th>-->
</tr>
</table>
I have to get the data printed like the below format using document object model. I am having the problem in creating the below html.
name1 name2 name3
50 48 56
name4 name5 name6
52 58 49
example using below format:
var table = document.createElement("table");
var row = document.createElement("row");
Create a element
var table = document.createElement("table");
Create an empty element and add it to the 1st position of the table:
var row = table.insertRow(0);
Insert new cells ( elements) at the 1st and 2nd position of the "new" 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";
See reference
Use tr instead of row
var row0 = document.createElement("tr");
Here is a quick start for what you want to do:
var table = document.createElement("table");
var row0 = document.createElement("tr");
var a0 = document.createElement("td");
a0.textContent = "name1";
var a1 = document.createElement("td");
a1.textContent = "name2";
var a2 = document.createElement("td");
a2.textContent = "name3";
var row1 = document.createElement("tr");
var b0 = document.createElement("td");
b0.textContent = "50";
var b1 = document.createElement("td");
b1.textContent = "48";
var b2 = document.createElement("td");
b2.textContent = "56";
row0.appendChild(a0);
row0.appendChild(a1);
row0.appendChild(a2);
row1.appendChild(b0);
row1.appendChild(b1);
row1.appendChild(b2);
table.appendChild(row0);
table.appendChild(row1);
document.body.appendChild(table);
We can use insertRow function of table to create new row.
find the below code:
var table = document.createElement("table");
//to create first row
var row = table.insertRow(0);
// first row columns
var col = row.insertCell(0);
col.textContent = "name1";
col = row.insertCell(1);
col.textContent = "name2";
col = row.insertCell(2);
col.textContent = "name3";
// for second row
row = table.insertRow(1);
// for second row columns
col = row.insertCell(0);
col.textContent = "50";
col = row.insertCell(1);
col.textContent = "48";
col = row.insertCell(2);
col.textContent = "56";
document.body.appendChild(table);
jsfiddle
If you have your data stored in an object you can do this programmatically:
var data = {
name1: 50,
name2: 48,
name3: 56,
name4: 52,
name5: 58,
name6: 49
};
function buildTable(data) {
// grab the headings from the object
var headings = Object.keys(data);
var cells = [], rows = [];
// for each heading, push it and its data value into the cell array
headings.forEach(function (heading, i) {
var value = data[headings[i]];
cells.push('<td>' + heading + '<br/>' + value + '</td>');
// when we reach the end of the row, brace the cell data with
// row tags, and clear the cells array
if ((i + 1) % 3 === 0) {
rows = rows.concat('<tr>' + cells.join('') + '</tr>');
cells = [];
}
});
// return the complete table html
return '<table>' + rows.join('') + '</table>'
}
// grab the body tag and insert the table html as the first child
var body = document.querySelector('body');
body.insertAdjacentHTML('afterbegin', buildTable(data));
DEMO
I'm having trouble attaching an onclick event to my dynamic table rows.
What I have is here:
function parseOrderLine(data) {
var obj = JSON.parse(data);
if (obj.length > 0) {
var tbl = document.createElement('table');
var row = tbl.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "Code";
cell = row.insertCell(1);
cell.innerHTML = "Size";
cell = row.insertCell(2);
cell.innerHTML = "Description";
cell = row.insertCell(3);
cell.innerHTML = "Type";
cell = row.insertCell(4);
cell.innerHTML = "Price";
cell.style.textAlign = "right";
for (var i = 0; i < obj.length; i++) {
row = tbl.insertRow(i + 1);
row.className = "results_row";
cell = row.insertCell(0);
cell.innerHTML = obj[i].Code;
cell = row.insertCell(1);
cell.innerHTML = obj[i].Size;
cell = row.insertCell(2);
cell.innerHTML = obj[i].Description;
cell = row.insertCell(3);
cell.innerHTML = obj[i].Type;
cell = row.insertCell(4);
cell.innerHTML = parseFloat(obj[i].Price).toFixed(2);
cell.style.textAlign = "right";
//row.addEventListener("click", function(){ alert('listen'); });
row.onclick = (function(){ alert('click'); });
}
return tbl.outerHTML;
}
else { ...
As you can see I have tried both setting the onclick event and adding a listener. Neither seem to work.
I'm hoping someone can tell me I'm just being crazy and have overlooked something obvious. ;0)
Any help appreciated guys.
Thanks for reading.
Jas
Your problem is on the tbl.outerHTML.
When you add an event listener using addEventListener, Javascript does not add the method to your HTML code in the onclick attribute, it is added only to the DOM. So when you use tbl.outerHTML you listener isn't added to the returned HTML code. The same is applicable for the row.onclick = function()...
If you want to keep the event listener when using outerHTML I suggest you go with setAttribute:
function createTable()
{
var obj = [1,2,3,4,5];
var tbl = document.createElement('table');
var row = tbl.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "Code";
cell = row.insertCell(1);
cell.innerHTML = "Size";
cell = row.insertCell(2);
cell.innerHTML = "Description";
cell = row.insertCell(3);
cell.innerHTML = "Type";
cell = row.insertCell(4);
cell.innerHTML = "Price";
cell.style.textAlign = "right";
for (var i = 0; i < obj.length; i++) {
row = tbl.insertRow(i + 1);
row.className = "results_row";
cell = row.insertCell(0);
cell.innerHTML = obj[i].Code;
cell = row.insertCell(1);
cell.innerHTML = obj[i].Size;
cell = row.insertCell(2);
cell.innerHTML = obj[i].Description;
cell = row.insertCell(3);
cell.innerHTML = obj[i].Type;
cell = row.insertCell(4);
cell.innerHTML = parseFloat(obj[i].Price).toFixed(2);
cell.style.textAlign = "right";
//row.addEventListener("click", function(){ alert('listen'); });
row.setAttribute('onclick', "(function(){ alert('click'); })()");
}
return tbl.outerHTML;
}
document.getElementById('test').innerHTML = createTable();
<div id="test"></div>
HOWEVER it's not the best solution, you should not use outerHTML when you want in fact use the object you just created (in your case, the table). You should add it in the DOM using the appendChild method, doing this way you can use addEventListener:
function createTable()
{
var obj = [1,2,3,4,5];
var tbl = document.createElement('table');
var row = tbl.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "Code";
cell = row.insertCell(1);
cell.innerHTML = "Size";
cell = row.insertCell(2);
cell.innerHTML = "Description";
cell = row.insertCell(3);
cell.innerHTML = "Type";
cell = row.insertCell(4);
cell.innerHTML = "Price";
cell.style.textAlign = "right";
for (var i = 0; i < obj.length; i++) {
row = tbl.insertRow(i + 1);
row.className = "results_row";
cell = row.insertCell(0);
cell.innerHTML = obj[i].Code;
cell = row.insertCell(1);
cell.innerHTML = obj[i].Size;
cell = row.insertCell(2);
cell.innerHTML = obj[i].Description;
cell = row.insertCell(3);
cell.innerHTML = obj[i].Type;
cell = row.insertCell(4);
cell.innerHTML = parseFloat(obj[i].Price).toFixed(2);
cell.style.textAlign = "right";
row.addEventListener("click", (function(){ alert('click'); }));
}
return tbl;
}
document.getElementById('test').appendChild(createTable());
<div id="test"></div>
I am adding rows and cols to html table programatically using Javascript:
for (var i = 0; i < results.length; i++) {
table = document.getElementById("EntityRecords");
rowCount = table.rows.length;
row = table.insertRow(rowCount);
row.id = results[i].LeadId;
row.className = "EntityRecordsRow";
cell1 = row.insertCell(0);
element = document.createElement("input");
element.type = "checkbox";
element.name = "chkbox[]";
cell1.appendChild(element);
cell1.className = "EntityRecordsCol";
cell2 = row.insertCell(1);
cell2.innerHTML = results[i].FirstName + " " + results[i].LastName;
}
On button click event, I need to find selected checkbox. I am reading the table cells using below code but checkbox cell checked property is undefined:
function OnRecordSelectionBtnClick() {
var table = document.getElementById("EntityRecords");
for (var i = 0, row; row = table.rows[i]; i++) {
var col = row.cells[0];
if (col.checked) {
var selectedText = row.cells[1].innerHTML;
alert(selectedText);
}
}
}
Any suggestions?
if ( col.firstElementChild.checked ), not if ( col.checked ). col is td element and its first child is input that has checked property.