Can't get JSON string's element - javascript

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

Related

Send a grid as json

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

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>

Javascript variabel scope confusion

I have a small problem with regards to scope. In the program below I have declared two variables in the .js file, countRows and countCols. Inside the saveTable(). However their value is 0 when after the function when I log them.
Why do they not hold their value from the function?
var table = document.getElementById("table");
var countRows = 0;
var countCols = 0;
function saveTable() {
countRows = table.rows.length;
countCols = table.rows[0].cells.length;
var data = "";
for(var i = 0; i < table.rows.length; i++) {
for(var j = 0; j < table.rows[i].cells.length; j++) {
data += table.rows[i].cells[j].innerHTML + ",";
}
}
document.cookie = data;
}
console.log(countRows); //These equal 0
console.log(countCols);
To add to #Steven Stark answer, it happens because you didn't call the function before logging the variable, they share the scope here. Example below:
let a = 0;
// This change a, because the function is directly accessing the a declared in the parent scope
function changeA() {
a = 3;
}
changeA();
console.log(a)
// This doesn't change a
function changeAParameter(a) {
// because this 'a' only exists in the scope of this function
a = 5;
}
changeAParameter(a);
console.log(a);
You can have more information about closure (which is beyond topic here), but is interesting: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
You have to invoke the function
var table = document.getElementById("table");
var countRows = 0;
var countCols = 0;
function saveTable() {
countRows = table.rows.length;
countCols = table.rows[0].cells.length;
var data = "";
for(var i = 0; i < table.rows.length; i++) {
for(var j = 0; j < table.rows[i].cells.length; j++) {
data += table.rows[i].cells[j].innerHTML + ",";
}
}
document.cookie = data;
}
// Call the function
saveTable();
console.log(countRows); //These equal 0
console.log(countCols);

.remove is not function How to fix?

var dbRefObjectHis = firebase.database().ref('Box1').child('history');
dbRefObjectHis.on('value',gotData, errData);
function gotData(data) {
var ref = d3.selectAll('.His');
for (var i = 0; i < ref.length; i++){
ref[i].remove();
}
var history = data.val();
var keys = Object.keys(history);
for (i = 0; i < keys.length; i++) {
var k = keys[i];
var humidity = history[k].humidity;
var temperature = history[k].temperature;
$('.His').append('Humidity:' + humidity + 'Temperature:' + temperature );
}
This happens when the element you are trying to remove is not a removable Node.
try replacing
for (var i = 0; i < ref.length; i++){
ref[i].remove();
}
with
ref.forEach(function(e) {
e.remove();
});

Having trouble trying to style duplicates

I'm checking for duplicates in a table. What I'm trying to accomplish is when I display the first column if it is the same value as the previous row I don't want to display the value. I'm finding the duplicates but I get an error when I try to hide them by using display. style ="none"; My code is below.
I'm Thanking You In Advance
PD
var data=[['e',0,1,2,3,4], ['a',54312,235,5,15,4], ['a',6,7,8,9,232],
['a',54,11235,345,5,6], ['b',0,1,2,3,4], ['b',54312,235,5,15,4],
['c',62,15,754,93,323], ['d',27,11235,425,18,78], ['d',0,1,2,3,4],
['d',54312,235,5,15,4], ['e',6,7,8,9,232], ['e',54,11235,345,5,6],
['e',0,1,2,3,4], ['e',54312,235,5,15,4], ['e',62,15,754,93,323],
['e',27,11235,425,18,78]];
//Create a HTML Table element.
var table = document.createElement("TABLE");
var somedata = document.createElement("TD");
var dvTable = document.getElementById("dvTable");
var elems = document.getElementsByClassName("tableRow");
//Get the count of columns.
var columnCount = data[0].length;
//Add the data rows.
for (var i = 0; i < data.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
//Searching for duplicates
var num = data[i][0];
for (var otherRow = i + 1; otherRow < data.length; otherRow++) {
var dup = data[otherRow][0];
console.log("What is the dup" + dup);
if (num === dup)
{
console.log("duplicate");
dvTable[i].style.display = "none";
}
}
var cell = row.insertCell(-1);
cell.innerHTML = data[i][j];
cell.innerHtml = myZero;
}
}
dvTable is an HTML table element. You can't access the row using dvTable[i].
Try -
dvTable.rows(i).cells(j).style.display = none;

Categories

Resources