Implement counter in javascript - javascript

I will be printing two fields using for fields using for loop in javascript. First field is the name and second field is the link to download that file. This table will be generated dynamically. I want to keep a counter saying how many times a particular file is downloaded on the generated table.
for (i=0; i<resp.items.length; i++) {
var titulo = resp.items[i].title;
var fechaUpd = resp.items[i].modifiedDate;
var userUpd = resp.items[i].lastModifyingUserName;
var userEmbed = resp.items[i].embedLink;
var userAltLink = resp.items[i].alternateLink;
var download = resp.items[i].webContentLink;
var hold="Download";
var flag=0;
<!-- var fileInfo = document.createElement('li');
<!-- fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd +' url: ' + hold.link(download)));
<!-- document.getElementById('content').appendChild(fileInfo);
document.write(titulo + " ");
document.write(hold.link(download) + "<br>");
<!--flag=1;
}
<!--if(flag!=1){
<!--document.write("not found!");
<!--}
});

Related

How to make a table in in a html template with app scripts

I am trying to make a table inside my email template but I am not to sure what is going on, but it is not displaying as a table in the email template. Could someone help me convert this into a table? Information is showing up as line by line but not in a table. Would like some help please.
here is my code.
function sendEmail2(template) {
//setup function
var ActiveSheet = SpreadsheetApp.openById("1naSWINA8_uxeLUsj0lFntqILyDj2nirb56uvkBel79Y").getSheetByName("Sheet3");
var StartRow = 2;
var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
var WholeRange = ActiveSheet.getRange(StartRow,1,RowRange,11);
var AllValues = WholeRange.getValues();
var message = "";
//iterate loop
for (var i in AllValues) {
//set current row
var CurrentRow = AllValues[i];
//define column to check if sent
//var EmailSent = CurrentRow[12];
var check = CurrentRow[12];
if ( check == "sent"){
continue;
}
//set HTML template for information
message +=
"<p><b>Timestamp by: </b>" + CurrentRow[1] + "</p>" +
"<p><b>Requester Email: </b>" + CurrentRow[2] + "</p>" +
"<p><b>Star Rating: </b>" + CurrentRow[3] + "</p>" +
"<p><b>Request Category: </b>" + CurrentRow[4] + "</p>" +
"<p><b>Description: </b>" + CurrentRow[5] + "</p>" +
"<p><b>Label: </b>" + CurrentRow[6] + "</p>" +
"<p><b>Ticket ID: </b>" + CurrentRow[7] + "</p>" +
"<p><b>Comment: </b>" + CurrentRow[8] + "</p>" +
"<p><b>Status: </b>" + CurrentRow[9] + "</p><br><br>";
//set the row to look at
var setRow = parseInt(i) + StartRow;
//mark row as "sent"
//ActiveSheet.getRange(setRow, 13).setValue("sent");
}
var SendTo = "someone#gmail.com";
//set subject line
var Subject = "CT IT feedback";
var htmlBody = HtmlService.createTemplateFromFile(template);
var htmlContent = htmlBody.evaluate().getContent();
//send the actual email
MailApp.sendEmail({
to: SendTo,
cc: "",
subject: Subject,
htmlBody: htmlContent,
});
};
Try this:
function sendEmail2(template) {
var ss=SpreadsheetApp.openById("1naSWINA8_uxeLUsj0lFntqILyDj2nirb56uvkBel79Y");
var sh=ss.getSheetByName("Sheet3");
var rg=sh.getRange(StartRow,1,sh.getLastRow()-1,11);
var vA=rg.getValues();
var html= '<style>th,td{border: 1px solid black;}</style><table>';
for (var i=0;i<vA.length;i++) {
var row=vA[i];
if ( row[12]=="sent"){
continue;
}
html+=Utilities.formatString('<tr><td><strong>Timestamp by: </strong>%s</td><td>%s</td></tr>',row[1]);
html+=Utilities.formatString('<tr><td><strong>Requester Email: </strong>%s</td><td>%s</td></tr>',row[2]);
html+=Utilities.formatString('<tr><td><strong>Star Rating: </strong>%s</td><td>%s</td></tr>',row[3]);
html+=Utilities.formatString('<tr><td><strong>Request Category: </strong>%s</td><td>%s</td></tr>',row[4]);
html+=Utilities.formatString('<tr><td><strong>Description: </strong>%s</td><td>%s</td></tr>',row[5]);
html+=Utilities.formatString('<tr><td><strong>Label: </strong>%s</td><td>%s</td></tr>',row[6]);
html+=Utilities.formatString('<tr><td><strong>Ticket ID: </strong>%s</td><td>%s</td></tr>',row[7]);
html+=Utilities.formatString('<tr><td><strong>Comment: </strong>%s</td><td>%s</td></tr>',row[8]);
html+=Utilities.formatString('<tr><td><strong>Status: </strong>%s</td><td>%s</td></tr>',row[9]);
}
html+='</table>';
var SendTo = "someone#gmail.com";
var Subject = "CT IT feedback";
MailApp.sendEmail({to:SendTo,subject: Subject,htmlBody: html});
}

Google Script Time-Based Trigger -> Asking for Authorization all the time

So I have this google script function that reads information from a google spreadsheet and sends an email with the data. I set up a time-based trigger that activates every day at a certain hour but the problem is that every time it triggers the script ask for authorization so basically what I'm receiving is the email with this "time-based" error that asks for authorization.
The function self-works perfectly when I manually execute it and confirm the authorization myself.
I set up the time-based trigger via code and the trigger option of the scripts but none of them seems to work.
Do you guys know a way to always keep the authorization on so the trigger can work and send the email with the data?
so to add some additional information here, this is the code I'm using right now:
The spreadsheet is shared between two people, me and a co-worker.
If I manually execute this script, it will ask for authorization and then send to my email the data I need. My problem comes when I tried to set up a trigger to automatically execute this script. Every time the trigger execute the script I get an email saying that it needs authorization.
Function: emailCarts
Error Message: Authorization is required to perform this action. Activation: Time-Based
function emailCharts(sheet,emails,emailSubject){
var ss = SpreadsheetApp.openById("SPREADSHEET_ID");
var sheet = SpreadsheetApp.openById("SPREADSHEET_ID").getSheetByName("Graficos");
var emailSubject = 'Reporte Automático Reclamos y Sugerencias ' + Utilities.formatDate(sheet.getRange("B2").getValue(),ss.getSpreadsheetTimeZone(),"dd/MM/yy");
var emails = 'MY_EMAIL'; // your email ID
var charts = sheet.getCharts();
var sheet2 = SpreadsheetApp.openById("SPREADSHEET_ID").getSheetByName("Tabla");
var schedRange = sheet2.getDataRange();
var body = '<div style="text-align:left;display: inline-block;font-family:
arial,sans,sans-serif">'
body += '<H1>'+ 'Reclamos Abiertos ' +'</H1>';
body += getHtmlTable(schedRange);
body += '</div><br>';
debugger;
if(charts.length==0){
MailApp.sendEmail({to: emails,subject: "ERROR:"+emailSubject,htmlBody: "No hay
gráficos en el spreadsheet"});
return;
}
var chartBlobs = new Array(charts.length);
var emailBody = "Estimados,<br><br> Junto con saludar, se hace envío del reporte
automático de los Reclamos/Sugerencias/Felicitaciones Abiertos y Cerrados,
correspondiente a la fecha: "
+ Utilities.formatDate(sheet.getRange("B2").getValue(),ss.getSpreadsheetTimeZone(),"dd/MM/yy");
var emailImages = {};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i] = newchart.getAs('image/png');
emailBody = emailBody + "<p align='center'><img src='cid:chart"+i+"'></p>";
emailImages["chart"+i]= chartBlobs[i];
}
for (var i = 0; i < emails.length; i++){
MailApp.sendEmail({to: emails[i], subject: emailSubject, htmlBody: emailBody+body, inlineImages: emailImages});
}
}
function getHtmlTable(range){
var ss = range.getSheet().getParent();
var sheet = range.getSheet();
startRow = range.getRow();
startCol = range.getColumn();
lastRow = range.getLastRow();
lastCol = range.getLastColumn();
// Read table contents
var data = range.getValues();
// Get css style attributes from range
var fontColors = range.getFontColors();
var backgrounds = range.getBackgrounds();
var fontFamilies = range.getFontFamilies();
var fontSizes = range.getFontSizes();
var fontLines = range.getFontLines();
var fontWeights = range.getFontWeights();
var horizontalAlignments = range.getHorizontalAlignments();
var verticalAlignments = range.getVerticalAlignments();
// Get column widths in pixels
var colWidths = [];
for (var col=startCol; col<=lastCol; col++) {
colWidths.push(sheet.getColumnWidth(col));
}
// Get Row heights in pixels
var rowHeights = [];
for (var row=startRow; row<=lastRow; row++) {
rowHeights.push(sheet.getRowHeight(row));
}
// Future consideration...
var numberFormats = range.getNumberFormats();
// Build HTML Table, with inline styling for each cell
var tableFormat = 'style="border:1.5px solid black;border-collapse:collapse;text- align:center" border = 1.5 cellpadding = 5';
var html = ['<table '+tableFormat+'>'];
// Column widths appear outside of table rows
for (col=0;col<colWidths.length;col++) {
html.push('<col width="'+colWidths[col]+'">')
}
// Populate rows
for (row=0;row<data.length;row++) {
html.push('<tr height="'+rowHeights[row]+'">');
for (col=0;col<data[row].length;col++) {
// Get formatted data
var cellText = data[row][col];
if (cellText instanceof Date) {
cellText = Utilities.formatDate(
cellText,
ss.getSpreadsheetTimeZone(),
"dd/MM/yy");
}
var style = 'style="'
+ 'color: ' + fontColors[row][col]+'; '
+ 'font-family: ' + fontFamilies[row][col]+'; '
+ 'font-size: ' + fontSizes[row][col]+'; '
+ 'font-weight: ' + fontWeights[row][col]+'; '
+ 'background-color: ' + backgrounds[row][col]+'; '
+ 'text-align: ' + horizontalAlignments[row][col]+'; '
+ 'vertical-align: ' + verticalAlignments[row][col]+'; '
+'"';
html.push('<td ' + style + '>'
+cellText
+'</td>');
}
html.push('</tr>');
}
html.push('</table>');
return html.join('');
}

Removing new line under link in textarea

When I create a new link for my textarea it creates a new line like
[enter link description here][1] and [enter link description here][2]
[1]: http://
[2]: http://
As you can see above there is a gap between the bottom two links I don't want the gap there
It should look like
[enter link description here][1] and [enter link description here][2]
[1]: http://
[2]: http://
Question how to make it so when create new link that there are no gaps
for the bottom links.
Here is a codepen demo has been updated with working code
<script type="text/javascript">
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#title').val(selectedText);
$('#url').val('http://');
});
$('#save').on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($.trim($('#title').val()).length == 0){
var replace_word = '[enter link description here]' + '[' + counter + ']';
} else {
var replace_word = '[' + $(this).val() + ']' + '[' + counter + ']';
}
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end,len) + add_link;
});
function findAvailableNumber(textarea){
var number = 1;
var a = textarea.value;
if(a.indexOf('[1]') > -1){
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
}
return number;
}
</script>
I think your code at:
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
should instead be
if (counter == 1)
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#url').val();
else
var add_link = '\n' + ' [' + counter + ']: ' + $('#url').val();
so that there is no gap between links, except between the text and link. Since the links should be next to each other (see assumption below), only the first link should have a gap
ASSUMPTION: I'm assuming there shouldn't be any text after the links.

for in loop statement return undefined values

Need some help with this piece of a code. I am able to produce the results I want with the code in Working Code, but when I implement this code on another sheet (which is the master code) it does not work. scratching my head trying to figure this out
Here is the shared google spreadsheet with both full codes. Go to script editor.
Google Docs Link
Any help would be much appreciated. Thank you in advanced.
EDIT#3 Submit section of None Working Code
function submit(e){
var app = UiApp.getActiveApplication();
var sheet = SpreadsheetApp.openById(submissioSSKey).getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var projectname = e.parameter.projectname;
var projectid = e.parameter.projectid;
var projectmanager = e.parameter.projectmanager;
var salesrep = e.parameter.salesrep;
var duedate = e.parameter.duedate;
var projectphase = e.parameter.projectphase;
var disctype = e.parameter.disctype;
var mediatype = e.parameter.mediatype;
var encryptiontype = e.parameter.encryptiontype;
var password = e.parameter.password;
var quantity = e.parameter.quantity;
var specialinstructions = e.parameter.specialinstructions;
var update = "Colombo Save";
//var sheet = ss.getSheets()[0];
var uiData = [[
projectname,
projectid,
projectmanager,
salesrep,
duedate,
projectphase,
disctype,
mediatype,
encryptiontype,
password,
quantity,
specialinstructions,
update
]];
sheet.getRange(sheet.getLastRow()+1, 1, uiData.length, uiData[0].length)
.setValues(uiData);
var app = UiApp.getActiveApplication();
var result = {};
var numMembers = parseInt(e.parameter.table_tag);
result.members = [];
for(var i=1; i<=numMembers; i++){
var member = {};
member.firstName = e.parameter['fName'+i];
member.lastName = e.parameter['lName'+i];
member.company = e.parameter['company'+i];
member.address = e.parameter['address'+i];
result.members.push(member);
}
var htmlBody = 'Shipping Information: <br>'
for(var a in result.members) {
var member = result.members[a];
var fname = member.firstName;
var lname = member.lastName;
var company = member.company;
var address = member.address;
var timestamp = Utilities.formatDate(new Date(), "America/New_York", "MMMM dd, yyyy hh:mm:ss"); // Timestamp
var activeSessionuser = Session.getActiveUser();//Session.getEffectiveUser(); Get the current user in the spreadsheet
var emailAddress = 'test#email.com'; //Venue Colombo Team
var subject = "**Test Email** DVD Request Submitted - **Test Email**"+ projectname +" - "+projectid+" - "+ projectmanager;
/^var emailBody =*/
var emailBody =
"<br><font color=\"Blue\"><b><h2>Request Submitted</h2></b></font>"
+"<br/>Hi Venue Colombo Team,<br/>"
+"<br/>The following data room(s) will need a disc creation. Please begin bulk save data room and create ISO to upload to the FTP site:<br/>"
+"<br/><b>Project Name:</b> " + projectname
+"<br/><b>Project ID:</b> " + projectid
+"<br/><b>Project Manager:</b> " + projectmanager
+"<br/><b>Sales:</b> " + salesrep
+"<br/>" + htmlBody + 'Client Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Address: ' + address +'<br>'+'<br>'+
+"<br/>"
+"<br/><b>Phase:</b> " + projectphase
+"<br/><b>Disc Type:</b> " + disctype
+"<br/>"
+"<br/><b>Encryption:</b> " + encryptiontype
+"<br/><b>Password:</b> " + password
+"<br/><b>Quantity:</b> " + quantity
+"<br/>"
+"<br/><b>Client Due Date:</b> " + duedate
+"<br/>"
+"<br/><font color=\"Red\"><b>Special Instructions:</b></font> " + "<br/>"+ specialinstructions
+"<i><br/> <br/>This request was submitted by:</i> "
+"<br/><font color=\"blue\">Name:</font> " + activeSessionuser
+"<br/>Time Stamp: " + timestamp
+"<br/>"
+"———————————————————————————————"
+ //Line divider code —
"<br/>Venue Client Services"
+"<br/>United States: "
+"<br/>UK/International: "
+"<br/>France: "
+"<br/>Asia: ";
htmlBody += 'Client Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Address: ' + address +'<br>'+'<br>';
}
var optAdvancedArgs = {name: "Venue Client Services", htmlBody: emailBody};
//MailApp.sendEmail('fake#email.com', subject, '', optAdvancedArgs);
Logger.log(htmlBody);
Logger.log(emailBody);
var html = app.createHTML('First Name: '+ fname + ' ' + lname +'<br>'+ 'Company Name: '+ company +'<br>' + 'Client Address: ' + address);
app.add(html);
//dvdForm();
return app;
}
Here is the result on the Application
Here is the Logger logs
Logger.log(htmlBody);
Logger.log(emailBody);
I was finally able to figure out what the issues was with "for loop statement return undefined values"
I did not add a .addCallbackElement to the panel containing the form fields.

jquery Append add same value always

I use this jQuery code to append a div to another:
$('#sklep').on('click', '.kup', function () {
var cena = $('#cena').text();
var tytul = $('#tytul').text();
var iden = $('#id').text();
var suma = $('#koszykdiv .cyfry').text();
var dodawanie = parseInt(cena) + parseInt(suma);
$('.cyfry').text(dodawanie);
var source = $("#miniatura").attr("src");
$('.koszyk_content_items').append($('<div class="item_koszyk"><div class="miniatura_koszyk"><img width="165" height="110" src="' + source + '"/></div><span id="opis">' + tytul + ' - ' + cena + ' zł - </span><span class="identyfikator" style="display:none;">' + iden + '</span>USUŃ</div>'));
var licznik = $('#koszykdiv .licznik').text();
alert(licznik);
$('#identyfikator').text(licznik);
var licznik_dodawanie = parseInt(licznik) + 1;
$('#koszykdiv .licznik').text(licznik_dodawanie);
$.cookie("obraz" + licznik_dodawanie, id);
var cena = '';
var tytul = '';
var iden = '';
var source = '';
});
but it always appends a div with the same variables values, even if parent of '.kup' href has another text values. Can you help me and tell where the problem is?
You say in your question that you get the same variable values "even if parent of '.kup' href has another text values."
This is because nothing in your code is relative to the '.kup'-element. You get the src-attribute of the element with id=miniatura everytime.

Categories

Resources