Create a row using group off arrays - javascript

Lets say we have an Array that looks like this
(example)
Array1 = [Data_A,Data_B];
Array2 = [Data_1,Data_2,Data_3];
and I have a table that looks like this
How can I achieve this?
For now I can retreive the data in row order using for loop and this is my code
for (i = 0; i < Array1 .length; i++) {
for (x in Array1 [i]) {
console.log(data from array);
}
}
My target here is for every array is I need to make it as a row for every col. for example Array1 is fol Col1 and also note that my arrays are fixed for each col. col3 and 4 are for ex. only

Because the data in table columns don't usually change unlike they do in rows, I highly discourage managing table data by columns. It is best to do it by rows.
What I mean is to have Row1 = [Data_A, Data_1]; and Row2 = [Data_B, Data_2]; and so on, rather than how you had it set up.
function CreateRow(data) {
var tr = "<tr>"
for (var i = 0; i < data.length; i++) {
tr += "<td>" + data[i] + "</td>";
}
tr += "</tr>"
$('#table').append(tr);
}
function EditRow(data, rowIdx) {
var tr = $('#table').children().eq(0);
for (var i = 0; i < data.length; i++) {
tr.children().eq(i).text(data[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Data 0</td>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
<button type="button" onclick="CreateRow(['A','B','C','D'])">Create Row</button>
<button type="button" onclick="EditRow(['EditedData1','EditedData2', 'EditedData3', 'EditedData4'], 0)">Edit First Row</button>
(Pure Javascript snippet for those who are interested)
function CreateRow(data) {
var table = document.getElementById("table");
var tr = document.createElement("tr");
for (var i = 0; i < data.length; i++) {
var td = document.createElement("td");
td.appendChild(document.createTextNode(data[i]));
tr.appendChild(td);
}
table.appendChild(tr);
}
function EditRow(data, rowIdx) {
var tr = document.getElementById("table").getElementsByTagName("tr")[rowIdx];
for (var i = 0; i < data.length; i++) {
tr.getElementsByTagName("td")[i].innerHTML = data[i];
}
}
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Data 0</td>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
<button type="button" onclick="CreateRow(['A','B','C','D'])">Create Row</button>
<button type="button" onclick="EditRow(['EditedData1','EditedData2', 'EditedData3', 'EditedData4'], 0)">Edit First Row</button>

Related

loop over table to set the background css

My HTML table has some classes and table tag is used
Want to retain the classes as is, but all my table and tr , th or td are using td bgcolor which is an old technique.
I want to loop over the table and find if that bgcolor is defined, use the same color and convert it to a css based background color so i can print it in IE
function setBackground() {
var table = document.getElementById("table1");
//i found this in a previous stack overflow answer and tried it
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
//this is for debugging purposes... I can't even get this to work
alert(table.rows[i].cells[j]);
table.rows[i].cells[j].style.background = "orange"; //just an example
}
}
}
because IE is not able to print the background lines and colors for some reason using the webkit property
I cleaned up the for loops a little. You can read the attribute with getAttribute and set the style.
var table = document.getElementById("table1");
for (var i = 0; i < table.rows.length; i++) {
var row = table.rows[i]
for (var j = 0; j < row.cells.length; j++) {
var cell = row.cells[j]
var bgc = cell.getAttribute('bgcolor')
if (bgc) {
cell.style.background = bgc
}
}
}
td {
width: 30px; height: 30px;
}
<table id="table1">
<tr>
<td bgcolor="red"></td>
<td></td>
<td bgcolor="blue"></td>
</tr>
<tr>
<td></td>
<td bgcolor="green"></td>
<td></td>
</tr>
<tr>
<td bgcolor="yellow"></td>
<td></td>
<td></td>
</tr>
<tr>
<td bgcolor="silver"></td>
<td></td>
<td></td>
</tr>
</table>
You can just do it with one loop with getElementsByTagName
var tds = document.getElementById("table1").getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
var cell = tds[i]
var bgc = cell.getAttribute('bgcolor')
if (bgc) {
cell.style.background = bgc
}
}
td {
width: 30px; height: 30px;
}
<table id="table1">
<tr>
<td bgcolor="red"></td>
<td></td>
<td bgcolor="blue"></td>
</tr>
<tr>
<td></td>
<td bgcolor="green"></td>
<td></td>
</tr>
<tr>
<td bgcolor="yellow"></td>
<td></td>
<td></td>
</tr>
<tr>
<td bgcolor="silver"></td>
<td></td>
<td></td>
</tr>
</table>
Get the color if found and then do with it whatever needed...
function setBackgroundColor(colorValue) {
const table = document.getElementById("table1");
const rows = table.children[0].rows
for (let i = 0; i < rows.length; i++) {
const tds = rows[i].children;
for (let j = 0; j < tds.length; j++) {
if (tds[j].bgColor === colorValue) {
console.log('Color found, do action')
}
}
}
}
setBackgroundColor('red')
<table id="table1">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td bgcolor="red">January</td>
<td bgcolor="green">$100</td>
</tr>
</table>
You can do this:
var cells = $("#targetTable td");
for(i in cells){
color = $(cells[i]).attr('bgcolor');
console.log(color);
$(cells[i]).css({background: color});
}
as Taplar mentioned in the comment :
Use document.querySelectorAll('td[bgcolor]') to get the td that have bgcolor, loop through them and set the background to that color :
document.querySelectorAll('td[bgcolor]').forEach(e => {
const bgColor = e.getAttribute('bgcolor');
e.removeAttribute('bgcolor'); // optional, if you want to remove the attribute
e.style.background = bgColor;
})
<table id="table1">
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
</thead>
<tbody>
<tr>
<td bgcolor="red">1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td bgcolor="green">5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td bgcolor="blue">9</td>
</tr>
</tbody>
</table>

Convert javascript alertbox to show it on a html textbox

I want to show my xy coordinates in html td cell using JavaScript but instead of showing an alert, I want it to be shown in an html textbox
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 1; i < cells.length; i++){
var cell = cells[i];
cell.onclick = function(){
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
alert("X: " + cellIndex + " / Y: " + rowIndex );
}
}
I have loop over the td elements and bind click event.So each time you click on td you will see cellIndex and rowIndex.Check my code and let me know if it satisfies you.
var cells = document.querySelectorAll("table td");
for(var i = 0; i < cells.length; i++){
cells[i].addEventListener('click',showCoordinates);
}
function showCoordinates(){
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
this.innerHTML = "X:"+cellIndex +" Y:"+rowIndex;
}
table td{ padding:10px; }
<table border="1">
<tr>
<td>TD</td>
<td>TD</td>
<td>TD</td>
</tr>
<tr>
<td>TD</td>
<td>TD</td>
<td>TD</td>
</tr>
</table>
There are different ways to achieve what I think you want. Feel free to update you question to reflect your will. Adding your HTML as inquired in comment, would be useful.
Lets assume that your table doesn't use rowspan or colspan. Something like this:
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
The basic way with two loops:
// Lets get all your rows
var rows = document.querySelectorAll("table tr");
// for each row...
for (var j = 0; j < rows.length; j++) {
var row = rows[j];
// ... we will find all this rows' cells.
var cells = row.querySelectorAll("td");
// for each cell...
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
// ... we will set its textContent to its coordinate in the table
cell.textContent = "X: " + (i + 1) + " / Y: " + (j + 1);
}
}
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Another solution if you know beforehand the number of columns:
var colsCount = document.querySelectorAll("table tr:nth-child(1) td").length;
var cells = document.querySelectorAll("table td");
for (var i = 0; i < cells.length; i++) {
const y = i / colsCount | 0;
const x = i % colsCount;
cells[i].textContent = `X: ${x + 1} / Y: ${y + 1}`;
}
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>

getElementsByTagName for the 1st row columns in Javascript

I have a table and I am editing the name of a specific table column value using the code below in JS:
document.querySelector('tr:nth-child(1) > td:nth-child(1)').innerHTML = "1111";
Now, I am trying to make it more dynamic considering that the column is unknown (first or third etc).
The script below check for every td in the table and it works:
var columns = document.getElementsByTagName('td');
for (var i=1; i<columns.length; i++)
{
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 1"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "11111";
}
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 2"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "2222";
}
console.log(i);
}
<table border="1" class="richtext-query-table"><tbody><tr><td>Column 0</td><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td></tr><tr><td>Column 5</td><td>£3K</td><td>5,748</td><td>£0.45</td><td>0.93 %</td></tr><tr><td></td><td>--</td><td>4,551</td><td>£0.00</td><td>0.66 %</td></tr></tbody></table>
but I am getting an error because of the fact that the script applies for every td in the table. Now, I am trying to make it work only for the tds of the first row.
var columns = document.getElementsByTagName('tr:first-child > td');
for (var i=1; i<columns.length; i++)
{
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 1"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "1111";
}
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 2"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "2222";
}
console.log(i);
}
<table border="1" class="richtext-query-table"><tbody><tr><td>Column 0</td><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td></tr><tr><td>Column 5</td><td>£3K</td><td>5,748</td><td>£0.45</td><td>0.93 %</td></tr><tr><td></td><td>--</td><td>4,551</td><td>£0.00</td><td>0.66 %</td></tr></tbody></table>
and it does not work unless I try using the eq function from this answer:
LINK
although I am having limitations with the functions in the platform I am using. I can use another line to get the first row and then get the columns from the first row (for statement) but I am guessing there is an easier way by just changing the part:
var columns = document.getElementsByTagName('tr:first-child td');
It looks simple but I cannot find a solution.
document.getElementsByTagName('tr')[0] it will return first tr, then row.querySelectorAll('td') get all columns of first row.
var row = document.getElementsByTagName('tr')[0];
var columns = row.querySelectorAll('td');
for (var i = 1; i < columns.length; i++) {
if (row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML.includes("Column 1")) {
row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML = "1111";
}
if (row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML.includes("Column 2")) {
row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML = "2222";
}
console.log(i);
}
<table border="1" class="richtext-query-table">
<tbody>
<tr>
<td>Column 0</td>
<td>Column 1</td>
<td>Column 2</td>
<td>Column 3</td>
<td>Column 4</td>
</tr>
<tr>
<td>Column 5</td>
<td>£3K</td>
<td>5,748</td>
<td>£0.45</td>
<td>0.93 %</td>
</tr>
<tr>
<td></td>
<td>--</td>
<td>4,551</td>
<td>£0.00</td>
<td>0.66 %</td>
</tr>
</tbody>
</table>

Adding rows to table body dynamically

I am trying to add rows to an existing table that has header and footer also.
Here is my code:
<script>
function test() {
var tbl = document.getElementById("tbl");
var lastRow = tbl.rows.length - 1;
var cols = tbl.rows[lastRow].cells.length;
var row = tbl.insertRow(-1);
for (var i = 0; i < cols; i++) {
row.insertCell();
}
}
</script>
<table id="tbl" onclick="test()">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
when I click on any table I want to add new row to table body, but the issue here is the new row is added to table footer. please help me how to fix this issue.
You insert the row into the tBody element. Since there can be more than one tBody, you should refer to the tBodies prop of table at index 0.
var row = tbl.tBodies[0].insertRow(-1);
function test() {
var tbl = document.getElementById("tbl");
var lastRow = tbl.rows.length - 1;
var cols = tbl.rows[lastRow].cells.length;
var row = tbl.tBodies[0].insertRow(-1);
for (var i = 0; i < cols; i++) {
row.insertCell().appendChild(document.createTextNode(i));
}
}
test();
<table id="tbl" onclick="test()">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
Try something like this. Just clone first row and then append it as child to your table. Hope it will help you
function appendRow() {
let tbl = document.getElementById("tbl");
let newRow = tbl.rows[0].cloneNode(true);
tbl.appendChild(newRow);

JS - Compare first row to other rows in table

I'm a completely newbie and looking for help.
Given the following table:
<table id="table">
<thead>
# FIRST ROW
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
</tr>
<tbody>
# SECOND ROW
<tr>
<td>Apple</td> --> should end with 'success' class
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td> --> should end with 'success' class
</tr>
# THIRD ROW
<tr>
<td>Pizza</td> --> should end with 'success' class
<td>Chicken</td>
</tr>
</tbody>
</table>
I would like to add class 'success' to every td in SECOND and THIRD rows whenever it matches any td in FIRST row (and only in FIRST ROW).
For now I came up with adding <td> values of first row to array and I'm not sure what steps should I take next (filter? for loop and '===' comparison?):
function myFunction() {
var tHeadersValues = [];
var tHeaders = document.getElementById("table").rows[0].cells;
for (var i = 0; i < tHeaders.length; i++) {
tHeadersValues.push(tHeaders[i].textContent);
}
return tHeadersValues;
}
Object.keys(tHeaders).map(key => tHeaders[key].textContent) transforms the td objects to an array with the containing text. The rest is straight forward:
function toValues(tHeaders) {
return Object.keys(tHeaders).map(function(key){
return tHeaders[key].textContent;
});
}
function myFunction() {
var rows = document.getElementById("results-table").rows;
var tHeadersValues = toValues(rows[0].cells);
for (var i = 1; i < rows.length; i++) {
var rowCells = rows[i].cells;
var values = toValues(rowCells);
for(var j=0;j<values.length;j++) {
if(values[j].length > 0 && tHeadersValues.indexOf(values[j]) > -1) {
rowCells[j].className = "success";
}
}
}
}
myFunction();
<style>
.success {
background-color: green;
}
</style>
<table id="results-table">
<thead>
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td>
</tr>
<tr>
<td>Pizza</td>
<td>Chicken</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
function myFunc(){
var tds = document.getElementsByTagName("td");
var hds = document.getElementsByTagName("th");
for(var i=0; i<tds.length; i++) {
var tdContent = tds[i].innerHTML;
if(tdContent.length > 0){
for(var j = 0; j<hds.length; j++) {
if(tdContent === hds[j].innerHTML) {
document.getElementsByTagName("td")[i].className = "success";
}
}
}
}
}
myFunc();
<style>
.success {
background-color: green;
}
</style>
<table id="results-table">
<thead>
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td>
</tr>
<tr>
<td>Pizza</td>
<td>Chicken</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>

Categories

Resources