Send a grid as json - javascript

I'm relatively new to the world of JavaScript. I create a grid in which I can select any cells.
Now I would like to send all cells as binary with a Json document to the backend. For this purpose, an unselected cell should have a 0 and a selected one should have a 1. I orientate myself on Conway's Game of Life. I've been at it for 2 days now and don't know how best to implement it. Does anyone have an idea?
Here is my code to create the grid
var rows = 10;
var cols = 10;
var grid = new Array(rows);
var nextGrid = new Array(rows);
var startButton = document.getElementById('start');
startButton.addEventListener('click', event => {
initialize()
})
function initializeGrids() {
for (var i = 0; i < rows; i++) {
grid[i] = new Array(cols);
nextGrid[i] = new Array(cols);
}
}
function copyAndResetGrid() {
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
grid[i][j] = nextGrid[i][j];
}
}
}
// Initialize
function initialize() {
createTable();
initializeGrids();
}
// Lay out the board
function createTable() {
var gridContainer = document.getElementById('gridContainer');
if (!gridContainer) {
// Throw error
console.error("Problem: No div for the drid table!");
}
var table = document.createElement("table");
for (var i = 0; i < rows; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < cols; j++) {
var cell = document.createElement("td");
cell.setAttribute("id", i + "_" + j);
cell.setAttribute("class", "dead");
cell.onclick = cellClickHandler;
tr.appendChild(cell);
}
table.appendChild(tr);
}
gridContainer.appendChild(table);
}
function cellClickHandler() {
var rowcol = this.id.split("_");
var row = rowcol[0];
var col = rowcol[1];
var classes = this.getAttribute("class");
if(classes.indexOf("live") > -1) {
this.setAttribute("class", "dead");
grid[row][col] = 0;
} else {
this.setAttribute("class", "live");
grid[row][col] = 1;
}
}

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>

Can't get JSON string's element

I'm totally new to javascript and I'm trying to display an array of object which is stored in local storage using javascript and html and display each element of the JSON string in td tag of a table
In studentList.js file, first of all, I create a Student object:
function Student(id, name, birthDay, gender, falcuty, point ) {
this.id = id
this.name = name
this.birthDay = birthDay
this.gender = gender
this.falcuty = falcuty
this.point = point
}
var table = document.getElementById("table-stud")
And an array of 'Student' object:
var collection = [];
collection.push(new Student("01","A","20/11/1998","M","IT","8.0"),
new Student("02","B","2/1/1998","F","IT","8.0"),
new Student("03","C","9/9/1997","F","CK","8.8"))
Save student in local storage:
function saveStudent(collection) {
for(var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = JSON.stringify(collection[i])
console.log(studentObjectSerialiseData)
window.localStorage.setItem("student"+i, studentObjectSerialiseData)
}
}
Display students:
function getStudents() {
console.log(Student.length)
for(var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student"+i)
var temp = JSON.parse(studentObjectSerialiseData)
var tr = document.createElement("tr")
for(var j = 0; j < Student.length; j++) {
var td = document.createElement("td")
td.innerText = temp[j]
tr.appendChild(td)
}
table.appendChild(tr)
}
}
saveStudent(collection);
getStudents();
In HTML file, I called studentList.js file and added id to the 'table' tag, the localStorage worked perfectly but when I want to display, this happened:
id Name birthDay Gender Falcuty Point
undefined undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined undefined
Please help me solve this problem!
The problem is mostly on the parts you're trying to loop over the keys of Student. Utilize Object.keys for achieving it instead:
function getStudents() {
for (var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student" + i)
var temp = JSON.parse(studentObjectSerialiseData)
var tr = document.createElement("tr")
for (var j = 0; j < Object.keys(temp).length; j++) {
var td = document.createElement("td")
console.log(temp)
td.innerText = temp[Object.keys(temp)[j]]
tr.appendChild(td)
}
table.appendChild(tr)
}
}
For a working example, see this snippet: https://jsbin.com/koqikiquzu/1/edit?html,js,output (Tried to embed through SO's own playground, but using localStorage is a bit tricky here).
temp in getStudents() is an object so you need to loop over that too.
function getStudents() {
for (var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student" + i)
var temp = JSON.parse(studentObjectSerialiseData)
var tr = document.createElement("tr")
for (var j = 0; j < Student.length; j++) {
for(var i in temp) {
var td = document.createElement("td")
td.innerText = temp[i]
tr.appendChild(td)
}
}
table.appendChild(tr)
}
}
You can get the result by using for in loop inside j for loop and appends to tr tag if j and i are equal.
function getStudents() {
for (var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student" + i);
var temp = JSON.parse(studentObjectSerialiseData);
var tr = document.createElement("tr");
for (var j = 0; j < Student.length; j++) {
for (x in temp) {
if (j == i) {
var td = document.createElement("td");
td.innerText = (temp)[x];
tr.appendChild(td);
}
}
}
table.appendChild(tr)
}
}
Access Student in a for in loop to get the keys.
for(var i = 0; i < collection.length; i++) {
var studentObjectSerialiseData = window.localStorage.getItem("student"+i)
var temp = JSON.parse(studentObjectSerialiseData)
console.log(temp);
for(var j in Student) {
console.log(temp[j]) ;
}
}

Changing status of <td> on click with javascript

I am making a conways game of life in javascript and having trouble getting my onclick implementation to work. It is supposed to change the life status of the cell when the td is clicked, but instead I am getting an error at my console that says : TypeError: World.tds is undefined.
TLDR: Can't figure out why onclick won't work. World.tds[] is undefined for some reason.
Onclick implementation:
if (table !== null) {
for (var i = 0; i < 20; i++) {
for (var j = 0; j < 20; j++)
World.tds[i][j].onclick = function() {
if (World.tds[i][j].cells.alive) {
World.tds[i][j].cells.alive = false;
} else {
World.tds[i][j].cells.alive = true;
}
};
}
}
Constructor and tds[] filling
var World = function() {
this.h = maxH;
this.w = maxW;
this.tds = [];
};
//generate the world in which the cells move
World.prototype.init = function() {
var row, cell;
for (var r = 0; r < this.h; r++) {
this.tds[r] = [];
row = document.createElement('tr');
for (var c = 0; c < this.w; c++) {
cell = document.createElement('td');
this.tds[r][c] = cell;
row.appendChild(cell);
}
table.appendChild(row);
}
};
Problem Statement - When you trigger the click handler, by that time values of i and j have updated to 20 each and World.tds[20][20] is undefined.
Update your code inside for loop to
(function(i,j) {
World.tds[i][j].onclick = function() {
if (World.tds[i][j].cells.alive) {
World.tds[i][j].cells.alive = false;
} else {
World.tds[i][j].cells.alive = true;
}
};
})(i,j);

Show the first row of the table in alert message using javascript

I want to show the first row of the table in alert message at a time
function GetCellValues() {
var rows = document.getElementsByTagName('tr');
for (var c = 0; c < rows.length; c++) {
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0; k < inputs.length; k++) {
alert(inputs[k].value);
//here I want some code to show the first table row at a time.
}
}
}
window.onload = function () {
makeTable();
};
Try This,
function GetCellValues() {
var rows = document.getElementsByTagName('tr');
for (var c = 0; c < rows.length; c++) {
var row = rows[c];
var inputs = row.getElementsByTagName('input');
var inputValList=[];
for (var k = 0; k < inputs.length; k++) {
// alert(inputs[k].value);
inputValList.push(inputs[k].value);
}
if(inputValList.length>0){
alert(inputValList);
}
}
}
I just hope...this will solve your problem.

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