Support for muliple table ids through javascript method - javascript

I am using the following method to read header names in a table and put in excel. Could anyone let me know how to modify this to support multiple tables with header info and data.
i.e. how to modify to pass table id. "headers" is the id for "th" tag in code.
function write_headers_to_excel()
{
str="";
var myTableHead = document.getElementById('headers');
var rowCount = myTableHead.rows.length;
var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for(var i=0; i<rowCount; i++)
{
for(var j=0; j<colCount; j++)
{
str= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th") [j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
}
}

Your question is a bit vague, so I'm guessing at what you want. Assuming your current function works as is, you can just take out the hard-coding of the table's ID and pass it in as a parameter:
function write_headers_to_excel(tableID) {
var myTableHead = document.getElementById(tableID);
// rest of your function as is
}
Then call it once for each table, though that will create a new ExcelSheet for each table.
If the idea is for all of the tables to be added to the same ExcelSheet you can pass an array of table IDs to the function something like the following. I've kept the basic structure of your function but moved the variable declarations out of the loops (since that what JavaScript does behind the scenes anyway), deleted your ExcellApp variable since it wasn't used, and moved the getElementsByTagName call out of the inner loop.
write_headers_to_excel(["headers1","headers3","headers7","etc"]);
function write_headers_to_excel(tableIDs) {
var myTableHead,
rowCount,
cols,
t,
i,
j,
rowOffset = 1,
ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for (t=0; t < tableIDs.length; t++) {
myTableHead = document.getElementById(tableIDs[t]);
rowCount = myTableHead.rows.length;
for(i=0; i<rowCount; i++) {
cols = myTableHead.rows[i].getElementsByTagName("th");
for(j=0; j < cols.length; j++) {
ExcelSheet.ActiveSheet.Cells(i+rowOffset,j+1).Value = cols[j].innerHTML;
}
}
rowOffset += rowCount;
}
}
(No, I haven't tested it.)

You can get all tr elements by tag name
var rows = document.getElementsByTagName('tr');// get all rows of all tables
var table=0, TableRow=0;
for (i = 0; i < rows.length; i++) {
row = rows[i];
if (row.parentNode.tagName != 'THEAD' && row.parentNode.tagName != 'thead') {
table=table+1;
// do something here for headers
} else if (row.parentNode.tagName != 'TBODY' && row.parentNode.tagName != 'tbody')
{
TableRow=TableRow+1;
//do something here for rows
}
}

Related

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
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');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

How can add my javaScript total function with google spreadsheet, I'm not able select the range in one sheet where I need to get the result

I can add number in google spreadsheet with formula but I want to do it without formula, I can create total function with other editor and works fine but I cannot get it going with google spreadsheet.
function calculateSum(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheet=ss.getSheets()[0];
var cell=sheet.getRange("B22");
cell.setFormula("=sum(B17:B21)");
}
javaScript Code is Below:-
function addNumbers(a,b,c){
var sum=a+b+c;
return sum;
}
var result=addNumbers(2,3,4);
document.write(result);
I would do it like this:
function addRange() {
var myVals = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange("A1:A11").getValues();
var answer = 0;
for (var i = 0; i < myVals.length; i++) {
answer = answer + myVals[i][0];
}
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange("A12").getCell(1,1).setValue(answer);
}
To do multiple columns try this:
function addRange() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var cellValues = sheet.getRange("A1:C12").getValues(); // 2D array
var columnCount = cellValues[0].length;
var rowCount = cellValues.length;
var answer = 0;
for (var row = 0; row < rowCount; row++) {
for (var column = 0; column < columnCount; column++) {
answer = answer + cellValues[row][column];
}
}
sheet.getRange("D12").getCell(1, 1).setValue(answer);
}

JavaScript : Delete dynamically created table

I am new to web development and struggling with deleting a dynamically created table.
Below is the JavaScript function to create the table when user clicks a button.
function DrawTable(data){
var oTHead = myTable.createTHead();
var oTFoot = myTable.createTFoot();
var oCaption = myTable.createCaption();
var oRow, oCell;
var i, j;
var heading = new Array();
heading[0] = "AAA";
heading[1] = "BBB";
heading[2] = "CCC";
heading[3] = "DDD";
var tableData = data.split(':');
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++)
{
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
// Insert rows and cells into bodies.
for (i=0; i < tableData.length; i++)
{
var oBody = oTBody0;
oRow = oBody.insertRow(-1);
var splitData = tableData[i].split(',');
for (j=0; j < splitData.length; j++)
{
oCell = oRow.insertCell(-1);
oCell.innerHTML = splitData[j];
}
}
}
The above code works perfectly and draws the table when user clicks on the button.
If user clicks on the button again it will draw the table again.
i.e., it will draw another header and all the rows all over again.
At this point I want to delete the existing header and rows and draw it all new.
I tried many things to delete the existing table, but nothing works.
Is there a way I can make sure that the table is not duplicated again?
UPDATE
The HTML part is:
<table id="myTable">
<tbody ID="oTBody0"></tbody>
</table>
ANOTHER UPDATE
I tried below and it worked.
oTHead.innerHTML = "";
oTBody0.innerHTML = "";
jQuery offers a .empty() function that you can use
$("#myTable").empty();
Or with javascript you can just set the innerHTML to empty
document.getElementById("myTable").innerHTML = "";
Just execute this function before you start trying to add new content to the table.
//$("#myTable").empty();
document.getElementById("myTable").innerHTML = "";
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++) {
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
Since you're using jQuery, just do this: $('#containerIdThatYourTableSitsIn').html('');
That will clear the html of whatever element your table sits in. Then just reload it.
Edit
As the comments have mentioned, .empty() is another option.

My Javascript code not working properly

I am creating a simple function that increment number and bind with multiple Table as S.NO.. I don't understand what's wrong with my code.
function _IncrementNumber(id) {
var table = document.getElementById(id);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
table.rows[i + 1].cells[0].innerHTML = (i + 1);
}
}
$(document).ready(function () {
_IncrementNumber("FirstTable");
_IncrementNumber("SecondTable");
});
DEMO
Please guide me.
You are accessing i+1 instead of i.
In the last iteration -> you will go out of bounds.
function _IncrementNumber(id) {
var table = document.getElementById(id);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
table.rows[i].cells[0].innerHTML = (i + 1);
}
}
$(document).ready(function () {
_IncrementNumber("FirstTable");
_IncrementNumber("SecondTable");
});
You're trying to access a row that doesnt exist.
You should start with i=1 instead to skip the header row
for (var i = 1; i < rowCount; i++) {
table.rows[i].cells[0].innerHTML = (i);
}
the error at this line was the issue. Table rows starts from 0 index. so dont need to increment the rows index change to this table.rows[i].cells[0].innerHTML = (i + 1);

convert html table to json object (with text boxes in table cell)

i have table like this
there are textboxes in table cell
im trying to convert this table to json object using
var InvoiceData = {};
InvoiceData = $('#invoiceDetailTbl').tableToJSON();
but values in text boxes not added to json object
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=1; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
i have found the solution, i'll done it manually
var table = document.getElementById('invoiceDetailTbl');
var tableRowCount = $("#invoiceDetailTbl > tbody > tr").length;
for (var i = 1; i <= tableRowCount; i++) {
var obj = {
Inv_Date: table.rows.item(i).cells[0].innerText,
Bill_No: table.rows.item(i).cells[1].innerText,
Net_Amt: table.rows.item(i).cells[2].innerText,
Paid_Amt: table.rows.item(i).cells[3].innerText,
Pay_Dis: $(table.rows.item(i).cells[4]).find('input').val(),
Paying_Amt: $(table.rows.item(i).cells[5]).find('input').val(),
Balance: table.rows.item(i).cells[6].innerText,
};
InvoiceData.push(obj);
}

Categories

Resources