Unable to generate table after clearing table - javascript

I'm working on a project but am stuck on the fact that I'm unable to generate a new table after resetting the previous table.
What I would like to do is to let a user reset the table using the button and then generate another one if needed, and not needing him to reload the page. However, I am unsure why my codes only allow me to reset the table but am unable to generate another table.
Any help on this would be greatly appreciated.
function generate() {
var myTable = document.getElementById("generatedTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
myTable.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
var parentElement = removeTab.parentElement;
parentElement.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<table id="generatedTable" onmouseover="mouseOver()" onmouseout="mouseOut()"></table>

You were using the id "generatedTable" in a confusing way, at the same time for the newly generated table and for the table you already had in your html file. And at the end you were removing the wrapper table instead of the newly generated one.
It is maybe easier to understand if you use a target element and add the table in it:
const wrapper = document.getElementById('table-wrapper');
function generate() {
var table = document.createElement('TABLE');
table.id = 'generatedTable';
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
wrapper.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
wrapper.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<div id="table-wrapper"></div>

Related

Make table which have cells 10x10 and every cells have inside number from 1 to 100

Need to make table which have numbers from 1 to 100, and it should be 10x10 cells. I make cells 10x10 but result fill every grid line from 1 to 10, how to make every line like that 1 to 10, 11 to 20 and to 100 like that ? Thank you for attention to my problem.
function generate_table() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let i = 1; i < 11; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 10; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(i);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
tbl.setAttribute("border", "1");
}
<form action="#">
<input type="button" value="Generate a table" onclick="generate_table()">
</form>
function generate_table() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let y = 0; y < 10; y++) {
const row = document.createElement("tr");
for (let x = 0; x < 10; x++) {
const cell = document.createElement("td");
const cellText = document.createTextNode((x + 10 * y) + 1);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
tbl.setAttribute("border", "1");
}
<form action="#">
<input type="button" value="Generate a table" onclick="generate_table()">
</form>

How can i insert a label text in a table cell

I have a table which i am dynamically generating based on user input. I am trying to insert a label text into table cell on button click. onclick of button a label text of a demo method should be inserted into table cells. Can someone suggest me how can i do this?
Thanks.
Creating Table:
function CreateTable(){
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById('myDynamicTable');
var table = document.createElement('table');
table.setAttribute("contenteditable", "true");
table.border = "1";
table.id = "myTable";
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
Button:
<asp:Button ID="button1" Text="button" runat="server" OnClick="demo" />
C# code:
public void demo()
{
TableCell tcell = new TableCell();
RadLabel rlbl = new RadLabel();
rlbl.Text = "test";
tcell.Controls.Add(rlbl);
}
protected void demo(object sender, EventArgs e)
{
demo();
}
To give you a start using Javascript, you can use below code as a starting point.
window.onload=function(){
CreateTable();
}
function CreateTable(){
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById('myDynamicTable');
var table = document.createElement('table');
table.setAttribute("contenteditable", "true");
table.border = "1";
table.id = "myTable";
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
rowCnt = 3; //document.getElementById('txtrows').value;
cellCnt =2; //document.getElementById('txtcols').value;
for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function demo(){
var myTable=document.getElementById('myTable');
var cell=myTable.rows[0].cells[1];
var label = document.createElement('label');
label.id="lbl-"+cell.cellIndex;
label.innerText="This is label text";
cell.appendChild(label);
}
<input type="button" onclick="demo()" value="Create Label" />
<div id="myDynamicTable"></div>

Creating a JS function that colors a specific cell

I am trying to create a separate function that once a table has been generated, a value x and y can be placed within the input and it will highlight the desired cell a certain colour.
My issue arises when I try to select the cell specifically, my code breaks down at
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
// functions to create values of r and c
function GenerateTable() {
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
//selector function
function SelectCell() {
//grab value from the input x and y
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
//insert the value of x and y into an array retriever
var rowIndex = document.getElementById("valy").value;
var cellIndex = document.getElementById("valx").value;
//*********BREAKS DOWN HERE*******
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
change.style.backgroundColor = "red";
//change color of specific coord
}
<label>Rows</label>
<input type="number" id="irow">
<label>Cols</label>
<input type="number" id="icol">
<input type="submit" id="smit1">
<input type="number" id="valx" placeholder="x">
<input type="number" id="valy" placeholder="y">
<input type="submit" id="smit2">
<table id="table">
</table>
I'm not sure you can chain it like this:
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
I think what you want is:
//grab value from the input x and y
var rowIndex = +document.getElementById('valy').value;
var cellIndex = +document.getElementById('valx').value;
// Get reference to the table
var table = document.getElementById('table');
// Get the tr of the table with the index rowIndex
var tr = table.querySelectorAll('tr')[rowIndex];
// Query the selected row for all column elements and select the one at the needed index
var change = tr.querySelectorAll('td')[cellIndex];
NOTE: It's probably best to validate the values in the input before trying to retrieve the DOM element to ensure the code does not break if the user enters a non integer value or a value which is out of bounds
Since I finished it anyway:
Here is a working example
var irow = document.querySelector('#irow');
var icol = document.querySelector('#icol');
var smit1 = document.querySelector('#smit1');
var valx = document.querySelector('#valx');
var valy = document.querySelector('#valy');
var smit2 = document.querySelector('#smit2');
function GenerateTable() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
tbl.setAttribute('class', 'generated');
tbl.appendChild(tblBody);
body.appendChild(tbl);
smit1.disabled = true;
irow.disabled = true;
icol.disabled = true;
smit2.disabled = false;
valx.disabled = false;
valy.disabled = false;
}
function SelectCell() {
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
var rowIndex = valy.value;
var cellIndex = valx.value;
var change = document.querySelector('table.generated tbody').children[rowIndex].children[cellIndex];
change.style.backgroundColor = "red";
}
smit1.addEventListener('click', GenerateTable);
smit2.addEventListener('click', SelectCell);
table.generated td {
width: 10px;
height: 10px;
border: 1px solid #000000;
}
.width100 {
width: 100%;
}
<body>
<div class="width100">
<input type="number" id="irow" placeholder="rows">
<input type="number" id="icol" placeholder="cols">
<input type="submit" id="smit1">
</div>
<div class="width100">
<input type="number" id="valx" disabled="true" placeholder="x">
<input type="number" id="valy" disabled="true" placeholder="y">
<input type="submit" id="smit2" disabled="true">
</div>
</body>

Calculate a new AveValue in TableCell while adding new Columns using JavaScript-not JQuery

I have a <th> header row with a stated class, and one fixed row with a stated class. Both are contenteditable. I'm adding new rows and new columns. I want to calculate the AverageValue in the final cell. I have tried the code on a fixed number of rows and it works, but when I try it this way it is only taking in the number of columns, not the DATA inserted. It is also not recognizing the row DATA. I'm clearly missing a function?!
I'm at the stage where I need an extra pair of eyes.
JavaScript:
func = function() {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function() {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-");
}
}
createCell = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute('placeholder', '' - '');
cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute("placeholder", "-");
cell.appendChild(div); // append DIV to the table cell
}
addColumn = function() {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
}
}
}
HTML:
<table class="tg" id="mytable">
<tr>
<th class="tg-s6z2" contenteditable="true">Student Name</th>
<th class="tg-s6z2" contenteditable="true">Student ID</th>
<th class="tg-s6z2" contenteditable="true">Assignment 1</th>
<th class="tg-s6z2" contenteditable="true">Final Grade</th>
</tr>
<tr>
<td class="tg-031e" contenteditable="true">Student1</td>
<td class="tg-031e" contenteditable="true">StudentNo</td>
<td class="tg-0ord" contenteditable="true"></td>
<td class="tg-0ord" contenteditable="true"></td>
</tr>
</table>
<button id="btnFinalGrade" class="btn btn-action" onClick="func();">Final Grade</button>
<button id="btnaddRow" class="btn btn-action" onclick="addRow();">AddRow</button>
<button id="btnaddColumn" class="btn btn-action" onclick="addColumn();">AddColumn</button>
You were adding a div to td element which was throwing error while executing this line document.getElementById("mytable").rows[j].cells[i].innerHTML
which returns a div element not the text you entered!
No need to add a div, Here is the updated code,
func = function () {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function () {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-","tg-031e");
}
}
createCell = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute('placeholder', '' - '');
//cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute("placeholder", "-");
//cell.appendChild(div); // append DIV to the table cell
}
addColumn = function () {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-031e");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-s6z2");
}
}
}

Javascript random cell background color change

I am trying to create a table. ruudud.value is a value from <select>. But while this function is creating a table, I want it to place some random yellow cells in it.
This is a small school project and this code is part of a code which should createbattleship game.
Also if possible. when it does create a random yellow cell, then could it also paint the next cell yellow? (to create a 2 cell ship).
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var x = Math.floor((Math.random() * ruudud.value) + 0);
var y = Math.floor((Math.random() * ruudud.value) + 0);
for (var i = 0; i < ruudud.value; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
console.log(x + "," + y);
for (var j = 0; j < ruudud.value; j++) {
var td = document.createElement('TD');
var td = document.getElementsByTagName("td");
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
td.setAttribute("onClick", "colorChange(this)")
td.innerHTML = (i + "," + j);
if (td[i].innerHTML == (x + "," + y)) {
td[i].setAttribute("style", "background:yellow;");
}
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function colorChange(tdObj) {
tdObj.style.backgroundColor = "green";}
example2:
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var x = Math.floor((Math.random() * ruudud.value) + 0);
var y = Math.floor((Math.random() * ruudud.value) + 0);
for (var i=0; i<ruudud.value; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
console.log(x + ","+y);
for (var j=0; j<ruudud.value; j++){
var td = document.createElement('TD');
var td2 = document.getElementsByTagName("td");
var i = 0, tds = td.length;
td.width='50';
td.height='50';
td.style.backgroundColor="white";
td.setAttribute("onClick", "colorChange(this)")
td.innerHTML = (i +","+ j);
if(td2[i].innerHTML == (x + "," + y)) {
td2[i].setAttribute("style", "background:yellow;");
}
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function colorChange(tdObj) {
tdObj.style.backgroundColor = "green";}
In both the cases, you are selecting the td element before it is appended to the DOM. You don't need to select it again, you can simply apply style to the td element when you create it. Here's a slight modification to your code. I have also added a condition to add two-cell ships like you asked.
function addTable(double) {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var x = Math.floor((Math.random() * ruudud.value) + 0);
var y = Math.floor((Math.random() * ruudud.value) + 0);
for (var i = 0; i < ruudud.value; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
//console.log(x + "," + y);
for (var j = 0; j < ruudud.value; j++) {
var td = document.createElement('td');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
td.setAttribute("onClick", "colorChange(this)");
td.innerHTML = (i + "," + j);
if (x === i && y === j) {
td.setAttribute("style", "background:yellow;");
}
// If you need to enable two-cell ships, pass true to the function
// You can allow horizontal or vertical cells by changing x and ys in the equality checks below
if(double){
if(y+1 < ruudud.value){
if(x === i && y+1 === j){
td.setAttribute("style", "background:yellow;");
}
}
else{
if(x === i && y-1 === j){
td.setAttribute("style", "background:yellow;");
}
}
}
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function colorChange(tdObj) {
tdObj.style.backgroundColor = "green";}
addTable(true);

Categories

Resources