I'm trying my hand at web development and one of my early projects is to create a grid that is mutable in size and responds to mouse events.
For some reason (I'm sure there is a good one), my function to change the grid size doesn't always remove all of the necessary rows.
Ex. When changing the grid size from 10 to 4, or 6 to 2, there are additional rows that are not removed
CODE PEN
HTML
<!DOCTYPE html>
<html>
<head>
<title>My Grid</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id='container'>
<div id='userSettings'>
<h1>Welcome to "My Grid"</h1>
<form>
<input id='gridSizeValue' type='text' name="gridSize">
<input id='button' type='button' value="Change Grid Size">
</form>
</div>
<table class='mainTable' style="border-color: black; border-top-width: 5px;">
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
<tr class="tableRow">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
<td class="tableColumn">
</tr>
</table>
</div>
JavaScript
$(document).ready(function(){
$('#button').click(function(){
var gridSize = document.getElementById('gridSizeValue').value;
var amountOfTableRows = document.getElementsByClassName('tableRow').length;
setTableRows(amountOfTableRows, gridSize);
});
styleTable();
});
function setTableRows(currentAmountOfRows, newGridSize) {
// Check if the number of rows is less than or greater than current amount of rows
// either add or subtract rows
// loop through rows and either add or subtract columns
if (newGridSize > currentAmountOfRows) {
var rowsToAdd = newGridSize - currentAmountOfRows;
for (var i = 0; i < rowsToAdd; i++) {
$('.mainTable').append("<tr class=\"tableRow\"></tr>");
}
newAmountOfRows = document.getElementsByClassName('tableRow');
for (var i = 0; i < newAmountOfRows.length; i++) {
currentAmountOfColumnsInRow = newAmountOfRows[i].getElementsByClassName('tableColumn').length;
columnsToAdd = newGridSize - currentAmountOfColumnsInRow;
// console.log("Need to add " + columnsToAdd + "columns");
for (var j = 0; j < columnsToAdd; j++) {
$('.tableRow:nth-child(' + (i+1) +')').append("<td class=\"tableColumn\">");
}
}
}
else if (newGridSize < currentAmountOfRows){
var rowsToSubtract = currentAmountOfRows - newGridSize;
for (var i = 0; i < rowsToSubtract; i++) {
$('.tableRow:nth-child(' + (i+1) +')').remove();
}
newAmountOfRows = document.getElementsByClassName('tableRow');
for (var i = 0; i < newAmountOfRows.length; i++) {
currentAmountOfColumnsInRow = newAmountOfRows[i].getElementsByClassName('tableColumn').length;
columnsToSubtract = currentAmountOfColumnsInRow - newGridSize;
// console.log("There are " + currentAmountOfColumnsInRow + " columns in row" + (i+1));
for (var j = 0; j < columnsToSubtract; j++) {
$('.tableColumn:nth-child(' + (i+1) +')').remove();
}
}
}
styleTable();
}
function styleTable(){
$('td').mouseenter(function(){
$(this).css("background-color","white");
});
$('td').mouseleave(function(){
$(this).css("background-color","black");
});
//Option 1: set height and width of each "cell" to the total height of table / cound of rows
// rowHeight = $('td').eq(0).height();
tableHeight = 400;
// alert("The Table Height is" + tableHeight);
numberOfRows = document.getElementsByClassName('tableRow').length;
// alert("rows " + numberOfRows);
dynamicCellHeight = (tableHeight / numberOfRows);
// alert("The Cell Height is " + dynamicCellHeight);
cellHeightInt= Number(dynamicCellHeight);
$('td').height(cellHeightInt);
$('td').width(cellHeightInt);
}
When you already have 6 rows and change the size 2, your code will call pass through the else statement, where you do :
for (var i = 0; i < rowsToSubtract; i++) {
$('.tableRow:nth-child(' + (i+1) +')').remove();
}
You are subtracting 4 rows, so actually the code is executing:
$('.tableRow:nth-child(1)').remove();
$('.tableRow:nth-child(2)').remove();
$('.tableRow:nth-child(3)').remove();
// at this point your table has 3 rows
$('.tableRow:nth-child(4)').remove();
So at the last line, you are trying to remove the fourth line of a table which has 3 rows ... so nothing happens.
You could invert the for loop looping backwards from rowsToSubtract to 0, that would solve your problem. But there are better ways to do this...
Just explaining why it's going wrong here :)
(Concurrent issue?)
for (var i = rowsToSubtract; i > 0; i--) {
$('.tableRow:nth-child(' + (i) +')').remove();
}
When rows are being subtracted from 8 to 2 (by 6), starting from removing 5th row, you can't do remove since it does not exist.
And yep, the code to remove columns for each row should also be fixed like aforementioned:
for (var j = columnsToSubtract; j > 0; j--) {
$('.tableColumn:nth-child(' + (i) +')').remove();
}
Thank you both very much for your help, it makes sense that what I was was trying to remove items that the code has no reference to and therefor does nothing.
I rewrote the code in a much simpler function to simply redraw the table in a much more concise way.
function drawNewTable(newGridSize){
$('.mainTable').remove();
// Draw New Grid -> Add Table -> Add Rows -> Add Column
$('.tableDiv').append("<table class='mainTable'>")
for(var i = 0; i < newGridSize; i++){
$('.mainTable').append("<tr class='tableRow'>");
for(var j = 0; j < newGridSize; j++){
$('.tableRow:nth-child(' + (i+1) +')').append("<td class=\"tableColumn\">");
}
$('.mainTable').append("</tr>");
}
$('.tableDiv').append("</table>");
styleTable();
}
Related
Yesterday I asked a question and, "with a little help from my friends" got my little javascript working.
This one:
<script type="text/javascript" >
function paint_cells() {
var tds = document.querySelectorAll('tbody td'), i;
for(i = 0; i < tds.length; i += 3) {
if(tds[i+1].textContent != tds[i+2].textContent){
tds[i+2].bgColor = "red";
}
}
}
paint_cells();
</script>
Now I would like to tweak this to cater for multiple correct answers. For example, both
'don't hurry' or 'do not hurry' are correct. In my MySQL table, they are stored as a string like this:
don't hurry|do not hurry
I want to split the string on | and then check if the student's answer is in the array (same as I do in PHP when marking the answers).
Not all answers have multiple correct answers. I hope that is not a problem for .split()??
I tried this, but I am not getting the result I want. Can you please help me tweak this to give me the result I want?
Edit: I thought maybe the apostrophes were causing the problem, so I escaped them. I trimmed each variable.
But I still don't get what I want! Any tips please?
<script type="text/javascript" >
function paint_cells() {
var tds = document.querySelectorAll('tbody td'), i;
for(i = 0; i < tds.length; i += 3) {
var arr = tds[i+1].textContent.split('|');
for(j = 0; j < arr.length; j++) {
arr[j].trim();
arr[j].replace(/'/g, "\'");
}
var myvar = tds[i+2].textContent;
myvar.trim();
myvar.replace(/'/g, "\'");
//console.log("Your line would be here")//Prints a line on the console
if(!arr.includes(myvar)){
//if(arr[0] != myvar){
alert('Array length: ' + arr.length + ' Answers: ' + tds[i+1].textContent + ' Student answer:' + myvar);
tds[i+2].bgColor = "red";
}
}
}
paint_cells();
</script>
Quotes don't matter. You have to reset the array to the trimmed value... trim returns the modified value, it doesn't "change in place".
var arr = answers.split('|');
for(var ii=0; ii<arr.length; ii++){
arr[ii] = arr[ii].trim().toLowerCase();
}
Here's a working example (run code snippet below):
function paint_cells() {
var tds = document.querySelectorAll('tbody td');
for (var i = 0; i < tds.length; i += 3) {
var cell_1 = tds[i + 1];
var cell_2 = tds[i + 2];
var answers = cell_1.textContent;
var arr = answers.split('|');
for (var ii = 0; ii < arr.length; ii++) {
arr[ii] = arr[ii].trim().toLowerCase();
}
var guess = (cell_2.textContent || "").trim().toLowerCase();
//console.log("Your line would be here")//Prints a line on the console
if (arr.indexOf(guess) < 0) {
console.log('Array length: ' + arr.length + ' Answers: ' + answers + ' Student answer:' + cell_2.textContent);
cell_2.style.backgroundColor = "red";
}
}
}
paint_cells()
<table>
<tbody>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>do not hurry</td>
</tr>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>don't hurry</td>
</tr>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>abc</td>
</tr>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>xyz</td>
</tr>
</tbody>
</table>
I have been trying to solve this for days.I would greatly appreciate any help you can give me in solving this problem. I have a table like the following:
ID Name Study
1111 Angela XRAY
2222 Bena Ultrasound
3333 Luis CT Scan
1111 Angela Ultrasound
3333 Luis XRAY
3333 Luis LASER
and I want to group them like:
ID Name Study
GROUP BY id(1111) 2 hits "+"
2222 Bena Ultrasound
GROUP BY id(3333) 3 hits "+"
AND if "+" is clicked then it will expand:
ID Name Study
GROUP BY id(1111) 2 hits "-"
1111 Angela XRAY
1111 Angela Ultrasound
2222 Bena Ultrasound
GROUP BY id(3333) 3 hits "-"
3333 Luis CT Scan
3333 Luis Ultrasound
3333 Luis LASER
There is a demo that I found on stackoverflow(http://jsfiddle.net/FNvsQ/1/) but the only problem I have is I want to include all rows having the same id under a dynamic header like
grouped by id(1111) then the expand/collapse icon (+/-)
var table = $('table')[0];
var rowGroups = {};
//loop through the rows excluding the first row (the header row)
while(table.rows.length > 0){
var row = table.rows[0];
var id = $(row.cells[0]).text();
if(!rowGroups[id]) rowGroups[id] = [];
if(rowGroups[id].length > 0){
row.className = 'subrow';
$(row).slideUp();
}
rowGroups[id].push(row);
table.deleteRow(0);
}
//loop through the row groups to build the new table content
for(var id in rowGroups){
var group = rowGroups[id];
for(var j = 0; j < group.length; j++){
var row = group[j];
if(group.length > 1 && j == 0) {
//add + button
var lastCell = row.cells[row.cells.length - 1];
$("<span class='collapsed'>").appendTo(lastCell).click(plusClick);
}
table.tBodies[0].appendChild(row);
}
}
//function handling button click
function plusClick(e){
var collapsed = $(this).hasClass('collapsed');
var fontSize = collapsed ? 14 : 0;
$(this).closest('tr').nextUntil(':not(.subrow)').slideToggle(400)
.css('font-size', fontSize);
$(this).toggleClass('collapsed');
}
Here is the answer to my own question.
First id's are added to the table and the rows and there's a small change to the JS:
var table = $('table')[0];
var rowGroups = {};
//loop through the rows excluding the first row (the header row)
while (table.rows.length > 1) {
var row = table.rows[1];
var id = $(row.cells[0]).text();
if (!rowGroups[id]) rowGroups[id] = [];
if (rowGroups[id].length > 0) {
row.className = 'subrow';
$(row).slideUp();
}
rowGroups[id].push(row);
table.deleteRow(1);
}
//loop through the row groups to build the new table content
for (var id in rowGroups) {
var group = rowGroups[id];
for (var j = 0; j < group.length; j++) {
var row = group[j];
var notSubrow = false;
if (group.length > 1 && j == 0) {
//add + button
var lastCell = row.cells[row.cells.length - 1];
var rowId = row.id;
var tableId = table.id;
notSubrow = true;
//$("<span class='collapsed'>").appendTo(lastCell).click(plusClick);
}
table.tBodies[0].appendChild(row);
if (notSubrow) {
$('#' + tableId).find('#' + rowId).attr('class', 'subrow');
$('#' + tableId).find('#' + rowId).before("<tr class='subrowHeader' style='background:#E6E6FA;border-bottom:1px solid #708AA0 !important'><td colspan='3'> group by " + $(row.cells[0]).text() + " (" + group.length + ")" + "<span class='collapsed' onclick='plusClick(this)' style='float:left;display:inline'></td></tr>");
$('#' + tableId).find('#' + rowId).hide();
}
}
}
//function handling button click
function plusClick(e) {
var collapsed = $(e).hasClass('collapsed');
var fontSize = collapsed ? 14 : 0;
$(e).closest('tr').nextUntil(':not(.subrow)').slideToggle('fast').css('font-size', fontSize);
$(e).toggleClass('collapsed');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
<tr id="tr1">
<th>Parent ID</th>
<th>Parent Name</th>
<th>Study</th>
</tr>
<tr id="tr2">
<td>1111</td>
<td>Angela</td>
<td>XRAY</td>
</tr>
<tr id="tr3">
<td>2222</td>
<td>Bena</td>
<td>Untrasound</td>
</tr>
<tr id="tr4">
<td>3333</td>
<td>Luis</td>
<td>CT Scan</td>
</tr>
<tr id="tr5">
<td>1111</td>
<td>Angela</td>
<td>Untrasound</td>
</tr>
<tr id="tr6">
<td>3333</td>
<td>Luis</td>
<td>LCD</td>
</tr>
<tr id="tr7">
<td>3333</td>
<td>Luis</td>
<td>LASER</td>
</tr>
</table>
*Inorder to test copy and paste the code into http://jsfiddle.net/FNvsQ/1/ &
In the Frameworks & Extensions panel, set onLoad to No wrap - in body.
As a comparison, here's a POJS function that is functionally equivalent in the same amount of code. Doesn't use a large external library though.
It uses the same algorithm of collecting all rows with the same value in the first cell, then modifies the table to insert header rows and group the data rows.
// Group table rows by first cell value. Assume first row is header row
function groupByFirst(table) {
// Add expand/collapse button
function addButton(cell) {
var button = cell.appendChild(document.createElement('button'));
button.className = 'toggleButton';
button.textContent = '+';
button.addEventListener('click', toggleHidden, false);
return button;
}
// Expand/collapse all rows below this one until next header reached
function toggleHidden(evt) {
var row = this.parentNode.parentNode.nextSibling;
while (row && !row.classList.contains('groupHeader')) {
row.classList.toggle('hiddenRow');
row = row.nextSibling;
}
}
// Use tBody to avoid Safari bug (appends rows to table outside tbody)
var tbody = table.tBodies[0];
// Get rows as an array, exclude first row
var rows = Array.from(tbody.rows).slice(1);
// Group rows in object using first cell value
var groups = rows.reduce(function(groups, row) {
var val = row.cells[0].textContent;
if (!groups[val]) groups[val] = [];
groups[val].push(row);
return groups;
}, Object.create(null));
// Put rows in table with extra header row for each group
Object.keys(groups).forEach(function(value, i) {
// Add header row
var row = tbody.insertRow();
row.className = 'groupHeader';
var cell = row.appendChild(document.createElement('td'));
cell.colSpan = groups[value][0].cells.length;
cell.appendChild(
document.createTextNode(
'Grouped by ' + table.rows[0].cells[0].textContent +
' (' + value + ') ' + groups[value].length + ' hits'
)
);
var button = addButton(cell);
// Put the group's rows in tbody after header
groups[value].forEach(function(row){tbody.appendChild(row)});
// Call listener to collapse group
button.click();
});
}
window.onload = function(){
groupByFirst(document.getElementById('table1'));
}
table {
border-collapse: collapse;
border-left: 1px solid #bbbbbb;
border-top: 1px solid #bbbbbb;
}
th, td {
border-right: 1px solid #bbbbbb;
border-bottom: 1px solid #bbbbbb;
}
.toggleButton {
float: right;
}
.hiddenRow {
display: none;
}
<table id="table1">
<tr id="tr1">
<th>Parent ID</th>
<th>Parent Name</th>
<th>Study</th>
</tr>
<tr id="tr2">
<td>1111</td>
<td>Angela</td>
<td>XRAY</td>
</tr>
<tr id="tr3">
<td>2222</td>
<td>Bena</td>
<td>Ultrasound</td>
</tr>
<tr id="tr4">
<td>3333</td>
<td>Luis</td>
<td>CT Scan</td>
</tr>
<tr id="tr5">
<td>1111</td>
<td>Angela</td>
<td>Ultrasound</td>
</tr>
<tr id="tr6">
<td>3333</td>
<td>Luis</td>
<td>LCD</td>
</tr>
<tr id="tr7">
<td>3333</td>
<td>Luis</td>
<td>LASER</td>
</tr>
</table>
I'm trying to get JavaScript to to change the color of a column and add a msg variable if it contains more than 2 div elements. My code is below and I know it's unfinished so hoping for some guidance.
I'm not using jQuery just browser JS.
HTML:
<table>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
<tr id="row">
<td id="columnA">
<div id="d1"></div>
</td>
<td id="columnB">
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
</td>
</tr>
</table>
Script:
<script>
function alertTooMany() {
var row = document.getElementById('row'), // Get Row
var col = row.getElementsByTagName('td'), // Get Columns in row
var div = col.getElementsByTagName('div'), // Get Div in columns
var num = divs.length; // count DIV tags
// prepare and display message
if (num < 2) { // If number of divs is less than 2
msg = "Column Open";
}
else if (num > 2){ // If number of divs is greater than 2
msg = "Warn: Column overfull!";
}
else { // If number of divs is 2
msg = "Column Full";
}
document.getElementById('message').innerHTML = msg;
}
</script>
Thanks in advance!
You didn't have any element with id message in your HTML. And you JavaScript code had some errors.
Demo on Fiddle
HTML:
<table>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
<tr id="row">
<td id="columnA">
<div id="d1">1</div>
</td>
<td id="columnB">
<div id="d1">1</div>
<div id="d2">2</div>
<div id="d3">3</div>
</td>
</tr>
</table>
<div id="message"></div>
JavaScript:
function alertTooMany() {
var row = document.getElementById('row'), // Get Row
col = row.getElementsByTagName('td'); // Get Columns in row
for (i = 0; i < col.length; i++) {
var div = col[i].getElementsByTagName('div');
var num = div.length;
if (num < 2) { // If number of divs is less than 2
msg = "Column Open";
} else if (num > 2) { // If number of divs is greater than 2
msg = "Warn: Column overfull!";
for (i = 0; i < div.length; i++) {
div[i].style.color = 'red';
}
} else { // If number of divs is 2
msg = "Column Full";
}
}
document.getElementById('message').innerHTML = msg;
}
alertTooMany();
<script>
function alertTooMany() {
var row = document.getElementById('row'); // Get Row
var cols = row.getElementsByTagName('td'); // Get Columns in row
// Iterating through columns
for (var i = 0; i < cols.length; i++) {
var col = cols[i];
var divs = col.getElementsByTagName('div'); // Get Div in column
var num = divs.length; // count DIV tags
// prepare and display message
if (num < 2) { // If number of divs is less than 2
msg = "Column Open";
}
else if (num > 2){ // If number of divs is greater than 2
msg = "Warn: Column overfull!";
// Finding header with same index as overfull column
var headers = document.querySelectorAll('th');
var matchingHeader = headers[i];
if (matchingHeader) {
matchingHeader.style['color'] = 'red';
}
col.style['color'] = 'red';
}
else { // If number of divs is 2
msg = "Column Full";
}
document.getElementById('message').innerHTML = msg;
}
}
alertTooMany();
</script>
HTML:
<table>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
<tr id="row">
<td id="columnA">
<div id="d1">01</div>
<span class="message"></span>
</td>
<td id="columnB">
<div id="d1">11</div>
<div id="d2">12</div>
<div id="d3">13</div>
<span class="message"></span>
</td>
</tr>
</table>
Script:
<script>
function alertTooMany() {
var row = document.getElementById('row'); // Get Row
var tds = row.getElementsByTagName('td'); // Get Columns in row
for (var i = 0; i < tds.length; i++) {
var divs = tds[i].getElementsByTagName('div'); // Get Div in columns
num = divs.length; // count DIV tags
// prepare and display message
if (num < 2) { // If number of divs is less than 2
msg = "Column Open";
tds[i].style.color="green";
} else if (num > 2){ // If number of divs is greater than 2
msg = "Warn: Column overfull!";
tds[i].style.color="red";
} else { // If number of divs is 2
msg = "Column Full";
}
document.getElementsByClassName("message")[i].innerHTML = msg;
}
}
</script>
My table format is
<table class"tabletop">
<tr>
<td>
<table>
<tr>
<td id="mycol1"></td>
<td id="mycol2"></td>
<td id="mycol3"></td>
<td id="mycol4"></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr>
</table>
I have to count columns(having id's) that are not disabled(or their display is not none) and that are disabled.
Suppose columns disabled are 4 and not disabled are 2.
So it must return disabled: 4 and not disabled: 2
td's are disabled by their id.
eg
mycol1.style.display="none";
Working Solution try this
<script type = "text/javascript" language = "javascript">
function getHiddenColumnCount() {
var tbl = document.getElementById("myTbl");
var HiddenColumnCount = 0;
for(var OuterCounter = 0 ; OuterCounter < tbl.rows.length ; OuterCounter++)
{
for(var InnerCounter = 0 ; InnerCounter < tbl.rows[OuterCounter].cells.length;InnerCounter++)
{
if (tbl.rows[OuterCounter].cells[InnerCounter].style.display == "none")
HiddenColumnCount++;
}
}
alert("There are " + HiddenColumnCount + " Hidden Columns in Table");
}
</script>
You can use
$('table td:visible').length
Try this: fiidle
<table border="1" id="myTbl">
<tr>
<td class="mycol1">
1
</td>
<td class="mycol2">
2
</td>
<td class="mycol3">
3
</td>
<td class="mycol4">
4
</td>
</tr>
</table>
<script>
function hideColumn(columnClass) {
var els = document.getElementsByClassName(columnClass);
for (var i = 0; i < els.length; i++) {
els[i].style.display = "none";
}
}
hideColumn('mycol1');
hideColumn('mycol2');
function getHiddenColumnsCount() {
var rows = document.getElementById('myTbl').rows;
var count = 0;
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < rows[i].cells.length; j++) {
if (rows[i].cells[j].style.display == "none")
count++;
}
}
alert(count);
}
getHiddenColumnsCount();
</script>
First of all you should use class for defining column instead of id as id should not be duplicate & to define a column we will have to give similar id to all cells of a column.
my HTML code looks like this
<TR Row="1" CLASS="ThemeAlignCenter">
<TD id="wrdActive_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD>
... more rows
I want to put a javascript at the end of the page to add all of the the values of lblactive_row1 when ever it appears in the page (in this example the number 6)
Edit: more source
<TABLE style="" border="0" CLASS="rdThemeDataTable" id="dtWardData"
cellspacing="0">
<COL id="wrdActive"></COL>
<COL id="wrdOccupied"></COL>
<TR Row="1" CLASS="ThemeAlignCenter">
<TD id="wrdActive_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">4</SPAN></TD>
<TD id="wrdOccupied_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblOccupied_Row1">4</SPAN></TD>
</TR>
</TABLE>
<TABLE style="" border="0" CLASS="rdThemeDataTable" id="dtWardData"
cellspacing="0">
<COL id="wrdActive"></COL>
<COL id="wrdOccupied"></COL>
<TD id="wrdActive_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD>
<TD id="wrdOccupied_Row1" style="width: 50px"
CLASS="rdThemeDataTableCell"><SPAN id="lblOccupied_Row1">2</SPAN></TD>
</TR>
</TABLE>
Repeat...
it goes on like that for another 10 or so tables, all in the same source. editting the html is out of the question because its generated by a third party tool. all i can is add a little script at the end
Depending on whether you're using jQuery or not, you might have to modify your HTML to make it easier to pick out the elements you need.
With jQuery you should be able to do something like this:
var total = 0;
$('table tr.ThemeAlignCenter > td.rdThemeDataTableCell > span').each(function(i) {
total += parseInt($(this).text());
});
Without jQuery, assuming your <table> has an id of data, something along these lines should help:
var tbl = document.getElementById('data');
var cells = tbl.getElementsByTagName('td');
var total = 0;
for (var i = 0, limit = cells.length; i < limit; i++) {
var td = cells[i];
if (td.className === 'rdThemeDataTableCell') {
var elem = td.getElementsByTagName('span')[0];
total += parseInt(elem.innerHTML);
}
}
EDIT: refactored the code so it can be applied to each table (should hopefully work if the table id attributes can't be amended and have to remain identical):
function sumTable(tbl) {
var cells = tbl.getElementsByTagName('td');
var total = 0;
for (var i = 0, limit = cells.length; i < limit; i++) {
var td = cells[i];
if (td.className === 'rdThemeDataTableCell') {
var elem = td.getElementsByTagName('span')[0];
total += parseInt(elem.innerHTML);
}
}
return total;
}
var tables = document.getElementsByTagName('table');
var results = [];
for (var i = 0, limit = tables.length; i < limit; i++) {
var total = sumTable(tables[i]);
results.push(total);
}
Something like this might work:
function totalRows() {
var total = 0;
var spans = document.getElementsByTagName('span');
for(var i=0; i<spans.length; i++) {
if(spans[i].getAttribute('id') === 'lblactive_Row1') {
total += parseInt( spans[i].innerHTML, 10);
}
}
return total;
}
attach totalRows() to an eventHandler