Iterate HTML table to highlight differences where cells have multiple comparison items - javascript

I want to highlight differences between the first row of a table and all the other rows column-wise.
I have figured out how to accomplish this when each cell in the table only has 1 item/comparison. But I would like to extend this to multiple comparisons per cell separated by ","s.
Here is the code for the single item per cell. https://jsfiddle.net/t19Lqbkn/
using the following code:
var table = document.getElementById("mytab1");
for (var i = 1, row; row = table.rows[i]; i++) {
var matc = table.rows[1]
for (var j = 0, col; col = row.cells[j]; j++) {
if (col.innerHTML !== matc.cells[j].innerHTML){col.innerHTML = "<span style='color: red;'>" + col.innerHTML + "</span>";}
}
}
And here is a table with multiple items per cell.
https://jsfiddle.net/6c7s9mky/
As you can see in the second link. The first column of the second row, only the item "Eve" should be red, and in the last row of the first column there should be no red color text.

String and Array have lots of cool methods
Here an example:
const base = "with,hello,string"
let comparison = "string,with,comma";
comparison = comparison.split(",").map(str =>
base.indexOf(str) !== -1?`<span style="color:red;">${str}</span>`:str
).join(",");
You can also find a way with RegExp.

Related

Creating a table perfectly aligned in a row of another table

So, I wanna create table which has only one row and that is perfectly aligned with a row of another table,
I know it is weird that why I wanna do that I can demonstrate that with this image.
I want all the rows to be aligned perfectly with each other except row 2,
All rows should have 5 cols but only row 2 have 3 cols.
I couldn't achieve this from increasing colSpan because it just aligns it with the next col.
So I think the only way to achieve this is to add another table inside a row but doing this compresses the table in the middle, like this pic
This is what I am doing:
let newTable = document.createElement("table");
let newRow = document.createElement("tr");
for (let i = 0; i < 3; i++)
{ newRow.appendChild(document.createElement("td")); }
newTable.appendChild(newRow);
// Added row
let row = document.createElement("tr");
row.id = "tempR" + btn;
let data = document.createElement("td");
data.colSpan = 7;
data.style.padding = "0px";
data.appendChild(newTable);
row.appendChild(data);
prevRow = document.getElementById("row" + btn).insertAdjacentElement("afterend", row);

how to loop in html table and change the value of each cell in javascript

I have my input table which already filled by the user. now what I am trying to do is to loop on my table and change the value of each cell td using my JavaScript. some of my cells has input field and others only have text between td tags. I loop on my table correctly and I change the values of cells that has input field using the expression table.rows[R].cells[C].children[0].value = value; but I do not know how to change the cell that has only text between td tags without input field! tried to write table.rows[R].cells[C].value = value but its not working!
my table code:
var table = document.getElementById('table');
var rowCount = table.rows.length;
var colCount = document.getElementById('table').rows[0].cells.length;
for (var r = 1; r < rowCount; r++) {
for (var c = 1; c < colCount - 1; c++) {
table.rows[r].cells[c].children[0].value = somevalue; // this works with cells that has input field but not with cells that has not
table.rows[r].cells[c] value = somevalue; // tried this line but not working
}
}
Based on your explanation I understand that you want to modify the values of all td tags (input child or text child). In your snippet there are two problems in order to achieve this:

The start index of the “column loop” (c) is 1 and you loop until
this index is less than the length of all columns. This means that
you’ll loop through all the columns except the first and last one.
Maybe this is your intention.
You have a syntax error in the last line of the last for loop.


For your “main” problem, it seems like you are treating the cells the same even though some contain input elements and some text nodes. You can simply solve this by adding some logic and depending on if the cell has children (an input field) or not (text-node) you treat it respectively. For text nodes we simply modify the innerHTML.
Here's a snippet which should do the job for you if I understood you correctly:
var table = document.getElementById("table");
var rowCount = table.rows.length;
var colCount = document.getElementById("table").rows[0].cells.length;
var somevalue = "modified value";
for (var r = 1; r < rowCount; r++) {
for (var c = 0; c < colCount; c++) {
const cell = table.rows[r].cells[c];
if (cell.children.length) {
cell.children[0].value = somevalue;
} else {
cell.innerHTML = somevalue;
}
}
}

double forEach to double for Loop

I'm creating an HTML table from a server-side array (google apps script; so tableArray is coming from there). I have two forEach functions which work. However, I'm attempting to use two for loops instead because I'd like to be able to add different classes to different <td>'s.
The output doesn't come out as expected (see #1 below). I can either get an array in one column (instead of each element of the array as a separate <td> or the arrays are repeated in each <td> (see #2 below).
What do I need to change in my for loops to get the expected output?
You can see the version that works HERE.
1 (works with forEach)
2 (does not work with for)
Index.html
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column));
row.appendChild(cell);
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
}
Instead of line cell.appendChild(document.createTextNode(column));
write cell.appendChild(document.createTextNode(column[j]));
You've forgotten to add index [j]
// Loop over rows
for (var i = 0; i < tableArr.length; i++) {
var row = tableArr[i];
// loop over columns
for( var j =0; j<row.length; j++){
//create each column and append to row
}
// append row to table body
}
// append table body to DOM
For performance reasons you want to write to the DOM only once and create the table in memory first.
Change
cell.appendChild(document.createTextNode(column));
to
cell.appendChild(document.createTextNode(column[i]));
This will make it loop through all of your column data properly instead of appending the same content of the whole array repeatedly.

How to iterate through a table in Javascript and swap specified cells with each other?

I have a table with an id of "mytable", and I have a for loop that builds a 4x4 table, giving each cell an id from 0 to 15 and setting the innerHTML equal to that same number. Once cell is left blank, as this is going to be part of a sliding puzzle game where a user presses a button which scrambles the cells of the table, the solves it by shifting cell positions into that blank space. My issue at the moment is that I can't seem to implement a shuffle function that works. Below is my my code for building a table and shuffling it. See the comments for the error message.
function buildTable(){//need to build it with every cell being named
var tablelocation = document.getElementById('mytable');
var table = document.createElement('table');
table.id="newtable";
for(var i = 0; i<tableSize; i++){
var tableRow = table.insertRow();
for(var j = 0; j<tableSize; j++){
var arrTmp = (tableSize*tableSize-1)-(i*tableSize+j);
var cell = tableRow.insertCell();
cell.id = arrTmp;
if(arrTmp==15){
cell.className = "empty_cell";
else{
cell.className = "cell";
cell.appendChild(document.createTextNode(arrTmp));
}
}
}
tablelocation.appendChild(table);
}
Because the table is built from the bottom right to the top left I have a variable, that handles the values so that once the table is built the numbers appear in the table from 0 to 15 from top left to bottom right.
function shuffleTable(){//need to build it with every cell being named
var table = document.getElementById("newtable");
for (var i = 0; i<tableArray.length; i++) {
var tmp = tableArray[i];//array of shuffled ID values
var tmp2 = objectCellArray[tmp];
objectCellArrayShuffled.push(tmp2);
}
for (var j = 0; j<tableArray.length; j++){
var cell = table.cells[j];//fails here with undefined is not an object error
cell = objectCellArrayShuffled[j];
}
}
I'm calling shuffleTable with a button on my html page.

Javascript - Search Table Column for String

I am searching my Table Column for the string "None". It does this but I am unable to get the row number after. I am attempting to use the "rowIndex" attribute. Not sure why it is pulling "Not a Number" (NaN). Table is 50 rows 10 cols. I am assuming it may have to do with that I am pulling from a column instead of Row.
function F0416()
{
var tab = document.getElementById('part1Table');
var l = tab.rows.length;
var s = '';
for ( var i = 0; i < l; i++ )
{var tr = tab.rows[i];
var cll = tr.cells[2];
s += ' ' + cll.innerText;
}
var y = (s.indexOf('None') != -1)
document.write(this.rowIndex + 1)
Instead of concatenating all the values of the column into a string and searching the string, you could instead test the value of each cell in the column for the value 'None'. Then you would know the row number from the loop counter, and you could halt the loop if you find it instead of iterating over every row.
It would look more like this:
for ( var i = 0; i < l; i++ ) {
var tr = tab.rows[i];
var cll = tr.cells[2];
if(cll.innerText.indexOf('None') != -1) {
document.write(i + 1);
break;
}
}
You could also return the value of the row instead of outputting it.
I would recommend using a rich javascript library like JQuery.
Then given the following HTML:
<table>
<tr><td>Row 1- Column 1</td><td>Row 1 - Column 2</td>
<tr><td>none</td><td>Row 2 - Column 2</td>
<tr><td>Row 3- Column 1</td><td>Row 3 - Column 2</td>
</table>
You can use the following to get all the rows containing none:
var rows = $('table tr').filter(":contains('none')");
Have a look at this Fiddle example.

Categories

Resources