Trying to store a table and have it load after refresh? - javascript

I am taking information from a form, and storing it as an object into an array.
then I am stringifying that, and storing it into local storage.
grabbing it from local storage,
and attempting to have the row show up.
its a "to do list" web app.
I want it to save the tasks, so that they are there when i come back/refresh the page. but everytime I refresh the page, it just disappears. It looks like the information is still stored in the local storage after I refresh, though. so that isn't the issue. However, if I refresh, AND THEN add a new task, it wipes the storage so that only the new tasks in that session are added.
how can I get this to wear I can add a task, and then, save everything, and have everything STAY even after I refresh?
I tried calling the buildTable function at the top of my file, thinking it might build the table so its there for me when I load the page, but it isn't working.
Thanks!
var table = document.getElementById("tableBody");
var toDoArray = [];
buildTable();
function buildTable(){
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
for(i=0; i < toDoArray.length; i++){
addTaskToTable(parsedObject[i]);
}
}
function addTaskToTable(obj){
var row = table.insertRow(0);
var cellName = row.insertCell(0);
var cellDate = row.insertCell(1);
var cellId = row.insertCell(2);
var cellCheck = row.insertCell(3);
cellName.innerHTML= obj.name;
cellDate.innerHTML= obj.date;
var checkStuff = "<input type='checkbox'>";
cellCheck.innerHTML = checkStuff;
}
function submitForm(name,date) {
var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = getTaskObj(addTaskName,addTaskDate);
toDoArray.push(taskSomething);
addTaskToTable(taskSomething);
var storedArray = JSON.stringify(toDoArray);
localStorage.setItem("task",storedArray);
};
function getTaskObj(taskName,taskData){
var taskObject = {
name: taskName,
date: taskData,
};
return taskObject;
}

here i've fix your fillde to work >> https://jsfiddle.net/ptzkLqc4/1/
function buildTable() {
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
for (i = 0; i < parsedObject.length; i++) {
toDoArray.push(getTaskObj(parsedObject[i].name, parsedObject[i].date));
addTaskToTable(parsedObject[i]);
}
}
basicly, since you overwriting your localStorage by toDoArray values, you need to fill toDoArray with localStorage value on load.

Related

.length not working on array in Google Apps Script

I have this code. I want to loop through the array and create a new doc for each entry. If I manually set the loop length to the number of rows it works fine. I want to set it to loop for the length of the array. However the .length property always returns null. What am I missing. I have also tried for each loops with no luck.
function createDocument()
{
//var headers = Sheets.Spreadsheets.Values.get('fileID', 'A1:Z1');
var studentHistory = Sheets.Spreadsheets.Values.get('fileID', 'A2:Z200');
var templateId = 'fileID';
var documentId;
var dstFolder = DriveApp.getFolderById('folderID');
var length = studentHistory.length;
Logger.log(studentHistory);
Logger.log(length);
//Loop through rows in sheet
for (var i = 0; i < length; i++){
//Get values from sheet row
var date = studentHistory.values[i][0];
var studentName = studentHistory.values[i][1];
var dob = studentHistory.values[i][2];
var pcDoctor = studentHistory.values[i][3];
var address = studentHistory.values[i][4];
var fgName = studentHistory.values[i][5];
var mgName = studentHistory.values[i][6];
var phoneMom = studentHistory.values[i][7];
var phoneDad = studentHistory.values[i][8];
var empMom = studentHistory.values[i][9];
var empDad = studentHistory.values[i][10];
var livesWith = studentHistory.values[i][11];
var childrenInHome = studentHistory.values[i][12];
var childrenNotInHome = studentHistory.values[i][13];
var othersInHome = studentHistory.values[i][14];
var illnesses = studentHistory.values[i][15];
var illnessDetails = studentHistory.values[i][16];
var hospitalizations = studentHistory.values[i][17];
var hospDetails = studentHistory.values[i][18];
var trauma = studentHistory.values[i][19];
var traumaDetails = studentHistory.values[i][20];
var injuries = studentHistory.values[i][21];
var injuryDetails = studentHistory.values[i][22];
var medications = studentHistory.values[i][23];
var additionalComments = studentHistory.values[i][24];
var otherSchools = studentHistory.values[i][25];
//Make a copy of the template file
documentId = DriveApp.getFileById(templateId).makeCopy(dstFolder).getId();
//Change name of newly created document
DriveApp.getFileById(documentId).setName('SocialHistory_' + studentName + '_' + date);
var body = DocumentApp.openById(documentId).getBody();
//Insert values
body.replaceText('<<date>>', date);
body.replaceText('<<studentName>>', studentName);
body.replaceText('<<dob>>', dob);
body.replaceText('<<pcDoctor>>', pcDoctor);
body.replaceText('<<address>>', address);
body.replaceText('<<fgName>>', fgName);
body.replaceText('<<mgName>>', mgName);
body.replaceText('<<phoneMom>>', phoneMom);
body.replaceText('<<phoneDad>>', phoneDad);
body.replaceText('<<empMom>>', empMom);
body.replaceText('<<empDad>>', empDad);
body.replaceText('<<livesWithe>>', livesWith);
body.replaceText('<<childrenInHome>>', childrenInHome);
body.replaceText('<<childrenNotInHome>>', childrenNotInHome);
body.replaceText('<<othersInHome>>', othersInHome);
body.replaceText('<<illnesses>>', illnesses);
body.replaceText('<<illnessDetails>>', illnessDetails);
body.replaceText('<<hospitalizations>>', hospitalizations);
body.replaceText('<<hospDetails>>', hospDetails);
body.replaceText('<<trauma>>', trauma);
body.replaceText('<<traumaDetails>>', traumaDetails);
body.replaceText('<<injuries>>', injuries);
body.replaceText('<<injuryDetails>>', injuryDetails);
body.replaceText('<<medications>>', medications);
body.replaceText('<<additionalComments>>', additionalComments);
body.replaceText('<<otherSchools>>', otherSchools);
}
}
studentHistory.values is the array.
Therefore, try this instead to get the length:
var length = studentHistory.values.length;
Solution
I see you are using Advanced Google Services to call the Sheets API. This Apps Script class allows you to call the Google APIs directly from your script handling automatically the authorization process.
However it doesn't work as the built in Classes that are available for example inside the SpreadsheetApp wrapper.
Your request will return an HTTP-like response following these specifications:
{
"range": string,
"majorDimension": enum (Dimension),
"values": [
array
]
}
You will need to parse these responses in order to achieve the desired result.
Proposed modification
function createDocument()
{
//var headers = Sheets.Spreadsheets.Values.get('fileID', 'A1:Z1');
var studentHistory = Sheets.Spreadsheets.Values.get('fileID', 'A2:Z200');
var templateId = 'fileID';
var documentId;
var dstFolder = DriveApp.getFolderById('folderID');
var length = studentHistory.values.length;
...
Reference
Google Sheets API
Advanced Google Services

Adding rows to a table, looping an array, doing crazy things, readding first row each time

I feel like this is probably an issue with the loop somewhere, but I am a bit newer to coding and I am having trouble figuring out where exactly the issue is.
Every time I add a new task to the list, it prints the first task again. So if i add a second task, it inserts the first task and second task into the table, if i add a third task it inserts the first task and third task into the table.. its weird.
I looked in my local storage files, and its being stored properly. as in, (task one, task two, task three) no repetition there and its getting stored the way I want it to.
The issue is I am trying to do this:
I want to loop through the array, and have everything that is stored in local storage be posted on the table. (Currently, when I refresh it resets completely. its acting like session storage rather than local storage. it shows up in local storage after I refresh, but as soon as I click to add more after the refresh it disappears)
its a to do list, so I want it to basically show all items by looping through the array, and when I add a new item, have it store that and loop through the array again and post it on the table.
var table = document.getElementById("tableBody");
toDoArray = [];
function buildTable(){
addToStorage();
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
for(i=0; i < toDoArray.length; i++){
var row = table.insertRow(0);
var cellName = row.insertCell(0);
var cellDate = row.insertCell(1);
var cellId = row.insertCell(2);
var cellCheck = row.insertCell(3);
cellName.innerHTML= parsedObject[i].name;
cellDate.innerHTML= parsedObject[i].date;
var checkStuff = "<input type='checkbox'>";
cellCheck.innerHTML = checkStuff;
}
}
function submitForm(name,date) {
var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = getTaskObj(addTaskName,addTaskDate);
toDoArray.push(taskSomething);
buildTable();
};
function getTaskObj(taskName,taskData){
var taskObject = {
name: taskName,
date: taskData,
};
return taskObject;
}
function addToStorage(){
var storedArray = JSON.stringify(toDoArray);
localStorage.setItem("task",storedArray);}
When you are calling buildTable in submit form, its looping over the whole array again and adding the elements to table. Try this,
var table = document.getElementById("tableBody");
toDoArray = [];
function buildTable(){
addToStorage();
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
for(i=0; i < toDoArray.length; i++){
addTaskToTable(parsedObject[i]);
}
}
function addTaskToTable(obj){
var row = table.insertRow(0);
var cellName = row.insertCell(0);
var cellDate = row.insertCell(1);
var cellId = row.insertCell(2);
var cellCheck = row.insertCell(3);
cellName.innerHTML= obj.name;
cellDate.innerHTML= obj.date;
var checkStuff = "<input type='checkbox'>";
cellCheck.innerHTML = checkStuff;
}
function submitForm(name,date) {
var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = getTaskObj(addTaskName,addTaskDate);
toDoArray.push(taskSomething);
addTaskToTable(taskSomething);
};
function getTaskObj(taskName,taskData){
var taskObject = {
name: taskName,
date: taskData,
};
return taskObject;
}
function addToStorage(){
var storedArray = JSON.stringify(toDoArray);
localStorage.setItem("task",storedArray);
}
Here's the snippet with my comments.
var tasksStorageName = 'myTasks';
var tasksTable = document.getElementById("tasks_table");
var saveBtn = document.getElementById("save_task_btn");
var tasksList;
var storage = getStorage();
// this is dirty workaround, because localStorage disabled
// due to security reasons. feel free to remove this function
// and use localStorage directly
function getStorage() {
try {
return window.localStorage;
}
catch(e) {
return {
get: function(key) {
return JSON.stringify([
{
id: Date.now(),
name: 'first task',
date: '10/10/2016',
done: false
}
]);
},
set: function(key, object) {
}
};
}
}
function getTasksList() {
var dumpedTasks = storage.get(tasksStorageName);
// in case there are no tasks saved we return empty list
// otherwise parse our tasks.
return dumpedTasks == null ? [] : JSON.parse(dumpedTasks);
}
function dumpTaskList(tasksList) {
var dumpedTasks = JSON.stringify(tasksList);
storage.set(tasksStorageName, dumpedTasks);
}
// try to reuse things, so we have `renderTasks` function
// to render all our tasks to table which uses `renderTask`
// for each task. later we'll use it to add our newly created
// tasks.
function renderTasks(tasks) {
for (var index = 0; index < tasks.length; index++) {
var task = tasks[index];
renderTask(task);
}
}
// helper function to create checkbox
function createCheckboxForTask(task){
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = task.done;
return checkbox;
}
function renderTask(task) {
var taskRow = tasksTable.insertRow();
var doneCell = taskRow.insertCell();
var nameCell = taskRow.insertCell();
var dateCell = taskRow.insertCell();
taskRow.id = task.id;
doneCell.appendChild(createCheckboxForTask(task));
nameCell.innerText = task.name;
dateCell.innerText = task.date;
}
function createTask(name, date) {
return {
// quite naive id generation, don't use it in production
id: Date.now(),
name: name,
date: date,
done: false
}
}
// to restore your previously added tasks
// you need to get them from localStorage
// on load event and render them.
window.addEventListener('load', function(e) {
tasksList = getTasksList();
if (tasksList.length > 0) {
renderTasks(tasksList);
}
});
saveBtn.addEventListener('click', function() {
var name = document.getElementById("task_name").value;
var date = document.getElementById("task_date").value;
var newTask = createTask(name, date);
tasksList.push(newTask);
renderTask(newTask);
dumpTaskList(tasksList);
});
/*
// function does too many things
function buildTable(){
// if you try to call `buildTable` at page load then
// `addToStorage` function will set localStorage task item
// to empty array. thats why you lost your state every time
// you reload page
addToStorage();
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
// why this two unnecessary variables?
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
for(i=0; i < toDoArray.length; i++){
addTaskToTable(parsedObject[i]);
}
}
// try to give parametes as well as variables meaningful names
// like `task` this time, not `obj`
function addTaskToTable(obj){
var row = table.insertRow(0);
var cellName = row.insertCell(0);
var cellDate = row.insertCell(1);
var cellId = row.insertCell(2);
var cellCheck = row.insertCell(3);
cellName.innerHTML= obj.name;
cellDate.innerHTML= obj.date;
var checkStuff = "<input type='checkbox'>";
cellCheck.innerHTML = checkStuff;
}
function submitForm(name,date) {
var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = getTaskObj(addTaskName,addTaskDate);
toDoArray.push(taskSomething);
addTaskToTable(taskSomething);
};
// actually you are creating new task object, not getting it
// from somewhere, so it's better to name it like createTask
// or newTask
function getTaskObj(taskName,taskData){
var taskObject = {
name: taskName,
date: taskData,
};
return taskObject;
}
function addToStorage(){
var storedArray = JSON.stringify(toDoArray);
localStorage.setItem("task",storedArray);
}
*/
<div>
<label>Name: </label>
<input id="task_name" type="text"/>
</div>
<div>
<label>Date: </label>
<input id="task_date" type="text"/>
</div>
<button id="save_task_btn" type="button">Save</button>
<table id="tasks_table">
<thead>
<tr>
<th>Done</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
<table>

Use RegEx to replace tags in document with column data from spreadsheet

I've been searching for the answer to this question but have so far been unable to piece together the answer. Please explain any answer you have in really simple terms as I'm fairly new to GAS and RegEx. I've got most of the syntax down but the execution of it in GAS is giving me a hard time.
Basically, I want to write a script that, when the spreadsheet is edited, checks which rows have yet to be merged. Then, on those rows, creates a copy of a template Google Doc and names the document based on the spreadsheet data. From there (this is the hard part), I need it to replace merge tags in the template with the data from the spreadsheet.
The tags in the templates I'll be using look like this: <<mergeTag>>
My idea was to match the whole tag, and replace it with data from the spreadsheet that exists in the column with the same name as what's inside the "<<>>". Ex: <<FooBar>> would be replaced with the data from the column named FooBar. It would obviously be from the current row that needs the merging.
After that, all that's left is to send an email (a few more row-specific personalization) with that document attached (sometimes as a PDF) with the body of the message coming from an HTML file elsewhere in the project.
This is the whole thing I have so far (notice the placeholders here and there that I can personalize for each spreadsheet I use this for):
function onEdit() {
//SPREADSHEET GLOBAL VARIABLES
var ss = SpreadsheetApp.getActiveSpreadsheet();
//get only the merge sheet
var sheet = ss.getSheetByName("Merge Data");
//get all values for later reference
var range = sheet.getActiveRange();
var values = range.getValues();
var lastRow = range.getLastRow();
var lastColumn = range.getLastColumn();
//get merge checker ranges
var urlColumn = range.getLastColumn();
var checkColumn = (urlColumn - 1);
var checkRow = range.getLastRow();
var checkRange = sheet.getRange(2, checkColumn, checkRow);
var check = checkRange.getBackgrounds();
//get template determination range (unique to each project)
var tempConditionRange = sheet.getRange(row, column);
var tempConditionCheck = tempConditionRange.getValues();
//set color variables for status cell
var red = "#FF0000";
var yellow = "#FFCC00";
var green = "#33CC33";
//////////////////////////////////////////////////////////
//DOC GLOBAL VARIABLES
var docTemplate1 = DriveApp.getFileById(id);
var docTemplate2 = DriveApp.getFileById(id);
var docTemplate3 = DriveApp.getFileById(id);
var folderDestination = DriveApp.getFolderById(id);
//////////////////////////////////////////////////////////
//EMAIL GLOBAL VARIABLES
var emailTag = ss.getRangeByName("Merge Data!EmailTag");
var personalizers = "";
var subject = "" + personalizers;
var emailBody = HtmlService.createHtmlOutputFromFile("Email Template");
//////////////////////////////////////////////////////////
// MERGE CODE
for (i = 0; i < check.length; i++) {
//for rows with data, check if they have already been merged
if (check[i] == green) {
continue;
} else {
var statusCell = sheet.getRange((i+2), checkColumn, 1, 1);
var urlCell = sheet.getRange((i+2), urlColumn, 1, 1);
var dataRow = sheet.getRange((i+2), 1, lastRow, (lastColumn - 2))
statusCell.setBackground(red);
//for rows with data, but not yet merged, perform the merge code
//////////////////////////////////////////////////////////
//DOC CREATION
//Determine which template to use
if (tempConditionCheck[i] == "") {
var docToUse = docTemplate1;
}
if (tempConditionCheck[i] == "") {
var docToUse = docTemplate2;
}
if (tempConditionCheck[i] == "") {
var docToUse = docTemplate3;
}
//Create a copy of the template
//Rename the document using data from specific columns, at specific rows
//Move the doc to the correct folder
var docName = "";
var docCopy = docToUse.makeCopy(docName, folderDestination);
var docId = docCopy.getId();
var docURL = docCopy.getUrl();
var docToSend = DriveApp.getFileById(docId);
var docBody = DocumentApp.openById(docId).getBody();
Here's where I need the help
//Locate the Merge Tags
//Match Merge Tags to the column headers of the same name
//Replace the Merge Tags with the data from the matched column, from the correct row
function tagReplace() {
var tagMatch = "/(<{2}(\w+)>{2})/g";
}
statusCell.setBackground(yellow);
urlCell.setValue(docURL);
The rest is just finishing up the process
//////////////////////////////////////////////////////////
//EMAIL CREATION
//Create an email using an HTML template
//Use Merge Tags to personalize email
//Attach the doc we created to the email
//Send email to recipients based on data in the sheet
MailApp.sendEmail(emailTag, subject, emailBody, {
name: "Person McPerson",
attachments: [docToSend], //[docToSend.getAs(MIME.PDF)],
html: emailBody,
});
//////////////////////////////////////////////////////////
//CHECK ROW UPDATE
statusCell.setBackground(green);
}
}
}
My sheets all have a frozen first row that acts as the header row. All my columns will be consistently named the exact same thing as the tags (minus the <<>>).
How do I match the tags to the data?
EDIT
```````````````````
The solution did not work as described when I inserted it into my code as follows:
function formMerge() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Merge Data");
var urlColumn = sheet.getMaxColumns();
var checkColumn = urlColumn - 1;
var lastRow = ss.getSheetByName("Form Responses").getLastRow();
var values = sheet.getDataRange().getValues();
var headers = values[0];
var urlRange = sheet.getRange(2, urlColumn, lastRow);
var checkRange = sheet.getRange(2, checkColumn, lastRow);
var check = checkRange.getBackgrounds();
var red = "#ff0404";
var yellow = "#ffec0a";
var green = "#3bec3b";
var docTemplate = DriveApp.getFileById(id);
var folderDestination = DriveApp.getFolderById(id);
// MERGE CODE
for (i = 0; i < check.length; i++) {
if (check[i] == green) {
continue;
} else {
var statusCell = sheet.getRange((i+2), checkColumn, 1, 1);
var urlCell = sheet.getRange((i+2), urlColumn, 1, 1);
var dataRow = sheet.getRange((i+2), 1, 1, (urlColumn - 2)).getValues();
var clientNameRange = sheet.getRange((i+2), 3);
var clientName = clientNameRange.getValue();
var dateRange = sheet.getRange((i+2), 2);
var datePreFormat = dateRange.getValue();
var timeZone = CalendarApp.getTimeZone();
var date = Utilities.formatDate(new Date(datePreFormat), timeZone, "MM/dd/yyyy");
statusCell.setBackground(red);
//EMAIL VARIABLES
var personalizers = clientName;
var subject = "Post Intake Report for " + personalizers;
var emailBody = "Please see the attached Google Doc for the Post Intake Report for " + clientName + ". The intake was performed on " + date + ".";
var emailTagRange = sheet.getRange((i+2), 24);
var emailTagValue = emailTagRange.getValue();
var emailTag = emailTagValue.split(", ");
//DOC CREATION
var docToUse = docTemplate;
var docName = "Post Intake Report - " + clientName + " [" + date + "]";
var docCopy = docToUse.makeCopy(docName, folderDestination);
var docId = docCopy.getId();
var docURL = docCopy.getUrl();
var docBody = DocumentApp.openById(docId).getBody().editAsText();
for (var j=0; j<headers.length; j++) {
var re = new RegExp("(<<"+headers[j]+">>)","g");
docBody.replaceText(re, dataRow[j]);
}
statusCell.setBackground(yellow);
urlCell.setValue(docURL);
//EMAIL CREATION
MailApp.sendEmail(emailTag, subject, emailBody, {
name: "Christopher Anderson",
attachments: [docCopy],
html: emailBody
});
statusCell.setBackground(green);
}
}
}
Build the RegExp for each tag on the fly, using the header values from your spreadsheet.
Use Body.replaceText() to perform the replacements.
var values = sheet.getDataRange().getValues();
var headers = values[0];
...
// Loop over all columns. Use header names to search for tags.
for (var col=0; col<headers.length; col++) {
// Build RegExp using column header
var re = new RegExp("(<{2}"+headers[col]+">{2})","g");
// Replace tags with data from this column in dataRow
body.replaceText(re, dataRow[col]);
}
This snippet will operate on a single row; the first couple of declarations should appear outside of your row loop. The column looping is then done after you've created and opened the new document, and obtained the body object.
It loops over all the columns in the spreadsheet, using the header names to find the tags you've defined, and replaces them with the corresponding cell contents for the current row.

extract javascript variable from a function

this is my first post. Hope I've observed all the rules properly.
I'm a JS beginner and I've been watching tutorials on thenewboston.com and w3schools and some others on Youtube but can't find the answer to my question.
I have a form that uses JS to dynamically add input rows and that works fine. However the last part I just can't get to work. It is the bit that is supposed to collate all the data entered by the user.
This is what I have so far:
//get all the row data
function getData(TechRiskTable){
try {
var table = document.getElementById(TechRiskTable);
var rowCount = table.rows.length;
var jsonArray = new Array();
for(var index=0; index < rowCount; index++) {
var mapObj = {};
var row = table.rows[index];
var name1 = row.cells[0].childNodes[0];
var name2 = row.cells[1].childNodes[0];
var name3 = row.cells[2].childNodes[0];
var name4 = row.cells[3].childNodes[0];
var name5 = row.cells[4].childNodes[0];
mapObj['name1'] = name1.value;
mapObj['name2'] = name2.value;
mapObj['name3'] = name3.value;
mapObj['name4'] = name4.value;
mapObj['name5'] = name5.value;
// document.write("Value in jsonArray " + name1.value + "<br />");
}
}catch(e) {
alert(e);
}
}
Ok, so I'm running this on a classic ASP page and the "onclick" does this:
response.write input type=submit onclick='getData(TechRiskTable);' value='Send to Reviewer'><input type=reset value='Start Again'>
My question is this: How can I extract the values the user entered into the added rows in the table "TechRiskTable" so I can insert them into a database. I don't need help with getting it into the dbase, I can do that myself. I'm just having trouble extracting the actual values. That "document.write" bit does actually display the correct values on the page when I have it uncommented, but that is still within the function. I can't find a way to access the entered data from OUTSIDE the function. I've tried using request.querystring but that doesn't return any data either.
I assume that I need to get them out of jsonArray() but I can't find anywhere I can get this to work.
Any clarification required please let me know. I didn't include all the code as this post would then be too long but if you need more just ask.
Cheers
function getData(TechRiskTable){
try {
var table = document.getElementById(TechRiskTable);
var rowCount = table.rows.length;
var jsonArray = new Array();
for(var index=0; index < rowCount; index++) {
var mapObj = {};
var row = table.rows[index];
var name1 = row.cells[0].childNodes[0];
var name2 = row.cells[1].childNodes[0];
var name3 = row.cells[2].childNodes[0];
var name4 = row.cells[3].childNodes[0];
var name5 = row.cells[4].childNodes[0];
mapObj['name1'] = name1.value;
mapObj['name2'] = name2.value;
mapObj['name3'] = name3.value;
mapObj['name4'] = name4.value;
mapObj['name5'] = name5.value;
// document.write("Value in jsonArray " + name1.value + "<br />");
return mapObj;
}
}catch(e) {
alert(e);
}
return null;
I am assuming you are calling this method from somewhere else,
var mapObj = getData(TechRiskTable);
if(mapObj!=null)
{
alert("name1 is "+mapObj.name1+" and name2 is "+mapObj.name2);
}

Using YUI to read data from HTML table?

I generate an html table using YUI/JavaScript. I am now trying to go through and store the information that is generated by looking at each item in the table using a for loop.
var savedata = function(){
var tabledata = Y.one("#generatedtable")._node;
var jData = [];
for (var r in tabledata.rows){
var samplerow = {};
samplerow.timestamp = r.cells[0].innerHTML;
samplerow.volts = r.cells[1].innerHTML;
samplerow.amps = r.cells[2].innerHTML;
samplerow.kW = r.cells[3].innerHTML;
samplerow.kWh = r.cells[4].innerHTML;
samplerow.sessionid = r.cells[5].innerHTML;
jData.push(samplerow);
}
};
using Chrome developer tools I can see that Y.one("#generatedtable")._node.rows gives me an HTMLcollection of [X]. This signifies the number of rows that were created by my previous function. Row[0] is just headers and I want to skip over this row. The loop fails on the
samplerow.timestamp = r.cells[0].innerHTML;
line. How should I structure this for loop to go through rows[0] to [X] to store in my JSON Data variable?
var savedata = function(){
var tabledata = Y.one("#generatedtable")._node;
var jData = [];
var i = 1;
var length = tabledata.rows.length
while (i<length){
var samplerow = {};
var r = tabledata.rows[i];
samplerow.timestamp = r.cells[0].innerHTML;
samplerow.volts = r.cells[1].innerHTML;
samplerow.amps = r.cells[2].innerHTML;
samplerow.kW = r.cells[3].innerHTML;
samplerow.kWh = r.cells[4].innerHTML;
jData.push(samplerow);
i++;
}
alert(jData);
};

Categories