Run function on all cells in table column with jQuery - javascript

I have a table element defined below as $table. I am trying to run a function on every cell a specific column that is defined by a specific table heading - qc_statusTh. I have found the index of that table heading (qc_statusColumnIndex) and have been able to grab the next table cell in that column - qc_statusCell.
However, I am not able to loop through the table cells and run a function on each table cell in that column.
Here is the JavaScript code I have so far:
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_statusCell = $($table).find("td").eq(qc_statusColumnIndex);
// this does not work. this only replaces the first cell
// in the row after qc_statusTh with "TESTING"
$(qc_statusCell).each(function() {
$(this).replaceWith("TESTING");
});
}
});
How can I edit this code to loop through each cell in the table that has an equal index to qc_statusColumnIndex?

If you think about it, you really want to iterate (using each) over the rows of the table, not the cells. If you do that, you can then grab the nth td element from each row and apply your transformation.
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_rows = $($table).find('tr');
$(qc_rows).each(function() {
$(this).find('td').eq(qc_statusColumnIndex).replaceWith("TESTING");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tables list">
<thead>
<th class="headersub">qc_example</th>
<th class="headersub">qc_status</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ok</td>
</tr>
<tr>
<td>2</td>
<td>Ok</td>
</tr>
<tr>
<td>3</td>
<td>Error</td>
</tr>
</tbody>
</table>

Related

How do I change the style of a cell in a column in an HTML table based on conditions?

I have an HTML table where the rows and cells are created dynamically using JavaScript. I need to change the style (background colour) of the cell with the lowest and highest value within each column. How do I achieve this? I have given each <td> tag within the same column a class.
<table id="table">
<thead id="thead">
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
</thead>
<tbody id="tbody">
//DYNAMICALLY ADDED TR AND TDS ADDED HERE
</tbody>
</table>
In order to have all the children of one of your columns you can use the Element.children property. After you can iterate on this collection to get the value of each child and then compare each value to determine the maximum and the minimum value.
const myElement = document.getElementById('thead');
for (const column of myElement.children) {
var maximum = 0;
var maximumElement;
var minimum = 0;
var minimumElement;
for (const cell of column.children) {
if (cell.value > maximum)
maximumElement = cell;
if (cell.value < minimum)
minimumelement = cell;
}
maximumElement.style.backgroundcolor = 'green';
minimumElement.style.backgroundcolor = 'red';
}
I hope it's can help you

How to find the largest count of <td>'s in a tree having multiple tables-JS

I have multiple tables in a dOM tree and I want to calculate the count of cells in every table.
code:
function tree() {
var table = document.getElementsByTagName('table');
for (var p = 0, tr; tr= table[p]; p++) {
for (var i =0, row; row = tr.rows[i]; i++) {
console.log(row.cells.length)
}
}
}
console.log(tree())
html:
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
<tr>
<td>and</td>
<td>second</td>
</tr>
</table>
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
</table>
In the first there are 4 cells and second there are 2 cells I want to print out the cells with largest count in a table. Hence the o/p will be:
4
my above js code, returns the total length of all the cells in a table. How can I traverse through the tables in a tree and find the largest count of cells?
thx!
Use querySelectorAll() to simplify this.
The below code will output 4 as in your OP. It's a simple modification to get the table with the most cells, which I suspect is what you meant (it's unclear).
// Get your list of all tables in the document.
const tables = document.querySelectorAll('table');
// Map list of tables to list of number of <td> elements.
const lengths =
Array.from(tables)
.map(table => table.querySelectorAll('td').length)
// Get the max of the list of lengths and log to console.
const max = Math.max(...lengths);
console.log(max);
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
<tr>
<td>and</td>
<td>second</td>
</tr>
</table>
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
</table>
You can try this to if you want :
const maxTdTable = ()=>{
var object;
var maxCol = 0;
$('table').each(function(element){
$(element).each(function(elem){
max = $(elem).childNodes.length;
maxCol = max>=maxCol ? max : maxCol ;
});
});
return {element : object,max : maxCol};
}

td background colouring applied to complete column rather to a single cell

I've below html.
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
Below is the jquery I've written.
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')').text());
}
}); var idx2 = [];
for(var x=0;x<list2.length;x++){
if(list[x]===list2[x]){
//console.log(list[x]);
}else{
console.log('mismatched : '+list[x]);
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
idx2.push(x);
}
}
});
I'm trying to compare values in list with values in lqwasb02 column and if it finds the difference, it should highlight the background of td cell in red colour.
Current issue with jquery code, it is highlighting the complete column.
Can someone please help me where I'm getting wrong? If possible, please pass on the recommended solutions.
Many Thanks in advance.
The problem is that in your .find you are returning multiple elements that it's selector matches. So as opposed to storing the text value for your td elements in the second array, just store the actual td element, compare it's text, and then you can assign the background color directly to the element as opposed to finding it again via it's index:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')')); // <-- Store the object here, not it's text value.
}
});
var idx2 = [];
for(var x=0; x < list2.length; x++){
if(list[x]===list2[x].text()) { // <-- compare list[x] to the text value of list2[x]
//console.log(list[x]);
} else {
list2[x].css("background-color", "red"); // <-- no find or selector needed, just apply it to the object you stored earlier.
};
idx2.push(x);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
this piece of code assign a background colour to each cell of index 'x' for each rows (each cells of index x of each table rows represent a column).
You have to select only the rows which contains the cells you want to colour.
Here is how i would have approached solving this issue:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
var colIndex = findColIndex('lqwasb02');
// Loop over table rows
$('tr').each(function(){
// Look up cell with specific index
var $cell = $(this).find('td').eq(colIndex);
// Check if the text of the cell is not present in the list and do smth
if ($.inArray($cell.text(), list) === -1) {
$cell.css('background', 'red')
}
});
});
// helper function to find the index of column by text in the header
function findColIndex (headerText) {
var $col = $('.myTable th:contains(' + headerText + ')');
return $('.myTable th').index($col);
}
https://jsbin.com/fafegi/1/edit?js,output

Filtering table rows upon Search

I am trying to filter the rows of a table to display the results of entered text in the search bar. The code below does the job but for some reason filters the column headings as well.
$('#search').keyup(function () {
var data = this.value.split(" ");
var rows = $(".Info").find("tr").hide();
if(this.value ==""){
rows.show();
return;
}
rows.hide();
rows.filter(function(i,v){
var t = $(this);
for (var d = 0; d < data.length; d++) {
if (t.is(":Contains('" + data[d] + "')")) {
return true;
}
}
return false;
}).show();
});
HTML
<input type = "search" name = "search" id = "search">
<table style ="width:95%" class = "Info">
<tr>
<th>Select </th>
<th>Name</th>
<th>Number</th>
<th>Date</th>
</tr>
</table>
The user adds rows which is why i haven't written any HTML for it.
Any help would be appreciated. Thanks in advance
http://jsfiddle.net/szjhngwm/
It looks like you need to filter using tbody
<table style ="width:95%" class = "Info">
<thead>
<tr>
<th>Select </th>
<th>Name</th>
<th>Number</th>
<th>Date</th>
</tr>
<thead>
<tbody>
</tbody>
</table>
var rows = $(".Info tbody tr").hide();
Another way to do this would be to use jQuery's :gt() selector.
The only thing that would change is this line:
var rows = $(".Info").find("tr:gt(0)").hide();
Notice the addition of :gt(0) to your tr.

How to append a row in table using javascript

I want to append a new row in my table using Javascript but the new row should be like my previous rows.
I am using CSS to format my rows.
If you are using jQuery it will be something like this:
$(document).ready(function() {
$("table tr:last").clone().appendTo("table");
})
Replacing table with the id or class of your table (unless you only plan to have one table).
Using good old Node.cloneNode(deep) along with HTMLTableElement.rows:
HTML:
<table id="foo">
<tbody id="bar">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
JS:
var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var rows = foo.rows;
var lastRow = rows[rows.length-1];
var newRow = cloneRow(lastRow, true, bar);
function cloneRow(row, append, parent)
{
var newRow = row.cloneNode(true);
if(append)
{
if(parent)
{
parent.appendChild(newRow);
}
}
return newRow;
}
For comparison's sake, here's my code juxtaposed against the jQuery answer: http://jsperf.com/dom-methods-vs-jquery-with-tables
Let's say that your row has a css style of .row
So you could just use DOM methods to create a new tr, add the class="row" then add the appropriate amount of td
Here is a solution that avoids the use of the cloneNode method, and that do not copy the content, data or events of the previous last row, just its CSS attributes and class names.
The new row will have the same number of cell as the previous last row.
var lastRow = myTable.rows[myTable.rows.length-1];
var newRow = myTable.insertRow();
newRow.className = lastRow.className;
newRow.style.cssText = lastRow.style.cssText;
for (var i = 0; i < lastRow.cells.length; i++) {
var newCell = newRow.insertCell(i);
newCell.className = lastRow.cells[i].className;
newCell.style.cssText = lastRow.cells[i].style.cssText;
}

Categories

Resources