can't display data in table from js - javascript

In the following code I need to display months and days in a table. I am able to display months but I can't display days in my table (it contains two headers months and days).
for (var i = 0; i <= result.length; i++) {
var doc = result[i];
var td = $("<td/>").html(doc.Months).data(doc);
var td2 = $("<td/>").html(doc.Days);
var tr = $("<tr>").html(td).append('</tr>');
table.append(tr);
}
<table id="mydemo5" class="mytdemo5" style="display:none;border-collapse: collapse; border-color:white;" border="1">
<tr><th colspan="2">Absence history </th></tr>
<tr><th>Months</th><th>Days</th></tr>
</table>

You are appending only first td, not td2, better to do it this way:
var tr = $("<tr>").appendTo(table); // no need of closing tag, it will be auto handled by jQuery
var td = $("<td>").html(doc.Months).data(doc).appendTo(tr); //No need to assign to var td if it doesn't have any other use
var td2 = $("<td>").html(doc.Days).appendTo(tr);
//table.append(tr) Not needed anymore

Related

javascript how modify table cell

I have a simple table in HTML and I'm trying to edit a particular cell containing a number.
My arrays all have data in them and the table is created OK.
I want to have an edit box for the number in row3 col 2.
I have tried lots of things but nothing seems to work for me.
Needless to say I am a newbie at JS !!
Thanks,
Chris
Update - I have cracked it! more by luck than judgement.
This code does exactly what I want, but I'm finding it difficult to display for you. It works fine on codepenio.
<p id="dt"></p>
<table id="myTable">
<caption>Current values</caption>
<tr>
<th>Item</th>
<th>value</th>
<th>units</th>
</tr>
</table>
<!--
<input type="button" onclick="createRow()" value="Create Row" />
-->
<style>
table {
width: 400px;
}
th {
text-align: center;
}
table,
th,
td {
border: 1px solid #000;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
</style>
<script>
let numberOfrows = document.getElementById("myTable").rows.length;
let numberoftds = document.getElementById("myTable").rows[0].cells.length;
document.getElementById("dt").innerHTML = Date();
// All names including blanks are placed in array below P01 - P30 incl
pname_english =
"#cabinet model#Serial number#Face velocity#Face velocity alarm setpoint?#Laminar flow velocity#Laminar flow velocity alarm point?#Extract volume#Extract volume alarm point?#Filter pressure#Filter pressure alarm point?#filter saturation value#Hydrocarbon filter monitor#Formaldehyde filter condition monitor#UV tube hours run#Cabinet hours run#service due date#main carbon filter type#main carbon filter date fitted#";
let pnamearray = "pname_english";
pnamearray = pname_english.split("#");
name = "#p01AB200#P021234#P033.4#P041.2#P054.2#P064.8#P072.9#P083.2?#p092332";
let myarray = "name";
myarray = name.split("#");
units = "# # #m/s#m/s#m/s#m/s#Pa#Pa?# ";
let unitsarray = "units";
unitsarray = units.split("#");
console.log("Hello World!");
let col1 = "";
let col2 = "";
let col3 = "";
function createRow() {
//() causes the function to execute anyway!
var row = document.createElement("tr"); // create row node
col1 = document.createElement("td"); // create column node
col2 = document.createElement("td"); // create second column node
col3 = document.createElement("td"); // create second column node
row.appendChild(col1); // append first column to row
row.appendChild(col2); // append second column to row
row.appendChild(col3); // append second column to row
// col1.innerHTML = ""; // put data in first column
// col2.innerHTML = ""; // put data in second column
col3.innerHTML = ""; // put data in second column
var table = document.getElementById("myTable"); // find table to append to
table.appendChild(row); // append row to table
}
var table = document.getElementById("myTable");
var row = document.getElementsByTagName("tr")[0];
let l = 0;
for (i = 0; i < 8; i++) {
// add i rows to myTable
l = myarray[i].length;
col1.innerHTML = pnamearray[i]; // name column
col2.innerHTML = myarray[i].substring(3, l); //value column myarray[i];
col3.innerHTML = unitsarray[i]; //units column
if (i == 3) {
col2.innerHTML =
'<input type="number" id="tentacles" name="tentacles" min="10" max="100" value="20">';
}
createRow(); // create new row
}
</script>
</body>
document.getElementById("Table_ID").rows[YourRowIndex].cells.item(CellIndex)
RowIndex: Start from 0 to n-1( n is number of rows)
CellIndex: Start from 0 to m-1( m is number of cells per each row)

JS - Access a <table> from the DOM (error: "TypeError: tablex[0] is undefined")

I want to add <th> headers to a <table> that does not have an "id" but which is in a <div> having a known "id" so I traverse the DOM to find it:
// search <table>
var c = document.getElementById("tablediv").children;
var i; for(i = 0; i < c.length; i++)
{ Output("- " + c[i].nodeName + "<br>"); // show progress
if(c[i].nodeName == "TABLE") break; }
var tablex = c[i]; // that's the right object
var columns = tablex[0].length; // "TypeError: tablex[0] is undefined"
var row = tablex.insertRow(-1);
for(var i = 0; i < columns; i++)
{ var headerCell = document.createElement("TH");
headerCell.innerHTML = tablex[1][i];
row.appendChild(headerCell);
}
And when tablex[0].length; is run it raises "TypeError: tablex[0] is undefined".
I guess var tablex is an incorrect way to assign c[i];.
Can you please let me know how to do it right?
NOTE: the first TD row of the table contains the column titles so either we convert this row to TH or we fetch titles and delete the TD row after a TH row was inserted.
First of all, you don't need to traverse like that. It's easier to query the table directly with querySelector('#tablediv table'). Notice the use of querySelector instead of querySelectorAll, this returns first table inside the node with requested ID.
So the final code would look like this:
var table = document.querySelector('#tablediv table');
// Here you can add check if the table was found (not null) - I'll leave that to you
var firstRow = table.querySelector('tr');
var columns = firstRow.querySelectorAll('td'); // Or th if you have a header cells
console.log(`Number of columns: ${columns.length}`);
var headerRow = document.createElement('tr');
firstRow.parentNode.insertBefore(headerRow, firstRow);
for(var i = 0; i < columns.length; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columns[i].innerHTML;
headerRow.appendChild(headerCell);
}
firstRow.remove();
Considering the fact that tablex would optimally be a HTMLTableElement, tablex[0] is not defined.

javascript change color of a dynamically added row

I been doing a small script in HTA in which it reads info from text files and show the info on screen.
I have a table with a header row.
<table cellspacing="2" cellpadding="2" border="1" id="TablaResultados" style="font-size:10;">
<tr bgcolor="#cd0041" align="center" style="color:white;">
<th>Fecha</th>
<th>Id Evento</th>
<th>Tipo Evento</th>
<th>Ubicacion</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Comentarios</th>
</tr>
</table>
and in this table I add dynamically rows of the info I read using javascript
function AgregarFila(Datos) {
var table = document.getElementById("TablaResultados");
var ArrDatos = Datos.split("#");
var row = table.insertRow(1);
var LargoArreglo = ArrDatos.length;
for (var i = 0; i < LargoArreglo; i++){
var cell1 = row.insertCell(i);
cell1.innerHTML = ArrDatos[i];
cell1.style.backgroundColor = "#99cc00";
}
}
every N rows I need to clear the color of the rows to white, and I am using this
function TablaABlanco() {
var table = document.getElementById("TablaResultados");
var rows = table.getElementsByTagName("tr");
for (var i = 1; i < rows.length; i++) {
rows[i].style.backgroundColor = "#ffffff";
}
}
My issue is that it does not change the color of the rows. I know that the function TablaABlanco does work because if I run the for loop from zero it changes the color of the header of the previous table.
I believe I might need to check something else to validate the new rows but I have been googling with no luck.
The issue is that in AgregarFila, you set the each cell to have a background color. In TablaABlanco, you set the row to be white. The style on the cell will take priority and override the style you apply to the row.
So instead of changing each cell to have the background color, you change the row's background color when you add it.
function AgregarFila(Datos) {
var table = document.getElementById("TablaResultados");
var ArrDatos = Datos.split("#");
var row = table.insertRow(1);
row.style.backgroundColor = "#99cc00";
var LargoArreglo = ArrDatos.length;
for (var i = 0; i < LargoArreglo; i++){
var cell1 = row.insertCell(i);
cell1.innerHTML = ArrDatos[i];
}
}

how to insert a <td> to a <tr> using jquery

I have a table with few rows, I just need to re arrange them, I am able to fetch <td> and <tr> and now what I need to do is to insert them back in a custom order
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)'); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)');
var td4 = tr.find('td:eq(7)');
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td4.remove();
td5.remove();
td6.remove();
td7.remove();
tr.insert(td7); // here am getting errors, i tried .append also
tr.insert(td6);
tr.insert(td4);
});
i just need to know how to insert td to this tr (currently tr is blank i guess, after removing all td)
You do not need .remove() at all. All you need is to use append and prepend (or appendTo and prependTo) in a clever way to rearrange your cells. These methods do not copy DOM nodes, they move them, so removal is completely unnecessary.
Quick example:
$('.white-header').each(function() {
var tr = $(this);
tr.find('td:eq(4)').appendTo(tr);
tr.find('td:eq(6)').appendTo(tr);
tr.find('td:eq(9)').prependTo(tr);
});
(in my example the order of the elements might seem strange at the end, because I don't run :eq on the original order, but always on the already changed order - this is only a quick example)
You are trying to append the deleted objects, You need to make clone of <td> and remove the <td> objects you have later append the cloned objects of insert
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)'); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)');
var td4 = tr.find('td:eq(7)');
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td4Cloned = td4.clone();
td4.remove();
td5.remove();
td6Cloned = td6.clone();
td6.remove();
td7Cloned = td7.clone();
td7.remove();
tr.insert(td7Cloned); // here am getting errors, i tried .append also
tr.insert(td6Cloned);
tr.insert(td4Cloned);
});
Try using .detach()
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)').detach(); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)').detach();
var td4 = tr.find('td:eq(7)').detach();
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td5.remove();
tr.append(td7); // here am getting errors, i tried .append also
tr.append(td6);
tr.append(td4);
});

Changing a div space with a table

Suppose I have these three spaces that are blank to start with. I want to change using innerHTML in JavaScript.
<p id="topname"></p>
<div id="table"></div>
<p id="botname"></p>
document.getElementById("topname").innerHTML = "Boy";
document.getElementById("botname").innerHTML = "Girl";
I managed to change topname and botname with the innerHTML. How do I change div id="table" to display an x by y (2x2, 4x4, 8x8,etc.) table?
Instead of replacing the <div> with a <table>, it is recommended to create a <table> as a child node of the <div> As long as you have not added additional styling to the <div> (like padding or margins), this will have no effect on the display.
A couple of loops to build <tr> and <td> will do the job. Here's a function that takes x and y:
function makeTable(rows, cols) {
// Create a table node
var tbl = document.createElement('table');
// Make a <tr> for each row
for (var i=0; i<rows; i++) {
var tr = document.createElement('tr');
// And make a <td> for eah col
for (var j=0; j<cols; j++) {
var td = document.createElement('td');
// Append them to the current tr
tr.appendChild(td);
}
// Append the row
tbl.appendChild(tr);
}
return tbl;
}
// Create a new 2x4 table with the function
var newTable = makeTable(2, 4);
// And append it as a child to the <div id='table'>
document.getElementById('table').appendChild(newTable);
Here it is in action
You should be able to do it the same way, however, that div id might be giving you issues. TABLE is an html entity unto itself. I would rename that.
document.getElementById("table").innerHTML = "<table><caption>Caption</caption><thead>Table Header</thead><tfoot>Table Footer</tfoot><tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table>";
And what Shadow Wizard said above. It is best to use the right tool for the job. My answer is solely if you insist on doing it within a div.
First of all, change your div to a table manually:
<table id="table"></table>
With following code you can fill your table with rows and columns:
document.getElementById("table").appendChild(makeTable(2, 4));
function makeTable(rows, cols) {
var table = document.createDocumentFragment(), tr = document.createElement("tr"), td = document.createElement("td"), i, j;
for(j = 0; j < cols; j++) tr.appenChild(td.cloneNode(true));
for(i = 0; i < rows; i++) table.appendChild(tr.cloneNode(true));
return table;
}

Categories