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>
Related
I'm trying to set each td as a different image that I have saved as imgn.gif. (n being image number, I have 13 images, img1.gif., img2.gif... img13.gif) I have a code that generates the table now I just can't figure out how to set a background image, preferably so that the n imgn.gif changes to the next index so the next td will have the next image.
this is the code that I have for now. I assume I have to set something differently here: const cellText = document.createTextNode(2);, so it sets background-image instead?
function options ()
{
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(2);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
just add 5 lines in you actual code:
options();
function options() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
const nbImage = 13;
let curImage = 1;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
if (curImage > nbImage) {
curImage = 1;
}
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
const cellText = document.createTextNode(2);
cell.appendChild(cellText);
row.appendChild(cell);
curImage += 1;
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
I've added:
nbImage (13 from your post)
curImage to iterate through your 13 images
After your cell creation, checking the image number:
if (curImage > nbImage) {
curImage = 1;
}
So your fourteenth TD will have the image 1
Your is already created as a DOM element so you can refer it and add a background image:
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
That will add for each TD a backgound image "img1.gif", "img2.gif"... till "img13.gif", after "img1.gif" ... and so on...
You can create a variable (nImage for exemple) starting from 1 to 13 and reset it when up to 13 so it came back to 1. Then use this variable to modify style.backgroundImage of your td :
function options ()
{
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
let nImage = 1 ;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(2);
if (nImage > 13){nImage =1 ;}
cell.style.backgroundImage = "url('yourPathTo/img"+nImage + ".gif')" ;
nImage++ ;
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "31";
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var thead = document.createElement('td');
thead.classList.add("ui-droppable");
thead.appendChild(data[j]);
tre.appendChild(thead);
tbody.appendChild(tre);
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
I'm trying to order the data that I get from my server to match the columns of my table.
My table columns are days from Monday to Sunday. When my data has more than 7items it needs to separate with another td. The td shows me week 1 and when my data has more than 7 items it needs to separate again that shows week 2 etc.
Update
Im now using a snipped verdion of my code.
Hope someone can help me out with this.
Thank you
There's a few things going on in the code that are problematic.
An attempt to add the table cells to the row, and the row to the table, was made on each iteration of the for loop. That would have produced a lot of rows with single cells had it worked.
It didn't work because there was only ever a single instance of tre, the row variable. So that meant the line tbody.appendChild(tre); did nothing, since appendChild won't append an element that already has a parent element.
Because your data was an array of references to HTMLElements with parents, appending them using appendChild did nothing for the same reason.
I've amended the code below to take care of all of these situations.
Firstly, the code will append a clone of the data to the cell if it's an HTMLElement. I expect in your real code you won't need this, but for this example, why not? It then appends the cell to the row and continues to the next data element.
Secondly, when the data iterator is at 7, before it appends the "Week N" header, it appends a clone of the row, if it has cells on it.
Finally, after appending the clone of the row, the code will reset the row variable to a new instance of a tr element, with no cells.
I also made some variable name and formatting changes to your code just so I could more easily work with it.
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "6"; // "31"; Why 31? A week has 7 days...
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
/* Major changes start here */
// if the row has cells
if (tre.querySelectorAll('td').length) {
// clone and append to tbody
tbody.appendChild(tre.cloneNode(true));
// reset table row variable
tre = document.createElement('tr');
}
// then append the Week header
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var td = document.createElement('td');
td.classList.add("ui-droppable");
// Set the value of the cell to a clone of the data, if it's an HTMLElement
// Otherwise, make it a text node.
var value = data[j] instanceof HTMLElement ?
data[j].cloneNode(true) :
document.createTextNode(data[j]);
td.appendChild(value);
tre.appendChild(td);
}
// If the number of data elements is not evenly divisible by 7,
// the remainder will be on the row variable, but not appended
// to the tbody, so do that.
if (tre.querySelectorAll('td').length) {
tbody.appendChild(tre.cloneNode(true));
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
I just started to create something that creates a table with x rows and you can put however many columns in a row that you want. Whenever I attempt to run it, it only creates one cell. How do I fix this?
var xio = parseInt(prompt("How many weighted areas are in this subject?"))
for (i = 5; xio > 0; xio--) {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1";
var firstRow = document.getElementById("myTable").rows[xio];
var x = firstRow.insertCell(0);
x.innerHTML = "New cell";
}
<table id="myTable"></table>
There's no prompt for second input so even if the rest of your code was ok (which it isn't) there'd be only one cell. As far as the cells/columns you need to create them in a loop within the loop that creates the rows. Note how the loops syntax is in demo.
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "NEW CELL";
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
You can simply create table by using the below function
function makeTableHTML(myArray)
{
var result = "<table border=1>";
for(var i=0; i<myArray.length; i++) {
result += "<tr>";
for(var j=0; j<myArray[i].length; j++){
result += "<td>"+myArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
return result;
}
In your code, you are trying to select table.rows[xio] but if xio === 5, the row number 5 doesn't exist yet (because it's iteration 1), so it crashes.
Do it the other way around. Instead of looping by decreasing xio, loop by increasing i.
var xio = parseInt(prompt("How many weighted areas are in this subject?")),
table = document.getElementById("myTable");
for (i = 0; i < xio; i++) {
var row = table.insertRow(0),
cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1";
}
<table id="myTable"></table>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "NEW CELL";
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
I want to delete a row from a table created by JavaScript. i tried the code from different post on this page but doesn't solve it.
function value_pass()
{
var Delete = document.createElement("input");
Delete.type="button";
Delete.name = "del"
Delete.value = "Delete";
Delete.onclick = function(o)
{
var r = o.parentElement.parentElement;
document.getElementById("table").deleteRow(r.rowIndex);
}
var order_no = document.getElementById("Order_no");
var quantity = document.getElementById("quantity");
var type = document.getElementById("Recipe");
var recipe = type.options[type.selectedIndex].text;
var body1 = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute("id","table");
var tblbody = document.createElement("tbody");
tbl.setAttribute("border","2");
var col = document.createElement("td");
for (var j = 0; j < 1; j++)
{
var rows = document.createElement("tr");
for (var i = 0; i < 4; i++)
{
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
var col5 = document.createElement("td");
var col1text = document.createTextNode(order_no.value);
var col2text = document.createTextNode(recipe);
var col3text = document.createTextNode(quantity.value);
var col4text = document.createTextNode();
//also want to put checked values in table row
}
col1.setAttribute("width","150");
col2.setAttribute("width","150");
col3.setAttribute("width","150");
col4.setAttribute("width","150");
col1.appendChild(col1text);
col2.appendChild(col2text);
col3.appendChild(col3text);
col4.appendChild(col4text);
col5.appendChild(Delete);
rows.appendChild(col1);
rows.appendChild(col2);
rows.appendChild(col3);
rows.appendChild(col4);
rows.appendChild(col5);
tblbody.appendChild(rows);
} tbl.appendChild(tblbody);
body1.appendChild(tbl);
}
The function will be called by a button in HTML
its an order form that
and also want to know about the checked values of checkbox to put in the table row.
You can use :
document.getElementById("myTable").deleteRow(0); //Where 0 is your row.
Explained : http://www.w3schools.com/jsref/met_table_deleterow.asp
Edit:
To delete the current row, set this on your button: onclick="deleteRow(this), with the following code in that function:
function deleteRow(t)
{
var row = t.parentNode.parentNode;
document.getElementById("myTable").deleteRow(row.rowIndex);
console.log(row);
}
I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name