InnerHTML changes old variables - javascript

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;

Related

To create a custom table by getting values from a dynamicaly created table

what I want is on save click to show another table like below where the second column(Questions) has sub-columns depending maximum L value a row has:
unit Question
unit1 23(L1)
unit2 23(L3)
unit3 24(L3)
unit4 6(L2)
unit4 10(L4)
unit5 7(L1)
unit5 10(L6)
unit6 10(L2)
unit 7(L4)
var x = [];
function getval() {
var trs = $('#DyanmicTable3 tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)');
var trs1 = $('#DyanmicTable3 tr:last-child');
var lastTotalElement = $('#DyanmicTable3 tr:nth-last-child(2)');
console.log(trs1);
for (let i = 2; i <= 7; i++) {
const total = Array.from(trs)
.reduce((acc, tr) => x.push(Number(tr.children[i].textContent)), 0);
;
}
console.log(JSON.stringify(x));
}
this is wt i got so far getting values in an array
function GenerateTable() {
var grid = new Array();
grid.push(["Unit", "Marks", "Bloom Level"]);
var tb = $('#DyanmicTable3:eq(0) tbody ');
tb.find("tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)").each(function (index, element) {
var colValtst;
$(element).find('th:not(:first-child):not(:nth-last-child(2)):not(:last-child)').each(function (index, element) {
colValtst = $(element).text();
});
$(element).find('td').each(function (index, element) {
var colVal = $(element).text();
let y = $(element).index();
if (colVal != '') {
console.log(" Value in " + colValtst + " : " + colVal.trim() + " L" + y);
//add grid here
grid.push([colValtst, colVal.trim(), "L" + y]);
}
});
});
//Build an array containing Customer records.
// $('#save').attr('href', 'AddQuestions.aspx?val1=' + grid + '');
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = grid[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = grid[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < grid.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = grid[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);

How to create a working identifier for the cells of this table?

I'm trying to give each cell of a table an identifier like in this photo
this is what I tried but it's not working:
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;// <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier;// <--------this is the problem
}
}
document.getElementById("main").appendChild(board);
}
First of all, instead of custom properties you should use data attributes and instead of the width and height attributes you should use CSS. Second, you were incrementing identifier by itself, so it wouldn't grow from 0.
const GRID_SIZE = 6;
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.dataset.identifier = identifier;
cell.innerText = identifier;
row.appendChild(cell);
identifier++;
}
}
document.getElementById("main").appendChild(board);
}
init();
main>table td {
width: 20px;
height: 20px;
}
<main id="main"></main>
Also, you don't need to store the coordinates of the cell, since you can calculate them from the identifier like this:
row = Math.floor(identifier / GRID_SIZE);
column = identifier % GRID_SIZE;
GRID_SIZE*i+j;
put it inside the cell using cell.innerHTML=GRID_SIZE*i+j;
function init(GRID_SIZE) {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0; // <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.innerHTML = GRID_SIZE * i + j;
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier; // <--------
}
}
document.getElementById("main").appendChild(board);
}
init(10)
<div id="main"></div>

How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page

How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.

Need separate javascript file function to work and it is not

I have a unique problem that I hope someone can help with. I have a page that pulls data from a controller with AJAX and presents it to this function to construct a table:
// make rows in table from json data
function makeTableRows() {
if (jsonTableData != null) {
tbl = null;
tbl = createTable('tableResults');
// constructHeader(tbl, 'left', jsonTableData[0]);
newHeader(tbl, 'left', jsonTableData[0]);
var totalItems = jsonTableData.length;
var topItem;
topItem = 0;
if ((lastItem + perpage) > totalItems) {
topItem = totalItems;
$(".btnNext").prop('disabled', true);
}
else {
topItem = lastItem + perpage;
}
for (var i = lastItem; i <= topItem - 1; i++) {
makeTableRow(tbl, jsonTableData[i], 'left', true, 'showTourDetails(' + jsonTableData[i]["TransactionID"] + ',' + i + ')', 0);
}
$("#divSearchResults").html(tbl);
makePagesLabel();
makeTableFooter(tbl);
}
}
the function inside the separate file is this:
function constructHeader(table, alignment, firstRow) {
if (firstRow != null) {
var thead = document.createElement('thead');
table.appendChild(thead);
var tr = document.createElement('tr');
for (var key in firstRow) {
var header = key.match(/[A-Z][a-z]*/g);
var newHeader = '';
for (var i = 0; i <= header.length - 1; i++) {
newHeader += header[i] + ' ';
}
var th = document.createElement('th');
var text = document.createTextNode(newHeader);
th.appendChild(text);
th.style.textAlign = alignment;
th.style.cursor = 'pointer';
th.setAttribute('title', "Sort by " + newHeader);
th.onclick = function () {
var rows = $(table).find('tbody').find('tr').toArray().sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc) {
rows = rows.reverse();
}
for (var j = 0; j < rows.length; j++) {
$(table).append(rows[j]);
}
$(table).find('tbody').find('tr:even').css("background-color", "#dae5f4");
$(table).find('tbody').find('tr:odd').css("background-color", "#b8d1f3");
};
tr.appendChild(th);
}
thead.appendChild(tr);
}
}
Basically the function creates a sort process for the header of each column. After the sort of the column, I want to reapply the zebra striping that is applied with the class of the table. If I don't try to reapply I end up with the striping all messed up. Now, the problem is that if I copy the function into the .cshtml page and give it the name of 'newheader', the re-striping works fine. It does not work in the separate JS file and I cannot figure out why. Anyone have any clues?

Change class attribute of td by onmouseover

I'm constructing a table. And I need a <td> of table change it's attribute class to someattribute till mouse over.
How should it be?
Code:
var table = document.createElement('table');
for (var i = 1; i <=10; i++)
{
var tr = document.createElement('tr');
tr.setAttribute('id',i)
table.appendChild(tr);
for (var j = 1; j <=15; j++)
{
var td = document.createElement('td');
td.setAttribute('id',j);
// Here:
td.OnMouseOver = new function()
{
td.setAttribute("class","new");
};
tr.appendChild(td);
};
};
document.getElementById("grid").innerHTML = '';
document.getElementById("grid").appendChild(table);
You are quite close.
Use the keyword this in your onmouseover function, instead of td, which is not accessible to your function. Also, you do not need to use the keyword new to define a function.
td.onmouseover = function () {
this.setAttribute("class", "new");
};
Code:
var table = document.createElement('table');
for (var i = 1; i <= 10; i++) {
var tr = document.createElement('tr');
tr.setAttribute('id', i)
table.appendChild(tr);
for (var j = 1; j <= 15; j++) {
var td = document.createElement('td');
td.setAttribute('id', j);
td.innerHTML = ' ';
td.onmouseover = function () {
this.setAttribute("class", "new");
};
tr.appendChild(td);
};
};
document.getElementById("grid").innerHTML = '';
document.getElementById("grid").appendChild(table);
http://jsfiddle.net/samliew/VnkHB/10/
If you did want to use jQuery:
$('table td').mouseover(function() {
$(this).addClass('new');
});
This would add the class new to any <td> element in any <table> on the mouseover event.
without jQuery:
function mouseover() {
this.setAttribute("class", "new");
return true;
}
var table = document.createElement('table');
var tr, td;
for (var i = 1; i <= 10; i++) {
tr = document.createElement('tr');
tr.setAttribute('id', 'td'+i);
table.appendChild(tr);
for (var j = 1; j <= 15; j++) {
td = document.createElement('td');
td.setAttribute('id', 'tr'+j);
// Here:
td.onmouseover = mouseover;
td.innerText = "..";
tr.appendChild(td);
}
}
document.getElementById("grid").innerHTML = '';
document.getElementById("grid").appendChild(table);
function is moved to outside the loop, ids are prefixed to avoid collision
with jQuery:
function mouseover() {
this.setAttribute("class", "new");
return true;
}
function nNewElements(tag, idPrefix, n) {
var result = [];
for (var i = 1; i <= n; i++) {
result.
push($("<" + tag + ">").
attr("id", idPrefix + i)[0]);
}
return $(result);
}
$(document).ready(function () {
$("#grid").
html('').
append('<table>');
nNewElements("tr", "row", 10).
appendTo("table").
each(function () {
nNewElements("td", "data", 15).
mouseover(mouseover).
text("..").
appendTo($(this));
});
});

Categories