Table created with JS is addin content in tr line - javascript

When creating a table with js following the following tutorial:
https://www.aspsnippets.com/Articles/Create-dynamic-Table-in-HTML-at-runtime-using-JavaScript.aspx
I'm getting the unexpected result, the table is creating the elements on the same line as the header, and I can not understand why this is happening if anyone could help me I'd be grateful.
Att,
Carlos Eduardo
//browserify index.js > bundle.js
const request = require('request')
var respRequest
var buttonTable = document.getElementById("button-table").addEventListener("click", function() {
request('https://jsonplaceholder.typicode.com/photos', function(error, response, body) {
console.log('error:', error)
console.log('statusCode:', response && response.statusCode)
//console.log('body:', body)
var content = []
content = JSON.parse(body)
var a = content.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key]
})
})
a.unshift(["AlbumId", "id", "url", "title", "thumbnailUrl"])
var table = document.createElement("table")
table.border = "1"
var columnCount = a[0].length
var row = table.insertRow(-1)
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("th")
headerCell.innerHTML = a[0][i]
row.appendChild(headerCell)
}
for (var i = 1; i < a.length; i++) {
line = table.insertRow(-1)
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1)
cell.innerHTML = a[i][j]
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/style.css">
<title>Meu Site</title>
</head>
<body>
<div class="container">
<p>Gerar Relatorio</p>
<button type="button" id="button-table" class="btn btn-default ">Gerar
Relatorio</button>
<div id="dvTable"></div>
</div>
<script src="script/bundle.js"></script>
</body>
</html>
I expect that it will create a table perfectly, with header, and lines, in a way that you can read perfectly what is in the table

var row = table.insertRow(-1)
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("th")
headerCell.innerHTML = a[0][i]
row.appendChild(headerCell)
}
for (var i = 1; i < a.length; i++) {
line = table.insertRow(-1)
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1)
cell.innerHTML = a[i][j]
}
}
In the first loop you create the header-row, stored in variable row.
in the second loop you try to create several more rows in variable line,
but you still append your cells to row.

Related

InnerHTML changes old variables

I'm doing a function that creates a table in JS.
I create a variable table_row fill it and then add table_layout.appendChild(table_row); it to the table_layout element.
Next, I clean it table_row through innerHTML='', but when cleaning, the variable that I ALREADY added to the element table_layout is also cleared.
Why is this happening?
Should the added element be cleared?
How can this be avoided?
Look at the CODE.
var columns = ["col1", "col2", "col3"];
var rows = 5;
function Table() {
var table_layout = document.createElement("table");
var table_row = document.createElement("tr");
for (var i = 0; i < columns.length; i++) {
// main row
table_row.innerHTML += "<th>" + columns[i] + "</th>";
}
table_layout.appendChild(table_row); //add in table element
// table_row.innerHTML = ""; //If you uncomment this line, then we get an empty output!
//refresh table_row html, that would generate a new line
//But when cleaning. Cleared in the previously added item in table_layout .... how??
// for (var j = 0; i < columns.length; j++) {
// table_main_row.innerHTML += '<td></td>';
// }
// for (var i = 0; i < rows; i++) {
// table_layout.appendChild(table_row);
// }
return table_layout;
}
var div = document.getElementById("qqq");
div.appendChild(Table());
#qqq {
background: red;
}
<div id="qqq"></div>
The table_row variable contains a reference. You will need to create a new element for each row.
// creates a DOM Element and saves a reference to it in the table_row variable
var table_row = document.createElement("tr");
// updates the DOM Element through the reference in the table_row variable
table_row.innerHTML += "<th>" + columns[i] + "</th>";
// still references the DOM Element, so you are clearing its content
// table_row.innerHTML = "";
You will need to . . .
// create a new DOM Element to use
table_row = document.createElement("tr");
// then update its contents
table_main_row.innerHTML += '<td></td>';
. . . for each iteration.
See JavaScript on MDN for tutorials, references, and more.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript">
var columns = ["col1", "col2", "col3"];
var rows = 5;
function createNewRow(headerRow)
{
var newRowElem = null;
try
{
newRowElem = document.createElement("tr");
for (var i = 0; i < columns.length; i++)
{
if(headerRow) newRowElem.innerHTML += "<th>" + columns[i] + "</th>";
else newRowElem.innerHTML += "<td>" + columns[i] + "</td>";
}
}
catch(e)
{
alert("createNewRow Error" + e.Message);
}
finally
{
}
return newRowElem;
}
function Table()
{
var table_layout = null;
try
{
table_layout = document.createElement("table");
// Create Header Row
table_layout.appendChild(createNewRow(true));
// Create Other Rows
for (var i = 0; i < rows; i++)
{
table_layout.appendChild(createNewRow(false));
}
}
catch(e)
{
alert("Table Error: " + e.Message);
}
finally
{
}
return table_layout;
}
</script>
<style>
#qqq {
background: red;
}
</style>
</head>
<body>
<div id="qqq"></div>
<script type="text/javascript" language="javascript">
var div = document.getElementById("qqq");
div.appendChild(Table());
</script>
</body>
</html>
I did so.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = document.createElement('tr');
row.setAttribute('class', 'main_row');
for (var i = 0; i < this.fields.length; i++) { // строка с именами столбцов
var th = document.createElement('th');
th.setAttribute('class', 'cell_name');
th.innerHTML = this.fields[i];
row.appendChild(th);
}
table_layout.appendChild(row); //добавляем
row = document.createElement('tr'); // очищаем от старых элементов строку (переопределяем)
row.setAttribute('class', 'table_row');
var td = document.createElement('td');
td.setAttribute('class', 'table_cell');
// td.setAttribute('ondblclick', 'input_func()');
td.addEventListener('click', function () {
alert();
});
td.innerHTML='000';
for (var j = 0; j < this.fields.length; j++) { // создаем строку с N-количеством ячеек
row.appendChild(td.cloneNode(true));
}
for (var i = 0; i < this.rows; i++) { // Добавляем её есколько раз через клона
table_layout.appendChild(row.cloneNode(true));
}
But then redistribution with functions for the table.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = table_layout.insertRow(0);
var cell;
for (var j = 0; j < this.fields.length; j++) {
cell = row.insertCell(j);
cell.outerHTML = '<th>' + this.fields[j] + '</th>';
cell.className = 'cell_name';
}
for (var i = 0; i < this.rows; i++) {
row = table_layout.insertRow(i + 1);
row.className = 'row_table';
for (var n = 0; n < this.fields.length; n++) {
cell = row.insertCell(n);
// cell.innerHTML = '00';
cell.className = 'table_cell';
cell.innerHTML = '&nbsp';
}
}
return table_layout;

Javascript code that should make a table and run on page load [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Javascript should run when the page loads, create a table with 10 rows and 10 columns and adds it to div "funky", the cells of the table should contain the text "N M" where N is the minumum of the row and column index and M is the maximum of the row and column index,cells in even numbered columns should have the text colour purple. here are my javascript and html codes
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky");
var table = document.createElement("table");
table.border = 1;
for (var i = 0; i <= ROWS; i += 1) {
var row = document.createElement("row");
if (i == 2) {
row.Fontweight = "bold";
}
for (var j = 0; j < COLS; j += 2) {
var col = document.createElement("cell");
col.innerHTML = i + " " + j;
if (j / 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
document.getElementsByClassName("table");
}
}
onload = go();
<html>
<head>
<title>Question 2</title>
<script src="question2.js" type="text/javascript"></script>
<head>
<body>
<div class="funky"></div>
</body>
<html>
Replace HTML Code To :
<html>
<head>
<title>Question 2</title>
<script src="question2.js" type="text/javascript"></script>
</head>
<body onload="javascript:go();">
<div class="funky"></div>
</body>
</html>
Replace JS Code To :
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky")[0];
var table = document.createElement("table");
table.style.border = "1px solid #000";
table.style.borderCollapse = "collapse";
for (var i = 0; i <= ROWS; i += 1) {
var row = document.createElement("tr");
if (i == 2) {
row.style.fontWeight = "bold";
}
for (var j = 0; j < COLS; j += 1) {
var col = document.createElement("td");
col.innerHTML = i + " " + j;
if (j % 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
}
out.appendChild(table);
}
You need to use MOD Operator to understand is it even or not. You need to use style property before using border property.
You have several mistakes in your code.
When you use getElementsByClassName you need to access them by
index like this
var out = document.getElementsByClassName("funky")[0];
You need to append table after creating it to div then it will be
show on page.
You need to create tr instead of row and td instead of cell.
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky")[0];
var table = document.createElement("table");
table.border = 1;
for (var i = 0; i <= ROWS; i ++) {
var row = document.createElement("tr");
if (i == 2) {
row.style.fontWeight = "bold";
}
for (var j = 0; j < COLS; j += 2) {
var col = document.createElement("td");
col.innerHTML = i + " " + j;
if (j / 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
document.getElementsByClassName("table");
}
out.appendChild(table);
}

Dynamically remove elements with javascript

I got a javascript with a function that creates a table. Now I want the table to be updated/replaced each time I press the button again. I have tried some solutions I have found on the web but none seem to do what I want.
javascript
//Updates table
function myFunction(jsonObject) {
//Build array from the jsonObject
var customers = new Array();
var jsonArr = jsonObject['log'];
for(var i in jsonArr){
customers.push((jsonArr[i]['date']) );
customers.push((jsonArr[i]['time']) );
customers.push((jsonArr[i]['temp']) );
customers.push((jsonArr[i]['humidity']) );
}
//Remove existing tables.-----------------------THIS HAS NO EFFECT!
var myNode = document.getElementById('logDiv');
while (myNode.hasChildNodes()) {
alert("logDiv has nodes, removing them now!")
myNode.removeChild(myNode.firstChild);
}
//----------------------------------------------THIS HAS NO EFFECT!
var container = document.getElementById('logDiv');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.className = "sortable";
//Adds table headers
var headers = ["Date", "Time", "Temp", "Hum"]
var row1 = document.createElement('tr');
for (var b = 0; b < 4; b++) {
var cell = document.createElement('th');
cell.textContent = headers[b];
row1.appendChild(cell);
counter++;
}
tbody.appendChild(row1);
var counter = 0;
// loop and create rows
for (i = 0; i < customers.length/4; i++) {
var values = customers[i];
var row = document.createElement('tr');
// loop and create columns
for (var b = 0; b < 4; b++) {
var cell = document.createElement('td');
cell.textContent = customers[counter];
row.appendChild(cell);
counter++;
}
tbody.appendChild(row);
}
table.appendChild(tbody);
container.appendChild(table);
}
html/php
<?php
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
$json = json_encode($finalOutput);
?>
<html>
<head>
<script src="script.js" type="text/javascript"></script>
<script src="sorttable.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="UTF-8">
<title>Antgus</title>
</head>
<body>
<button id="btnGenerate" type="button" onclick='myFunction(<?php echo $json ?>)'>Generate log</button>
<br><br>
<div id="logDiv"></div>
</body>
</html>

Javascript table with for

I'm new to Javascript and I have been trying a Javascript table with a for loop all the day. I want to get the value of a cell. I'm doing like an "Excel app". Please check what is wrong. I just fixed things in answers ....
var MatriXcel = ( function( window, undefined ) {
var matriz = [];
var matrizJson;
var row = 5;
var col = 6;
function getData(){
return matriz;
}
function addRow(){
var newCol = [];
for (var i=0; i < col; i++){
newCol.push("");
}
matriz.push(newCol);
this.draw();
}
function drawTable(){
var table = "<tr><th></th><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th></tr>";
for (var i=0; i < matriz.length; i++){
table += "<tr>";
for (var x=0; x < matriz[i].length; x++){
if (x == 0){
table += "<th>"+(i+1)+"</th>";
}else{
table += "<td><input type='text' onkeyup='MatriXcel.save("+i+","+x+",this)' value='"+matriz[i][x]+"'></td>";
}
}
table += "</tr>";
}
document.getElementById("tabla").innerHTML = table;
}
function saveInfo(irow, xcol, content){
matriz[irow][xcol] = content.value;
}
function getMatch(){
var tabla = document.getElementById("tabla");
search= document.getElementById("word").value;
var re = new RegExp(search,"gi");
var row;
var col;
for (var i = 0; i< tabla.rows.length; i++){
row = tabla.rows[i];
for (var j; j<row.cells.length; j++){
col = row.cells[j];
if(re.test(row.textContent)){
row.style.color="rgb(239, 19, 109)";
alert(row.textContent);
}else if(re.test(col.textContent)){
col.style.color="rgb(79, 2, 133)";
}
}
}
}
function saveLocal(){
matrizJson = JSON.stringify(matriz);
console.log(matrizJson);
window.localStorage.table = matrizJson;
// matrizJson = JSON.parse(matrizJson);
// console.log(matrizJson);
}
function init(){
if(typeof window.localStorage.table === 'string'){
matriz = JSON.parse(window.localStorage.table);
this.draw();
}
}
return {
addRow : addRow,
draw : drawTable,
save : saveInfo,
get : getData,
local : saveLocal,
init : init,
search : getMatch,
};
} )( window );
if (window.localStorage.length == 0){
MatriXcel.addRow();
MatriXcel.addRow();
MatriXcel.addRow();
MatriXcel.addRow();
MatriXcel.addRow();
}else{
MatriXcel.init();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ExcelApp</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<input type="search" value="" placeholder="write here" id="word">
<input type="button" value="Search" id="trigger" onclick="MatriXcel.search()">
<table id="tabla">
</table>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
It seems there is an issue with your way of checking regular expression.
For example, in place of this
if(re == row.value){
it should be
if(re.test(row.value)){
Additionally, please update the code as suggested by #Teemu in the comments
you've to check for col.textContent or col.innerHTML, not row.value

Object Orientation. How does the representation interact with the object. Javascript in this case

I am creating a tic-tac-toe game to play around with O-O code in Javascript, or should I say, pseudo-object orientation. And I'm having trouble wrapping my head around how a representation of an object, in this case, each grid cell being an object. How do you go from clicking on the cell to telling the cell object to place a mark here?
Here is my html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="scripts/tic-tac-toe.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div id="grid"></div>
</body>
</html>
And here is the unfinished javascript page:
var Grid = function() {
var cells = [];
// Todo: Finish
const WINNING_COMBINATIONS = new Array();
this.setup = function() {
for (var i = 0; i < 3; i++) {
cells.push(new Array());
for (var j = 0; j < 3; j++) {
var new_cell = new Cell();
cells[i].push(new_cell);
}
}
var grid_div = document.getElementById("grid");
var output = '';
for (var i = 0; i < cells.length; i++) {
for (var j = 0; j < cells.length; j++) {
output += cells[i].placeCell();
}
output += "<br />";
}
grid_div.innerHTML = output;
}
}
There's also a cell class which has a mark property, an output property (for what will be displayed) and a setMark method. So if I clicked on a cell which is created by the output property, how would I reference the cell which was being clicked?
Thanks in advance.

Categories