Javascript random cell background color change - javascript

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);

Related

How do I set an on click event for every cell that calls a function which takes id of cell as a parameter in JavaScript

Here I created a table and assigned each cell an id. What I want to do is something like this cell1.onclik = MyFunction(this.id);
function createTable() {
var table = document.getElementById("tabela2");
for (let j = 0; j < k; j++) {
var row = table.insertRow(0);
for (let i = 0; i < l; i++) {
var cell1 = row.insertCell(0);
cell1.id = "celica" + i + "_" + j;
/*doesnt work: cell1.onclik = MyFunction(this.id); */
}
}
}
Don't use onXXX events. It won't work it there is a content-security-policy on the page.
You just need to listen to the table
function createTable() {
var table = document.getElementById("tabela2");
// document.body.appendChild(table);
for (let j = 0; j < 4; j++) {
var row = table.insertRow(0);
for (let i = 0; i < 4; i++) {
var cell1 = row.insertCell(0);
cell1.textContent = "1";
cell1.id = "celica" + i + "_" + j;
}
}
table.addEventListener("click", function(e) {
console.log(e.target.id);
console.log(e.target.tagName);
});
}
createTable();
<html><body><table id='tabela2'></table></body></html>

Set type text inside cell javascript

I want to type text inside the cell but I tried to set attribute with td but it doesn't work. Please help me how can I set attribute to type text in the cell. Thank you for your help!
function addTable() {
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
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 < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
You need to create an input element and then append that to td:
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns", 1);
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 < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('value', 'text');
td.appendChild(input);
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
<div id="myDynamicTable">
</div>
You can use contenteditable attribute: td.contenteditable = 'true';.
Depending on how you want to use this value, you might also insert an input element.
You are perhaps looking for contentEditable?
function addTable() {
const rn = +window.prompt("Input number of rows", 1);
const cn = +window.prompt("Input number of columns", 1);
const myTableDiv = document.getElementById("myDynamicTable");
const table = document.createElement('table');
table.border = '1';
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (let i = 0; i < rn; i++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (let j = 0; j < cn; j++) {
var td = document.createElement('td');
td.width = '75';
td.contentEditable = true;
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
<div id="myDynamicTable"></div>
if you want to operate on tables, use corrects javascript instructions ...
const
DynTb = document.getElementById('myDynamicTable')
rn = +window.prompt("Input number of rows", 1)
, cn = +window.prompt("Input number of columns", 1)
;
if( isNaN(rn) || isNaN(cn))
throw 'bad integer input value (s)'
const myTable = addTable(DynTb, rn, cn )
function addTable(tDiv, rn, cn)
{
let
tab = tDiv.appendChild( document.createElement('table') )
, tBy = tab.createTBody()
;
for(let r=0;r<rn;++r)
{
let row = tBy.insertRow()
for(let c=0;c<cn;++c)
{
row.insertCell().innerHTML =
`<input type="text" placeHolder="${r}-${c}">`
} }
return tab
}
table {
border-collapse : collapse;
margin : 2em 1em;
}
td {
padding : .2em;
border : 1px solid darkblue;
}
input {
width : 5em;
}
<div id="myDynamicTable"></div>

Unable to generate table after clearing table

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>

Display the existing json data to matrix like table

I would like to display the json data to the table. Tried key value pattern. But no luck. Could anyone suggest me? Thanks.
my full JSON data contains around 20 objects. This is a dynamic created table according to other table's value -- example has 3. So when it's three rows, only three rows should be filled from the JSON data if exists. For example if 5 rows, 3 rows should be filled from the json and two rows should display '-'.
function setTrait_matrix() {
var json_data = {
Title1_Title1: "11yty",
Title1_Title2: "12sdf",
Title1_Title3: "1376",
Title2_Title1: "21yu",
Title2_Title2: "22",
Title2_Title3: "235",
Title3_Title1: "31",
Title3_Title2: "32",
Title3_Title3: "33"
};
var matrixVal = 3;
if (matrixVal != 0 || matrixVal != null) {
var root = document.getElementById("traits_matrix_Div");
var table = document.createElement('table');
table.className = "difftable";
var tblB = document.createElement('tbody');
table.appendChild(tblB);
var firstList = {};
for (var x = 1; x <= matrixVal; x++) {
firstList['Title' + x] = 'Title' + x;
}
myData = Object.values(firstList);
var tr = document.createElement('tr');
tr.appendChild(document.createElement('th'));
for (var j = 0; j < matrixVal; j++) {
var th = document.createElement('th');
var text = document.createTextNode(myData[j]);
th.appendChild(text);
tr.appendChild(th);
}
tblB.appendChild(tr);
for (var i = 0; i < matrixVal; i++) {
var tr = document.createElement('tr');
tblB.appendChild(tr);
var td = document.createElement('td');
var text = document.createTextNode(myData[i]);
td.appendChild(text);
tr.appendChild(td);
var thisMatrix = JSON.stringify(json_data);
var curcolumn = i + 1;
for (var j = 0; j < matrixVal; j++) {
var input = document.createElement("input");
input.type = "text";
if (typeof thisMatrix !== 'undefined') {
var curValue = "jsonVal";
} else {
var curValue = "-"
}
var col = j + 1;
if (i >= 0 && j >= 0) {
input.name = "Title" + curcolumn + "_Title" + col;
input.value = curValue;
input.id = "Title" + curcolumn + "_Title" + col;
}
const td = document.createElement('td');
td.appendChild(input);
tr.appendChild(td);
}
}
root.appendChild(table);
}
}
<body onload="setTrait_matrix()">
<div id="traits_matrix_Div" style="visibility:visible" style="border: 1px; height:200px; align: center;"></div>
</body>
Hope I am not confusing. Please suggest me!
function setTrait_matrix() {
var json_data = {
Title1_Title1: "11yty",
Title1_Title2: "12sdf",
Title1_Title3: "1376",
Title2_Title1: "21yu",
Title2_Title2: "22",
Title2_Title3: "235",
Title3_Title1: "31",
Title3_Title2: "32",
Title3_Title3: "33"
};
var matrixVal = 3;
if (matrixVal != 0 || matrixVal != null) {
var root = document.getElementById("traits_matrix_Div");
var table = document.createElement('table');
table.className = "difftable";
var tblB = document.createElement('tbody');
table.appendChild(tblB);
var firstList = {};
for (var x = 1; x <= matrixVal; x++) {
firstList['Title' + x] = 'Title' + x;
}
myData = Object.values(firstList);
var tr = document.createElement('tr');
tr.appendChild(document.createElement('th'));
for (var j = 0; j < matrixVal; j++) {
var th = document.createElement('th');
var text = document.createTextNode(myData[j]);
th.appendChild(text);
tr.appendChild(th);
}
tblB.appendChild(tr);
for (var i = 0; i < matrixVal; i++) {
var tr = document.createElement('tr');
tblB.appendChild(tr);
var td = document.createElement('td');
var text = document.createTextNode(myData[i]);
td.appendChild(text);
tr.appendChild(td);
var thisMatrix = JSON.stringify(json_data);
var curcolumn = i + 1;
for (var j = 0; j < matrixVal; j++) {
var input = document.createElement("input");
input.type = "text";
if (typeof json_data["Title"+(i+1)+"_Title"+(j+1)] !== 'undefined') {
var curValue = json_data["Title"+(i+1)+"_Title"+(j+1)];
} else {
var curValue = "-"
}
var col = j + 1;
if (i >= 0 && j >= 0) {
input.name = "Title" + curcolumn + "_Title" + col;
input.value = curValue;
input.id = "Title" + curcolumn + "_Title" + col;
}
const td = document.createElement('td');
td.appendChild(input);
tr.appendChild(td);
}
}
root.appendChild(table);
}
}
<body onload="setTrait_matrix()">
<div id="traits_matrix_Div" style="visibility:visible" style="border: 1px; height:200px; align: center;"></div>
</body>
I hope this will help you.
I just did a quick fix in your code. You weren't actually calling the JSON object data anywhere, so... I just called it like this:
let box_value = json_data["Title" + curcolumn + "_Title" + col];
input.value = box_value?box_value:"-";
function setTrait_matrix() {
var json_data = {
Title1_Title1: "11yty",
Title1_Title2: "12sdf",
Title1_Title3: "1376",
Title2_Title1: "21yu",
Title2_Title2: "22",
Title2_Title3: "235",
Title3_Title1: "31",
Title3_Title2: "32",
Title3_Title3: "33",
Title1_Title4: "1414141"
};
var matrixVal = 5;
if (matrixVal != 0 || matrixVal != null) {
var root = document.getElementById("traits_matrix_Div");
var table = document.createElement('table');
table.className = "difftable";
var tblB = document.createElement('tbody');
table.appendChild(tblB);
var firstList = {};
for (var x = 1; x <= matrixVal; x++) {
firstList['Title' + x] = 'Title' + x;
}
myData = Object.values(firstList);
var tr = document.createElement('tr');
tr.appendChild(document.createElement('th'));
for (var j = 0; j < matrixVal; j++) {
var th = document.createElement('th');
var text = document.createTextNode(myData[j]);
th.appendChild(text);
tr.appendChild(th);
}
tblB.appendChild(tr);
for (var i = 0; i < matrixVal; i++) {
var tr = document.createElement('tr');
tblB.appendChild(tr);
var td = document.createElement('td');
var text = document.createTextNode(myData[i]);
td.appendChild(text);
tr.appendChild(td);
var thisMatrix = JSON.stringify(json_data);
var curcolumn = i + 1;
for (var j = 0; j < matrixVal; j++) {
var input = document.createElement("input");
input.type = "text";
if (typeof thisMatrix !== 'undefined') {
var curValue = "jsonVal";
} else {
var curValue = "-"
}
var col = j + 1;
if (i >= 0 && j >= 0) {
input.name = "Title" + curcolumn + "_Title" + col;
let box_value = json_data["Title" + curcolumn + "_Title" + col];
input.value = box_value?box_value:"-";
input.id = "Title" + curcolumn + "_Title" + col;
}
const td = document.createElement('td');
td.appendChild(input);
tr.appendChild(td);
}
}
root.appendChild(table);
}
}
<body onload="setTrait_matrix()">
<div id="traits_matrix_Div" style="visibility:visible" style="border: 1px; height:200px; align: center;"></div>
</body>

MineField with Js

I am trying to create a minefield game with javascript.
When I click on clear ro**w it gives "passed" but sometimes "died" too or clicking on **mined row gives sometimes "passed". It's supposed to give only "passed" with clear and "died" with mined row.
I can't figure out the reason..
Could you see it?
Here is my code so far:
var level = 9;
// 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() * 50);
if (j <= 15) {
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", "1");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("td");
for (p = 0; p < rows.length; p++) {
var currentRow = table.rows[p];
var createClickHandler = function (row) {
return function () {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
if (id == "mined") {
alert("Died");
} else {
alert("Passed!");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
JSFiddle Here:
http://jsfiddle.net/blowsie/ykuyE/
Thanks in advance!
Its' this line, which causes the faulty behaviour: var cell = row.getElementsByTagName("td")[1]; Everytime a click is made, the [1] selects the 2nd cell of a column, no matter which cell was actually clicked.
I modified your fiddle: http://jsfiddle.net/ykuyE/1
The onclick handler is now applied to the individual cell directly, when the table is created.
cell.onclick = function() {
if (this.innerHTML == "mined") {
alert("Died");
} else {
alert("Passed!");
}
}

Categories

Resources