I'm not sure how to code GAS form buttons to fire a script with dynamic values.
In this scenario, the current sheet cell value is used to Look-Up rows in an adjoining sheet and to populate a result array.
A form then presents a list of buttons containing values from one column of the result array.
Pressing a form button should fire the script postLocationData, and update the current cell and adjoining cells in the row with result array values, and closes the form. At this point, pressing a form button does not seem to do anything. Much thanks in advance for your help :)
function lookUpLocationTest(){
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var sheetLocations = ss.getSheetByName('LU_Locations');
var arrayRecords = sheetLocations.getRange(2, 3, sheetLocations.getLastRow(), 2).getValues();
var matchingLocations=[];
for (var i=0;i<arrayRecords.length;i++) {
var result = arrayRecords[i][1].indexOf(cell.getValue())
if(result !== -1) {
matchingLocations.push(arrayRecords[i]);
}
}
if(matchingLocations.length === 0){
var result = ui.alert(
'Message:',
'No Matching Location Found.',
ui.ButtonSet.OK);
return 0;
}
Logger.log(' Process - ' + matchingLocations.length + ' Locations have been found.') ; //matchingLocations is a global
// Prep Form HTML with formatted matching Locations
var HTML= '<form><div>'
for(var i=0;i<matchingLocations.length;i++){
HTML += "<div><input type='button' value='" + matchingLocations[i][1]
+ "' onclick='google.script.run.withSuccessHandler(postLocationData).processForm(this.parentNode)'/></div>";
}
var htmlOutput = HtmlService.createHtmlOutput(HTML).setSandboxMode(HtmlService.SandboxMode.IFRAME);
var result = SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Matching Locations');
return 1;
}
function postLocationData(lookUpValue) {
var location = lookUpValuesInArray (matchingLocations, 1, lookUpValue); //matchingLocations is a global
var cell = currCell;
var latLongCol = 3;
cell.setValue(location[0][1]);
cell.getRowIndex();
var sheet = cell.getSheet();
sheet.getRange(cell.getRowIndex(), latLongCol).setValue(location[0][0]);
var temp =1;
}
The function "google.script.run" will be executed on the client side but it will call a function on the serverside (your .gs file). In this case the function you will call is "processForm()" where you are sending "this.parentNode" as parameter.
In you Apps script file (gs file) you should have a function called "processForm()" you didn't post it in the example.
After this function ends, if everything went well, the function "google.script.run" will execute the function that you defined in "withSuccessHandler()". In you example you used "postLocationData".
This function will receive as parameter the results returned from the execution of processForm().
As I mentioned before google.script.run is called on the client side, therefore the function that will be executed if everything went well (the one contained in withSuccessHandler), has to be also in the client side. This means it has to be part of the script contained in the HTML.
As the way you posted the code, I would change the onclick to:
onclick='google.script.run.withSuccessHandler(someJavascriptFunction).postLocationData(this.parentNode)
withSuccessHandler is optional, if you decided to use it, then you should create a html script tag in you HTML variable having that javascript function to show an alert or something that tells the user the result of clicking the button.
You can also create an html file in the appsscript project and call it like: HtmlService.createHtmlOutputFromFile('Index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
This way you can have a cleaner html file and the javascript asociated to it.
Hope this helps.
Related
I am a very novice coder and am trying to accomplish the following using a Google Form:
Rename file uploaded by user based on name defined by combination of form fields
Create a copy of the uploaded file to a specific folder in GDrive, based on answer to particular form question
So far, I have managed to get Part 1 working, but Part 2 doesn't seem to function properly (no error message, just no action). Anyone able to guide me where I'm going wrong?
function fileRename() {
var form = FormApp.getActiveForm()
// returns the total number of form submissions
var length=form.getResponses().length;
//retrieve fileID of document uploaded by user in Question 6 of the form (i.e. Index 5)
var id=form.getResponses()[length-1].getItemResponses()[5].getResponse();
//getResponses()[length-1] retrieves the last form response, accounting for the fact that the first index is zero and hte last length-1
//gets the form answers used to concatenate the file name
var fileUploadEntity=form.getResponses()[length-1].getItemResponses()[0].getResponse();
var fileUploadDate=form.getResponses()[length-1].getItemResponses()[3].getResponse();
var fileUploadType=form.getResponses()[length-1].getItemResponses()[1].getResponse();
//accesses the uploaded file
var file=DriveApp.getFileById(id);
var name = file.getName();
//changes the file name
var name = fileUploadEntity+'_'+fileUploadDate+'_'+fileUploadType
file.setName(name);
//creates a copy and saves it to the relevant regional shared drive depending on which array the entity belongs to, using its four-letter identifier
var APAC = ["WRAU", "WRNZ", "WRSG", "WRMY", "WRHK"];
var NORAM = ["WRCA", "WRCC", "WRCW", "WRUS"];
var MEA = ["WRKE", "WRUG", "WRSO", "WRSA", "WRRW", "WRTZ", "WRZW"];
var LATAM = ["WRMX"];
var EEA = ["WRBE", "WRUK"];
var folderAPAC = DriveApp.getFolderById('1IKIDSEEGHf802WaF4l4ntN9uiUO5jJpa');
var folderNORAM = DriveApp.getFolderById('1BitldN3Uw7453wxnnI1X5PUmbmTiQn5O');
var folderMEA = DriveApp.getFolderById('18tWR1C-mdO7moAtktOHJsvXjx_V0kdg0');
var folderLATAM = DriveApp.getFolderById('1cG0iPocn3KyXK8XgaxnZNWVU-HKJ97dX');
var folderEEA = DriveApp.getFolderById('1N8tB8AjMkR7gRarcwd4NYmry_wh0WVkY');
if (fileUploadEntity.indexOf(APAC)>-1) {
file.makeCopy(name, folderAPAC);
}
else if (fileUploadEntity.indexOf(NORAM)>-1) {
file.makeCopy(name, folderNORAM);
}
else if (fileUploadEntity.indexOf(LATAM)>-1) {
file.makeCopy(name, folderLATAM);
}
else if (fileUploadEntity.indexOf(MEA)>-1) {
file.makeCopy(name, folderMEA);
}
else if (fileUploadEntity.indexOf(EEA)>-1) {
file.makeCopy(name, folderEEA);
}
}
You code is using indexOf the wrong way.
Instead of
fileUploadEntity.indexOf(APAC)
try
APAC.indexOf(fileUploadEntity)
Do the same or the other places where indexOf is used
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
I have this function which works but it gets all responses.
function setEditUrl(ss, createDateColumn)
{
var formURL = 'https://docs.google.com/forms/d/101bMiRw9TQaGbdDc4U_tLAD0QzicqejM9qXOEwJPQKU/viewform';
var urlColumn = createDateColumn-2;
var data = ss.getDataRange().getValues();
var form = FormApp.openByUrl(formURL);
for(var i = 2; i < data.length; i++)
{
if(data[i][0] != '' && data[i][urlColumn-1] == '')
{
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if(formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
ss.getRange(i+1, urlColumn).setValue(editResponseUrl);
}//end of if
}//end of for
return;
}// This is the end of the setEditUrl function
As the spreadsheet gets larger I am concerned with performance lag so I want to streamline it and replace the function with one like the one below which just gets the editURL for the last response and only if the sheet cell is empty
function setGoogleFormURL(ss, lastRowInx, createDateColumn)
{
var urlColumn = createDateColumn-2;
if (ss.getRange(lastRowInx, urlColumn).getValue() == "") // so that subsequent edits to Google Form don't overwrite editResponseURL
{
var form = FormApp.openById('101bMiRw9TQaGbdDc4U_tLAD0QzicqejM9qXOEwJPQKU');
var formResponses = form.getResponses();
var lastResponseIndex = form.getResponses.length-1;
var lastResponse = formResponses[lastResponseIndex];
var editResponseUrl = lastResponse.getEditResponseUrl();
var createEditResponseUrl = ss.getRange(lastRowInx, urlColumn);
createEditResponseUrl.setValue(editResponseUrl);
}
else{} //do nothing
however this seems to break on the getEditResponseUrl. I am getting the following error TypeError: Cannot call method "getEditResponseUrl" of undefined. (line 100, file "Code").
I used #SandyGood 's answer to this post as a reference. I wonder though if her observation about the event trigger is why this is borking. This is the onFormSubmit function I am using to call this and other fucntions.
function onFormSubmit(e)
{
var ss = SpreadsheetApp.getActiveSheet();
var lastRowInx = ss.getLastRow(); // Get the row number of the last row with content
var createDateColumn = ss.getMaxColumns(); //CreateDateColumn is currently in AX (Column 50) which is the last/max column position
var createDate = setCreateDate(ss, lastRowInx, createDateColumn);
var trackingNumber = setTrackingNumber(ss, lastRowInx, createDateColumn);
//var editURL = setEditUrl(ss, createDateColumn);
var editResponseURL = setGoogleFormURL(ss, lastRowInx, createDateColumn);
}//This is the end of onFormSubmit
I also found a whole bunch of sources 234where they were looking use the URL to append to an email, were more complex than my use case, or were unanswered. I also found some solutions for getting the EditURL by binding the script to the form but since I want to store the value on the sheet it needs to be bound to the sheet rather than the form.
UPDATE:
Okay so I tried to bind my script to the form instead of the sheet which allowed me to see the URL but now I have the problem in reverse where the form can't find the spreadsheet methods like .getMaxColumns TypeError: Cannot find function getMaxColumns in object Spreadsheet. (line 40, file "Code") AND .getActiveRange Cannot find method getActiveRange(number). (line 48, file "Code").
Here is the code on the form side
function onFormSubmit(e)
{
var form = FormApp.getActiveForm();
var activeFormUrl = form.getEditUrl();
var ss = SpreadsheetApp.openById(form.getDestinationId());
var createDateColumn = ss.getMaxColumns(); //CreateDateColumn is currently in AY (Column 51) which is the last/max column position
var urlColumn = createDateColumn-1; //urlColumn is currently in AX (Column 50) Calculating using it's relative position to createDateColumn Position
Logger.log(activeFormUrl, createDateColumn, urlColumn);
var checkLog1 = Logger.getLog();
Logger.clear();
if (ss.getActiveRange(urlColumn).getValue() == "") // so that subsequent edits to Google Form don't overwrite editResponseURL
{
var editResponseURL = setGoogleFormEditUrl(ss, createDateColumn, activeFormUrl);
var createEditResponseUrl = ss.getActiveRange(urlColumn);
createEditResponseUrl.setValue(activeFormUrl);
}
else
{
if (ss.getActiveRange(urlColumn).getValue() != activeFormUrl)
{
Logger.log("Something went wrong - URL doesn't match")
Logger.log(ss.getActiveRange(urlColumn).getValue());
var checkLog2 = Logger.getLog();
}
else {}//do nothing
}
}//This is the end of the onFormSubmit function
So I am wondering how I can pass a variable between the form and the sheet. Can I somehow read the form log programmically from the sheet? Can I append the value to the form response array (This would mean a few other edits to the referenced columns but could work). Thoughts #Gerneio , #SandyGood , Anyone else?
UPDATE 2:
There seemed to be a conflict with using both the methods from the FormApp and the SpreadsheetApp within the same function.
The solution that worked for me was to modularize the spreadsheet functions out (except the getActiveSheet) and to leave the getEditResponseURL method within the onFormSubmit Function.
The code snippet can be found posted here.
I'd suggest trying to use the onFormSubmit(e) on the form side.
function onFormSubmit(e)
{
var form = e.source;
var response = e.response;
var sheet = SpreadsheetApp.openById(form.getDestinationId());
var editUrl = response.getEditResponseUrl();
Logger.log(editUrl); // check the logger to see what results you are getting now
// Then do whatever operations you need to do...
}
Update:
I'm not so sure why you are having so many problems with this, but I can tell you for sure that it can be done from either side, the Form or Spreadsheet. I just put together a working example with code written on the Spreadsheet side, none what-so-ever on the Form side. Check it out:
function onFormSubmit(e)
{
var rng = e.range;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fUrl = ss.getFormUrl();
var f = FormApp.openByUrl(fUrl);
var rs = f.getResponses();
var r = rs[rs.length - 1]; // Get last response made
var c = getCellRngByCol(rng, 'Edit Response URL');
c.setValue(r.getEditResponseUrl());
}
// Specific for a form submit trigger
// Pass e.range and the name of the column
// to return a single cell
function getCellRngByCol(rng, col)
{
var aRng = SpreadsheetApp.getActiveSheet().getDataRange();
var hRng = aRng.offset(0, 0, 1, aRng.getNumColumns()).getValues();
var colIndex = hRng[0].indexOf(col);
return SpreadsheetApp.getActiveSheet().getRange(rng.getRow(), colIndex + 1);
}
There were a few small hiccups that I ran into. Firstly, make sure to setup the trigger accordingly. I highly recommend setting up immediate notifications of failures. Secondly, even though the function will rely on the event that is passed, manually run the onFormSubmit(e) method at least once before submitting a form. It will check to see if your script needs any authorization and will request if needed. I'd also recommend that you open up a new form, link a fresh new spreadsheet, and test this code to make sure it works. Then mold the above code to fit your needs.
If you can't get it, then I'll share a working example.
There seemed to be a conflict with using both the methods from the FormApp and the SpreadsheetApp within the same function.
The solution that worked for me was to modularize the spreadsheet functions out (except the getActiveSheet) and to leave the getEditResponseURL method within the onFormSubmit Function.
The code snippet can be found posted here.
I'm getting an "undefined" error when I try to get the value from a cell in a spreadsheet. The thing is that if I execute the same command for a different cell I get the value in that cell. The only difference between those 2 cells is the way the value is produced.
The value in the cell that show correctly is produced directly from the Google Form associated with that spreadsheet. The value that doesn't show when called, is produced from a script I created in the Google Form.
Script for the Form (triggered on form submit):
// This code will set the edit form url as the value at cell "C2".
function assignEditUrls() {
var form = FormApp.getActiveForm();
var ss = SpreadsheetApp.openById("my-spreadsheet-id")
var sheet = ss.getSheets()[0];
var urlCol = 3; // column number where URL's should be populated; A = 1, B = 2 etc
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var resultUrl = formResponses[i].getEditResponseUrl();
sheet.getRange(2 + i, urlCol).setValue(resultUrl);
}
SpreadsheetApp.flush();
}
Table (changed to HTML)
<table>
<tr> <!-- Row 1 -->
<td>Timestamp</td> <!-- A1 -->
<td>Name</td> <!-- B1 -->
<td>Edit form URL</td> <!-- C1 -->
</tr>
<tr> <!-- Row 2 -->
<td>5/26/2015 14:04:09</td> <!-- A2: this value came from the form submittion-->
<td>Jones, Donna</td> <!-- B2: this value came from the form submittion-->
<td>https://docs.google.com/forms/d/1-FeW-mXh_8g/viewform?edit2=2_ABaOh9</td> <!-- C2: this value came from the the script in the form -->
</tr>
</table>
Script in Spreadsheet (Triggered on form submit)
function onFormSubmit(e) {
// This script will get the values from different cells in the spreadsheet
// and will send them into an email.
var name = e.range.getValues()[0][1]; // This will get the value from cell "B2".
var editFormURL = e.range.getValues()[0][2]; // This will get the value from cell "C2".
var email = 'my-email#university.edu';
var subject = "Here goes the email subject."
var message = 'This is the body of the email and includes'
+ 'the value from cell "B2" <b>'
+ name + '</b>. This value is retrieved correctly.'
+ '<br>But the value from cell "C2" <b>'+ editFormURL
+ '</b> show as "undefined".';
MailApp.sendEmail(email, subject, message, {htmlBody: message});
}
The email looks like this:
Sented by: my-email#university.edu
Subject: Here goes the email subject.
Body:
This is the body of the email and includes the value from cell "B2" Jones, Donna. This value is retrieved correctly.
But the value from cell "C2" undefined show as "undefined".
Question:
What am I doing wrong?
You've most likely got a race condition in play.
A user submits a form. This is our prime event.
Upon form submission, all triggers that are associated with the event are fired.
assignEditUrls() in the form script, and
onFormSubmit() in the spreadsheet script.
If you had other scripts set up for this event, they would also trigger. The complication here is that all those triggers are fired independently, more-or-less at the same time, but with no guaranteed order of execution. The spreadsheet trigger MIGHT run BEFORE the form trigger! So that's one problem.
Each trigger will receive the event information in the format specific to their definition. (See Event Objects.) Since C2 is not actually part of the form submission, it won't be in the event object received by the spreadsheet function. That's your second problem, but since you know the offset of the value relative to the form input, you can use range.offset() to get it.
An additional wrinkle has to do with the way that Documents and Spreadsheets are shared; each separate script invocation will receive its own copy of the Spreadsheet, which is synchronized with other copies... eventually. Changes made to the spreadsheet by one script will not be immediately visible to all other users. And that makes three problems.
What to do?
You could try to coordinate operations of the two related trigger functions. If they're in the same script, the Lock Service could help with this.
You could have just one trigger function to perform both operations.
Or you could make the spreadsheet function tolerant of any delays, by having it wait for C2 to be populated. This snippet would do that...
...
var editFormURL = null;
var loop = 0;
while (!editFormURL) {
editFormURL = e.range.offset(0,2).getValue(); // This will get the value from cell "C2".
if (!editFormURL) {
// Not ready yet, should we wait?
if (loop++ < 10) {
Utilities.sleep(2000); // sleep 2 seconds
}
else throw new Error( 'Gave up waiting.' );
}
}
// If the script gets here, then it has retrieved a value for editFormURL.
...
One bonus problem: since you're using getValues(), with the plural s, you are retrieving 2-dimensional arrays of information. You're not seeing a problem because when you treat those values like a string, the javascript interpreter coerces the array into the string you've wished for. But it is still a problem - if you want a single value, use getValue().
Get the correct row, then hard code the column with your URL:
var ss = SpreadsheetApp.openById("my-spreadsheet-id")
var sheet = ss.getSheets()[0];
var rowForLookup = e.range.getRow();
var columnOfUrl = 24; //Column X
var theUrl = sheet.getRange(rowForLookup, columnOfUrl).getValue();
So this code is what I finally got after implementing your recommendations. Thanks to Sandy Good and Mogsdad.
function onFormSubmit(e) {
Logger.log("Event Range: " + e.range.getA1Notation());
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var startRow = e.range.getRow();
var startCol = 1;
var numRows = 1;
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, startCol, numRows, numColumns);
var data = dataRange.getValues();
Logger.log("Data Range: " + dataRange.getA1Notation());
for (var i = 0; i < data.length; ++i) {
var column = data[i];
var name = column[4];
var editFormURL = null;
var loop = 0;
while (!editFormURL) {
editFormURL = column[23];
if (!editFormURL) {
// Not ready yet, should we wait?
if (loop++ < 10) {
Utilities.sleep(3000); // sleep 2 second
}
else throw new Error( 'Gave up waiting.' );
}
}
var email = 'my-email#university.edu';
var subject = "Subject here";
var message = 'Some text about ' + name + '.' +
'<br><br>Please view this link: ' +
+ editFormURL;
MailApp.sendEmail(email, subject, message, {htmlBody: message});
}
}
I have a working script that upon form submit, specific rows move from one sheet to another. One of the fields I'm pushing is a url.
On the second sheet, the link is listed and it is hyperlinked, but it's really ugly and I really want to format it so that it shows "Edit" with a hyperlink. I've tried a number of ways, but my knowledge is limited so all I get are errors. I'm hoping someone can point me in the right direction.
Here is my code. I'm very new at this so the script is not at all sophisticated. Any help/suggestions would be appreciated!
function copyAdHoc(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = SpreadsheetApp.setActiveSheet(ss.getSheetByName("Form Responses 1"));
var data = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
// Grab the Headers from master sheet
var headers = sh.getRange(1,1,1,sh.getLastColumn()).getValues();
var date = headers[0].indexOf('Effective Date');
var name = headers[0].indexOf('Employee Name');
var loc = headers[0].indexOf('Location');
var issue = headers[0].indexOf('Description/Question/Issue');
var add = headers[0].indexOf('Additional Information');
var change = headers[0].indexOf('Is this a Qualifying Life Event?');
var url = headers[0].indexOf('Form URL');
var category = headers[0].indexOf('Primary Category');
var status = headers[0].indexOf('Current Status');
var users = headers[0].indexOf('Users');
// Grab only the relevant columns
for(n = 0; n < data.length; ++n ) { // iterate in the array, row by row
if (data[n][change] !== "Yes" & data[n][category] !== "Employee Relations" & data[n][date] !== "") { // if condition is true copy the whole row to target
var arr = [];
arr.push(data[n][url]);
arr.push(data[n][users]);
arr.push(data[n][date]);
arr.push(data[n][loc]);
arr.push(data[n][name]);
arr.push(data[n][category]);
arr.push(data[n][issue] + ". " + data[n][add]);
arr.push(data[n][status]);
var sh2 = SpreadsheetApp.setActiveSheet(ss.getSheetByName("Ad Hoc")); //second sheet of your spreadsheet
sh2.getRange(sh2.getLastRow()+1,2,1,arr.length).setValues([arr]); // paste the selected values in the 2cond sheet in one batch write
}
}
}
It's a bit messy but the only way I know to achieve what you're trying to do would be to insert a column to the left of the hyperlink with the word Edit right justified and then remove the borders between the two.
From your description I am assuming you want the word "Edit" to be Hyperlinked. To do so, try this:
function getHyperlink(url)
{
return "=HYPERLINK(\""+url+"\","+"\"Edit\""+")";
}
function mainFunct()
{
//Do necessary steps
var tarLink = "https://www.google.com";
var tarRng = tarSheet.getRange(rowNum, colNum).setValue(getHyperlink(tarLink));
//perform other steps
}
EDIT:
Forgot to mention, since you're pushing your values to the array... you can do it in a similar way by either just storing the hyperlink in a variable or directly pushing it to the array like all the other values. Or if you're dealing with a hyperlink that has a static and dynamic part, For example: https://stackoverflow.com/questions/post_id, where post_id keeps changing but most of the URL is static, you can easily handle it by just passing the post_id to the getHyperlink function and getting the required Hyperlink in return. Hope this helps.
I have one of the most frustuating problems i have ever had with a programming language.
Im reading some xml and then trying to display on the web page. i have no problem doing that.
Here is the code of how im accomplishing this.
// File: readXML.js
var shared = [];
var sheet = new Array()
// Start function when DOM has completely loaded
$(document).ready(function(){
var bigo = new Object();
console.log("can you see me.");
var sheetJoint = new Object();
// get the sheet xml file
$.get("sheet1.xml",{},function(xml){
var attrs = [];
// this is a loop within a loop. we traverse the values in the xml to get end up with a key pair value of key: val
// in our case this works out to be A1 = 0 this is the first step to get the actual value from the sharedstring.xml
// Run the function for each row tag in the XML file
$(xml).find("row").each(function(i) {
//run the function for each c tag in the xml and get the attribute.
//this is the attribute that references the actual column.
$(this).find("c").each(function(i){
$('c',xml).each(function(i) {
v1 = $(this).attr("r");
bigo[v1] =v1;
bigo[v1]= $(this).find("v").text();
});
})});
//get the shared string elements to combine with the other
$.get("sharedStrings.xml",{},function(xml){
$('si',xml).each(function(i) {
shared.push($(this).find("t").text());
})});
});
combineObjects(bigo);//combine the the array and the object.
});
since i have two read two different xml files i have to use another function to combine them. Here is that function.
function combineObjects(obj){
myHTMLOutput = '';
myHTMLOutput += '<table width="98%" border="1" cellpadding="0" cellspacing="0">';
myHTMLOutput += '<th>A</th>';
//mydiv=document.getElementById("ContentArea")
try{
var strt="";
var tempVal;
//loop throught the obejct and get the value from the returnTheValueSegment.
for (var ind in obj){
//if you want to print something to the log then just add this.
// pretty handy when trying to discover variable values. does not see to work well inside for loops thought.
// console.log("can you see me.");
tempVal = returnTheValueOfSegment(obj[ind]);
//bring the values
obj[ind] = tempVal;
}
for (var ind in obj){
mydata = BuildStudentHTML(ind);
myHTMLOutput = myHTMLOutput + mydata;
}
myHTMLOutput += '</table>';
$("#ContentArea").append(myHTMLOutput);
}
catch(err){alert(err)};
}
my problem occurs when i'm creating the table. its basically hit or miss...
if i try it in firefox it work only if i use firebug and step through the code otherwise it doe s not show the table elements.
here is the code that is being called to make the table.
function BuildStudentHTML(column1){
// Build HTML string and return
output = '';
output += '<tr>';
output += '<td>'+ column1 +'</td>';
output += '</tr>';
return output;
}
what could i be doing wrong. do i need some sort of timer? is it that the loop is to fast and the page cant refresh. Please if someone can point me in the right direction i would be for ever grateful.
In your code, combineObjects(bigo); is called before the HTTP requests for the XML files can finish. $.get() starts a new HTTP request and then runs the success function when the request has finished loading. You could try putting combineObjects(bigo); in the success function for the last XML document, but that won't work because bigo will be undefined in that function. The solution is to create a function that creates a function. Put this before the $(document).ready() function:
function second_XML(bigo){
return function(xml){
$('si', xml).each(function (i) {
shared.push($(this).find("t").text());
});
combineObjects(bigo); //combine the the array and the object.
}
}
This allows you to pass the bigo variable to the function as an outer variable. Next, replace the code that loads the second XML document with this:
//get the shared string elements to combine with the other
$.get("sharedStrings.xml", {}, second_XML(bigo));
This will make the code wait until the second XML file has loaded before combining the two. For some reason, you already made your code wait for the first XML document to load before loading the second, so you don't have a problem there.