Run 2 functions inside a master function - javascript

I'm a beginner, sorry if my code might look a bit messy.
I'm trying to write a function to send an email to a specific email address whenever a cell in a column is equal to send_email. The email body needs to include data from the row with the cell equal to send_email.
This is my code:
function warnStatusBeginDay() {
// This function imports house data, every day, between 0am and 1am, and sends an email if the time left to answer the 'acta de observacion' is 3 or 7 days from the deadline
//Check when to send email
var checkValues = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('service_1_2_main').getRange('V2:AQ').getValues();
for (var i in checkValues) {
if (checkValues[i][4] === 'send_email') {
//Send email notification
function sendMail_7() {
// Build email body
var email_head = "https://i.imgur.com/aaa.jpg";
var house_id = checkValues[i][10];
var project = checkValues[i][7];
var name = checkValues[i][14];
var address = checkValues[i][19];
var neigh = checkValues[i][21];
var municipality = checkValues[i][17];
var country = checkValues[i][18];
var acta_date = Utilities.formatDate(checkValues[i][13],"GMT-0500","d MMM yyyy");
var acta_date_limit = Utilities.formatDate(checkValues[i][12],"GMT-0500","EEE, d MMM yyyy");
var record_id = checkValues[i][11];
var lat = checkValues[i][8];
var lng = checkValues[i][9];
var imageURL = checkValues[i][20];
var mapURL = "http://maps.googleapis.com/maps/api/staticmap?center="+lat+","+lng+"&zoom=15&size=300x300&maptype=hybrid&markers=color:red%7C"+lat+","+lng+"&key=myKey";
var mapURL2 = "https://www.google.com/maps/search/?api=1&query="+lat+","+lng;
var body = "<p>" +
"<p><img src='" + email_head + "' width='269' height='70' alt='Build Change - Sistema de notificación'></p>" +
"<i>[Este es un mensaje automatizado, por favor no responda a este correo]</i>" + "<br>" + "<br>" +
"La vivienda a continuación recibió una acta de observación el " + acta_date + ". El plazo limite para responder al acta vence en <b>7 días</b> desde hoy." + "<br>" + "<br>" +
"<b>Código ID vivienda: </b>" + house_id + "<br>" +
"<b>Proyecto: </b>" + project + "<br>" +
"<b>Nombre y apellido propietario: </b>" + name + "<br>" +
"<b>Fecha vencimiento acta de observación: </b>" + acta_date_limit + "<br>" + "<br>" +
"<b>Código ID Fulcrum: </b>" + record_id + "<br>" +
"<b>Latitud y longitud: </b>" + lat + ", " + lng + "<br>" +
"<b>Barrio/Comuna/Localidad/Sector: </b>" + neigh + "<br>" +
"<b>Dirección: </b>" + address + "<br>" +
"<b>Municipalidad: </b>" + municipality + "<br>" +
"<b>País: </b>" + country + "<br>" +
"<p><a href='https://web.fulcrumapp.com/records/" + record_id + "' title='Open in Fulcrum'><img src='" + mapURL + "'></a>" + " " + "<img src='" + imageURL + "' height='300 alt='Imagén fachada vivienda'></p>" +
"</p>";
// Send email
MailApp.sendEmail({
to: "myemail.dev#gmail.com",
subject: house_id + " - Acta de observación en vencimiento (7 días restantes)",
htmlBody: body
});
}
sendMail_7();
}
else {
continue;
}
}
SpreadsheetApp.flush();
for (var j in checkValues) {
if (checkValues[j][6] === 'send_email') {
//Send email notification
function sendMail_3() {
// Build email body
var email_head = "https://i.imgur.com/aaa.jpg";
var house_id = checkValues[j][10];
var project = checkValues[j][7];
var name = checkValues[j][14];
var address = checkValues[j][19];
var neigh = checkValues[j][21];
var municipality = checkValues[j][17];
var country = checkValues[j][18];
var acta_date = Utilities.formatDate(checkValues[j][13],"GMT-0500","d MMM yyyy");
var acta_date_limit = Utilities.formatDate(checkValues[j][12],"GMT-0500","EEE, d MMM yyyy");
var record_id = checkValues[j][11];
var lat = checkValues[j][8];
var lng = checkValues[j][9];
var imageURL = checkValues[j][20];
var mapURL = "http://maps.googleapis.com/maps/api/staticmap?center="+lat+","+lng+"&zoom=15&size=300x300&maptype=hybrid&markers=color:red%7C"+lat+","+lng+"&key=myKey";
var mapURL2 = "https://www.google.com/maps/search/?api=1&query="+lat+","+lng;
var body = "<p>" +
"<p><img src='" + email_head + "' width='269' height='70' alt='Build Change - Sistema de notificación'></p>" +
"<i>[Este es un mensaje automatizado, por favor no responda a este correo]</i>" + "<br>" + "<br>" +
"La vivienda a continuación recibió una acta de observación el " + acta_date + ". El plazo limite para responder al acta vence en <b>3 días</b> desde hoy." + "<br>" + "<br>" +
"<b>Código ID vivienda: </b>" + house_id + "<br>" +
"<b>Proyecto: </b>" + project + "<br>" +
"<b>Nombre y apellido propietario: </b>" + name + "<br>" +
"<b>Fecha vencimiento acta de observación: </b>" + acta_date_limit + "<br>" + "<br>" +
"<b>Código ID Fulcrum: </b>" + record_id + "<br>" +
"<b>Latitud y longitud: </b>" + lat + ", " + lng + "<br>" +
"<b>Barrio/Comuna/Localidad/Sector: </b>" + neigh + "<br>" +
"<b>Dirección: </b>" + address + "<br>" +
"<b>Municipalidad: </b>" + municipality + "<br>" +
"<b>País: </b>" + country + "<br>" +
"<p><a href='https://web.fulcrumapp.com/records/" + record_id + "' title='Open in Fulcrum'><img src='" + mapURL + "'></a>" + " " + "<img src='" + imageURL + "' height='300 alt='Imagén fachada vivienda'></p>" +
"</p>";
// Send email
MailApp.sendEmail({
to: "myemail.dev#gmail.com",
subject: house_id + " - Acta de observación en vencimiento (3 días restantes)",
htmlBody: body
});
}
sendMail_3();
}
else {
return;
}
}
}
Basically, I'm building an array through get.Values and then checking:
which row of the fifth column in the array is equal to send_email (checkValues[i][4] === 'send_email') and then send as many emails as the number of cells equal to send_email in the fifth column of the array, thanks to the function sendMail_7.
which row of the sevent column in the array is equal to send_email (checkValues[j][6] === 'send_email') and then send as many emails as the number of cells equal to send_email in the seventh column of the array, thanks to the function sendMail_3.
The function sendMail_7 works perfectly but I can't understand way the second part of the script, starting from for (var j in checkValues) {... is not working.
Actually the last curly bracket of the script is highlighted in red, so I think something is wrong but I don't know what.
I also tried to place the 2 functions to send emails, sendMail_7 and sendMail_3, outside of the main function warnStatusBeginDay. In this case the last curly bracket of the main function warnStatusBeginDay is green but in this way the variables defined in the email body (i.e. var name = checkValues[i][14] or var municipality = checkValues[i][17]) are not working.
I'm not sure if my explanation was clear but it's my first time with Google App Scripts/javascripts in general I'm a beginner in coding.
Any suggestion?
Thanks a lot,
Stefano

If your first j does not fulfill equation in (checkValues[j][6] === 'send_email') then you go out from the loop because of else{ return; }

Related

Get values from checkbox to calender

I'm new to this. And have a code. HTML form that has 4 Checkboxes
The result goes into a G-spreadsheet. From the Sheet I want the checked boxes values to polulate a Calendar event. Now it works but I get all the Checkboxes values in the calendar. Not only the ones that are checked.
function appendData(data){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Records");
Logger.log(data)
// Lägg till rad i spreadsheet
ws.appendRow([data.name, data.email, data.cuser, data.lastday, data.telenor, data.comment, data.company, data.costacc, data.laptop, data.ipad, data.printer, data.router]);
// Create data for event
var title = data.name + " börjar sin anställning på Roche"
var date = new Date(data.lastday)
var description = "<b>Mobil + Abonnemang:</b>\n" + data.telenor + "\n\n" +
"<b>Bolag:</b>\n" + data.company + "\n\n" +
"<b>Övrig utrustning:</b>\n" + data.laptop + ", " + data.ipad + ", " + data.printer + ", " + data.router
"<b>Kopiera rättigheter från:</b>\n" + data.cuser + "\n\n" +
"<b>Övriga kommentarer:</b>\n" +
data.comment

Can this be turned into a for loop?

I would like to clean this up with a For loop. What would be the most efficient way coding this out?
I'm creating a search form that looks through a database for the specific form criteria. The way I have it coded would only work for the 8 Fields. But it is possible for the search form to have more then 8. For now though, I'd like to be able to map the results and display in a results page.
This is what I tried. This did not work at all and probably make no sense to anyone lol.
var obj =data[0]
$.get("obj", {data: $('select["Fields.DisplayName" + Fields.DataValue]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
This works for getting the data and displaying it how I'd like.
var obj = data[0];
document.getElementById("test").innerHTML =
"<p>"+ obj.Fields[0].DisplayName + ": " + obj.Fields[0].DataValue + "</p>" +
"<p>" + obj.Fields[1].DisplayName + ": " + obj.Fields[1].DataValue + "</p>" +
"<p>"+ obj.Fields[2].DisplayName + ": " + obj.Fields[2].DataValue + "</p>" +
"<p>"+ obj.Fields[3].DisplayName + ": " + obj.Fields[3].DataValue + "</p>" +
"<p>" + obj.Fields[4].DisplayName + ": " + obj.Fields[4].DataValue + "</p>" +
"<p>" + obj.Fields[5].DisplayName + ": " + obj.Fields[5].DataValue + "</p>" +
"<p>"+ obj.Fields[6].DisplayName + ": " + obj.Fields[6].DataValue + "</p>" +
"<p>" + obj.Fields[7].DisplayName + ": " + obj.Fields[7].DataValue + "</p>"
;
The next problem is if there is more then 1 data object. Currently I have it set to loop through the first object, but when I remove that I get cannot read property of '0' undefined.
Sure.
var html = "";
obj.Fields.forEach(({DisplayName, DataValue}) => {
html += `<p>${DisplayName}: ${DataValue}</p>`;
});
document.getElementById("test").innerHtml = html;
Use Array.map() and join the results:
var fields = data[0].Fields ;
document.getElementById("test").innerHTML = fields
.map(function(field) {
return '<p>' + field.DisplayName + ': ' + field.DataValue + '</p>';
})
.join('\n');

Storing data from a select tag to a string using Javascript

I'm trying to take information out of a form controlled by a select statement and store it in a string. The plan is to send the information gathered from the user via email, which I used PHP to do. I have an idea how to do it (a while loop that's controlled by how many lines are in the list,) but I can't quite gather the information.
Here's the loop:
var empMessage = function(){
messageString = "";
var noEmp = $("#drpEmp option").length;
var i = 0;
$("#drpEmp").selector.index = i;
while (i < noEmp){
$("#drpEmp").index = i;
messageString = messageString +
"Name: " + firstName.val + " " + MI.val + " " + lastName.val + "<br/>" +
"Business: " + BusinessName.val + "<br/>" +
"Address: " + address.val + "<br/>" +
" " + city.val + ", " + state.val + " " + zip.val + "<br/>";
}
messageString = "<strong>Employee Information</strong><br/>" . messageString;
i++;
}
$("#stringHolder").val(messageString);
}
Here's the JS Fiddle:
https://jsfiddle.net/xptxz7by/3/
I know I probably really off. I know I have the loop working and the list is getting counted, but I can't seem to retrieve the information. I'm also thinking I'm approaching sending the information wrong and there's probably a better way of doing it, I just haven't figured out how.
The data you want is in the Employee object that you saved in each option's .data(), so you need to get that data and use the properties.
messageString = "<strong>Employee Information</strong><br/>";
$("drpEmp option:selected").each(function() {
var employee = $(this).data("employee");
messageString +=
"Name: " + employee.firstName + " " + employee.MI + " " + lastName + "<br/>" +
"Business: " + employee.BusinessName + "<br/>" +
"Address: " + employee.address + "<br/>" +
" " + employee.city + ", " + employee.state + " " + employee.zip + "<br/>";
});

retrieving last key in javascript localstorage

I am doing a uni assignment so please excuse the coplete lack of knowledge here. I have been tasked with creating a web based app for a "client" that requires me to open an invoice after they have completed all the details, so far I have the form working fine, i can save to localstorage without an issue and can even retrieve the information in the format that I want.
The issue is that if i have multiple "orders' than i can only retrieve the first string saved to localstorage and i cannot figure out how to make it display the newest/last one.
The key is an almost randomly generated number derived from the date as we had to assume a large quantity of orders. I have attached the code below so if anyone can help i would appreciate it. Also I cannot use Jquery or JSON or anything like that. We have been told we are not able to use these. Also i cannot use a server (php etc).
Thanks
Steve
<script>
var i = 0;
var itemKey = localStorage.key(i);
var values = localStorage.getItem(itemKey);
values = values.split(";");
var name = values[0];
var company = values[1];
var contactnumber = values[2];
var email = values[3];
var address1 = values[4];
var address2 = values[5];
var suburb = values[6]
var postcode = values[7];
var comments = values[8];
var bags = values[9];
var distance = values[10];
var hdelivery_fee = values[11];
var hprice = values[12];
var htotal_notax = values[13];
var hgst = values[14];
var htotal_tax = values[15];
var hordernumber = values[16];
document.write('Name: ' + name + '<br />');
document.write('Company: ' + company + '<br />');
document.write('Contact: ' + contactnumber + '<br />');
document.write('Email; ' + email + '<br />');
document.write('Address; ' + address1 + '<br />');
document.write('Address; ' + address2 + '<br />');
document.write('Suburb; ' + suburb + '<br />');
document.write('Postcode; ' + postcode + '<br />');
document.write('Comments; ' + comments + '<br />');
document.write('Number of Bags; ' + bags + '<br />');
document.write('Distance; ' + distance + '<br />');
document.write('Delivery Fee; $' + hdelivery_fee + '<br />');
document.write('Price of Bags; $' + hprice + '<br />');
document.write('Total Ex-GST; $' + htotal_notax + '<br />');
document.write('GST; $' + hgst + '<br />');
document.write('Total Inc GST; $' + htotal_tax + '<br />');
document.write('hordernumber; ' + hordernumber + '<br />');
</script>
To display the last value of an array you should use values[values.length-1].
This will guarantee you get the absolute last one.
simple put
var itemKey = localStorage.key(i);
var values = localStorage.getItem(itemKey); in a loop and increement i each time.
You can try something like this
var localStorageKeys = Object.keys(localStorage);
getOrder(localStoragesKeys[localStoragesKeys.length-1]);
function getOrder(itemKey) {
var values = localStorage.getItem(itemKey);
values = values.split(";");
var name = values[0];
var company = values[1];
var contactnumber = values[2];
var email = values[3];
var address1 = values[4];
var address2 = values[5];
var suburb = values[6]
var postcode = values[7];
var comments = values[8];
var bags = values[9];
var distance = values[10];
var hdelivery_fee = values[11];
var hprice = values[12];
var htotal_notax = values[13];
var hgst = values[14];
var htotal_tax = values[15];
var hordernumber = values[16];
document.write('Name: ' + name + '<br />');
document.write('Company: ' + company + '<br />');
document.write('Contact: ' + contactnumber + '<br />');
document.write('Email; ' + email + '<br />');
document.write('Address; ' + address1 + '<br />');
document.write('Address; ' + address2 + '<br />');
document.write('Suburb; ' + suburb + '<br />');
document.write('Postcode; ' + postcode + '<br />');
document.write('Comments; ' + comments + '<br />');
document.write('Number of Bags; ' + bags + '<br />');
document.write('Distance; ' + distance + '<br />');
document.write('Delivery Fee; $' + hdelivery_fee + '<br />');
document.write('Price of Bags; $' + hprice + '<br />');
document.write('Total Ex-GST; $' + htotal_notax + '<br />');
document.write('GST; $' + hgst + '<br />');
document.write('Total Inc GST; $' + htotal_tax + '<br />');
document.write('hordernumber; ' + hordernumber + '<br />');
}
If you must use localStorage and cannot use any client side database then I would save each entry with a key like new Date().getTime() with a known string in front of it, so that you have key-1368910344400.
When you need to retrieve the last entry then you could do:
var keys = Object.keys(localStorage);
keys = keys.map(function(key) {
// check if the current key matches match "key-"
// if that's the case create a new Date object with the ms obtained by a split
// return the Date
});
// sort keys and take the most recent
This is usually a bad choice but as I understand it you're limited with choices, so you have to stretch things a bit.
If you could use a browser that supports html5 and webdb then just throw localStorage away and go for that :D, here is an example: http://www.html5rocks.com/en/tutorials/webdatabase/todo/

JavaScript inserting images

Hi I'm trying to insert specific images on specific pages when each pages loads and i just cant seem to get it, my code looks like this
function display() {
coursetitle = (x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
coursecode = (x[i].getElementsByTagName("code")[0].childNodes[0].nodeValue);
enrolledyear = (x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
semester = (x[i].getElementsByTagName("semester")[0].childNodes[0].nodeValue);
labday = (x[i].getElementsByTagName("labday")[0].childNodes[0].nodeValue);
lectureday = (x[i].getElementsByTagName("lectureday")[0].childNodes[0].nodeValue);
description = (x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
graphic = (x[i].getElementsByTagName("graphic")[0].childNodes[0].nodeValue);
document.getElementById("show").innerHTML = "Title: " + coursetitle + "<br />Code: " +
+ coursecode + "<br />Year: " + enrolledyear + "<br />Semester:" + semester +
"<br />Lab Day:" + labday + "<br />Lecture Day:" + lectureday +
"<br />Course Description:<br/>" + description;
What should i do?
If graphic value has the image path
document.getElementById("show").innerHTML = "Title: " + coursetitle + "<br />Code: " +
+ coursecode + "<br />Year: " + enrolledyear + "<br />Semester:" + semester +
"<br />Lab Day:" + labday + "<br />Lecture Day:" + lectureday +
"<br />Course Description:<br/>" + description + "</br> <img src=\""+graphic +"\" /> ";

Categories

Resources