I have the following spreadsheet.
Spreadsheet
I need a script to count each agent email address (overall and based on client). I am struggling with arrays. I am new on scripting so still learning. So, on the Reports tab I need to know how many calls an agent made, then how many calls he made for Client 1, Client 2 and so on, how many appointments made - overall and for each client. I don't want to use =COUNTIFS() as this will be dynamic and in time there will be new agents.
I will make a script to get unique emails and paste it into a table and from there I need this script to count.
In the shared file I have my script, but I stuck there.
Thank you!
Build and Load Everything All At Once
I added a few more ranges to your reports sheet so that I could display all of the client data. The client names and agent emails have to be there because they are used as inputs in my data arrays and objects.
Here's the code:
function reportSummary()//This is final output
{
var br='<br />';
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var clientAgents=emailAddressAssociatedWithEachClient();
var agentClients=clientsAssociatedWithEachEmail();
var callsByAgent=callsMadeByAgentTotal();
var callsByAgentToClient=callsMadeByAgentToClient();
var apptsByAgent=apptsBookedByAgentTotal();
var apptsByAgentForClient=apptsBookedByAgentForClient();
var ss=SpreadsheetApp.getActive();
var rptSh=ss.getSheetByName('Reports');
var rgA=["A2:C6","A8:C12","A14:C18"];
for(var i=0;i<rgA.length;i++)
{
var rg1=rptSh.getRange(rgA[i]);
var vA1=rg1.getValues();
vA1[2][1]=callsByAgentToClient[vA1[2][0]][vA1[0][0]];
vA1[3][1]=callsByAgentToClient[vA1[3][0]][vA1[0][0]];
vA1[4][1]=callsByAgentToClient[vA1[4][0]][vA1[0][0]];
vA1[2][2]=apptsByAgentForClient[vA1[2][0]][vA1[0][0]];
vA1[3][2]=apptsByAgentForClient[vA1[3][0]][vA1[0][0]];
vA1[4][2]=apptsByAgentForClient[vA1[4][0]][vA1[0][0]];
rg1.setValues(vA1);
}
var rg2=rptSh.getRange('E2:H6');
var vA2=rg2.getValues();
vA2[2][1]=callsByAgent[vA2[2][0]];
vA2[3][1]=callsByAgent[vA2[3][0]];
vA2[4][1]=callsByAgent[vA2[4][0]];
vA2[2][2]=apptsByAgent[vA2[2][0]];
vA2[3][2]=apptsByAgent[vA2[3][0]];
vA2[4][2]=apptsByAgent[vA2[4][0]];
rg2.setValues(vA2);
/*
var s='<strong>Clients Contacted by Agent:</strong>';
for(var i=0;i<agentA.length;i++)
{
s+=br + '<span style="color:#ff0000">' + agentA[i] + '</span>';
for(var j=0;j<agentClients[agentA[i]].length;j++)
{
s+=br + agentClients[agentA[i]][j];
}
}
s+=br + br + '<strong>Agents who Contacted Client:</strong>';
for(var i=0;i<clientA.length;i++)
{
s+=br + '<span style="color:#ff0000">' + clientA[i] + '</span>';
for(var j=0;j<clientAgents[clientA[i]].length;j++)
{
s+=br + clientAgents[clientA[i]][j];
}
}
s+=br + br + '<strong>Calls made by Agents:</strong>';
for(var i=0;i<agentA.length;i++)
{
s+=br + Utilities.formatString('<br />%s = %s',agentA[i],callsByAgent[agentA[i]]);
}
s+=br + br + '<strong>Calls made by Agents to Client:</strong>';
for(var i=0;i<agentA.length;i++)
{
for(var j=0;j<clientA.length;j++)
{
s+=br + Utilities.formatString('<br />%s<br />%s<br />%s',agentA[i],clientA[j],callsByAgentToClient[agentA[i]][clientA[j]])
}
}
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Report Summary');
*/
}
function uniqueItemArray(column)
{
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName('Count');
var cntRg=cntSh.getDataRange();
var vA=cntRg.getValues();
var uiA=[];
for(var i=2;i<vA.length;i++)
{
if(uiA.indexOf(String(vA[i][column-1]).trim())==-1)
{
uiA.push(vA[i][column-1]);
}
}
return uiA;
}
function emailAddressAssociatedWithEachClient()
{
var agentEmailsA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName('Count');
var cntRg=cntSh.getDataRange();
var vA=cntRg.getValues();
var cEO=[];
for(var i=0;i<clientA.length;i++)
{
var ceA=[];
for(var j=2;j<vA.length;j++)
{
if(ceA.indexOf(String(vA[j][3]).trim())==-1 && String(vA[j][4]).trim()==clientA[i])
{
ceA.push(vA[j][3]);
}
}
cEO[clientA[i]]=ceA;
}
/*
for(var n=0;n<clientA.length;n++)
{
Logger.log(clientA[n] + '\n' + cEO[clientA[n]]);
}
*/
return cEO;
}
function clientsAssociatedWithEachEmail()
{
var agentEmailsA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName('Count');
var cntRg=cntSh.getDataRange();
var vA=cntRg.getValues();
var cEO=[];
for(var i=0;i<agentEmailsA.length;i++)
{
var ceA=[];
for(var j=2;j<vA.length;j++)
{
if(ceA.indexOf(String(vA[j][4]).trim())==-1 && String(vA[j][3]).trim()==agentEmailsA[i])
{
ceA.push(vA[j][4]);
}
}
cEO[agentEmailsA[i]]=ceA;
}
/*
for(var n=0;n<agentEmailsA.length;n++)
{
Logger.log(agentEmailsA[n] + '\n' + cEO[agentEmailsA[n]]);
}
*/
return cEO;
}
function callsMadeByAgentTotal()
{
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName('Count');
var cntRg=cntSh.getDataRange();
var vA=cntRg.getValues();
var callsByAgent=[];
for(var i=0;i<agentA.length;i++)
{
var cnt=0;
for(var j=2;j<vA.length;j++)
{
if(vA[j][3]==agentA[i])
{
cnt++;
}
}
callsByAgent[agentA[i]]=cnt;
}
/*
for(var i=0;i<agentA.length;i++)
{
Logger.log('\n%s\n%s',agentA[i],callsByAgent[agentA[i]]);
}
var s=Logger.getLog().replace(/^.+:/gm,'').replace(/\n/g,'<br />');
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Calls By Agent')
*/
return callsByAgent;
}
function callsMadeByAgentToClient()
{
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName('Count');
var cntRg=cntSh.getDataRange();
var vA=cntRg.getValues();
var callsByAgentToClient=[];
for(var i=0;i<agentA.length;i++)
{
callsByAgentToClient[agentA[i]]=[];
for(var k=0;k<clientA.length;k++)
{
var cnt=0;
for(var j=2;j<vA.length;j++)
{
if(vA[j][3]==agentA[i] && vA[j][4]==clientA[k])
{
cnt++;
}
}
callsByAgentToClient[agentA[i]][clientA[k]]=cnt;
}
}
/*
for(var i=0;i<agentA.length;i++)
{
for(var j=0;j<clientA.length;j++)
{
Logger.log('\n%s\n%s\n%s',agentA[i],clientA[j],callsByAgentToClient[agentA[i]][clientA[j]]);
}
}
var s=Logger.getLog().replace(/^.+:/gm,'').replace(/\n/g,'<br />');
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Calls By Agent To Client')
*/
return callsByAgentToClient;
}
function apptsBookedByAgentTotal()
{
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName('Count');
var cntRg=cntSh.getDataRange();
var vA=cntRg.getValues();
var apptsByAgent=[];
for(var i=0;i<agentA.length;i++)
{
var cnt=0;
for(var j=2;j<vA.length;j++)
{
if(vA[j][3]==agentA[i] && vA[j][5])
{
cnt++;
}
}
apptsByAgent[agentA[i]]=cnt;
}
/*
for(var i=0;i<agentA.length;i++)
{
Logger.log('\n%s\n%s',agentA[i],apptsByAgent[agentA[i]]);
}
var s=Logger.getLog().replace(/^.+:/gm,'').replace(/\n/g,'<br />');
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Calls By Agent')
*/
return apptsByAgent;
}
function apptsBookedByAgentForClient()
{
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var cntSh=ss.getSheetByName('Count');
var cntRg=cntSh.getDataRange();
var vA=cntRg.getValues();
var apptsByAgentForClient=[];
for(var i=0;i<agentA.length;i++)
{
apptsByAgentForClient[agentA[i]]=[];
for(var k=0;k<clientA.length;k++)
{
var cnt=0;
for(var j=2;j<vA.length;j++)
{
if(vA[j][3]==agentA[i] && vA[j][4]==clientA[k] && vA[j][5])
{
cnt++;
}
}
apptsByAgentForClient[agentA[i]][clientA[k]]=cnt;
}
}
/*
for(var i=0;i<agentA.length;i++)
{
for(var j=0;j<clientA.length;j++)
{
Logger.log('\n%s\n%s\n%s',agentA[i],clientA[j],apptsByAgentForClient[agentA[i]][clientA[j]]);
}
}
var s=Logger.getLog().replace(/^.+:/gm,'').replace(/\n/g,'<br />');
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Calls By Agent To Client')
*/
return apptsByAgentForClient;
}
And here's an image of my reports sheet:
Check Out reportSummaryNew() it creates a new sheet generates the report body and fills in all of the data. A separate function called buildReport() does the report building and returns an array of ranges for reportSummaryNew().
function buildReport()
{
var br='<br />';
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var sh=ss.insertSheet();
var shName=sh.getName();
sh.activate();
var rngA=[];
for(var i=0;i<=clientA.length;i++)
{
rngA[i]=sh.getRange(i*(agentA.length + 2) + 1,1,agentA.length + 2,3);
var vA=rngA[i].getValues();
if(i!=clientA.length)
{
vA[0][0]=clientA[i];
}
else
{
vA[0][0]='All';
}
vA[1][1]='Calls Made';
vA[1][2]='Appointments Booked';
for(var j=0;j<agentA.length;j++)
{
vA[j+2][0]=agentA[j];
}
rngA[i].setValues(vA);
}
return rngA;
}
function reportSummaryNew()
{
var br='<br />';
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var clientAgents=emailAddressAssociatedWithEachClient();
var agentClients=clientsAssociatedWithEachEmail();
var callsByAgent=callsMadeByAgentTotal();
var callsByAgentToClient=callsMadeByAgentToClient();
var apptsByAgent=apptsBookedByAgentTotal();
var apptsByAgentForClient=apptsBookedByAgentForClient();
var rngA=buildReport();
var ss=SpreadsheetApp.getActive();
var rptSh=ss.getActiveSheet();
for(var i=0;i<rngA.length-1;i++)
{
var rg1=rngA[i];
var vA1=rg1.getValues();
vA1[2][1]=callsByAgentToClient[vA1[2][0]][vA1[0][0]];
vA1[3][1]=callsByAgentToClient[vA1[3][0]][vA1[0][0]];
vA1[4][1]=callsByAgentToClient[vA1[4][0]][vA1[0][0]];
vA1[2][2]=apptsByAgentForClient[vA1[2][0]][vA1[0][0]];
vA1[3][2]=apptsByAgentForClient[vA1[3][0]][vA1[0][0]];
vA1[4][2]=apptsByAgentForClient[vA1[4][0]][vA1[0][0]];
rg1.setValues(vA1);
}
var rg2=rngA[rngA.length-1];
var vA2=rg2.getValues();
vA2[2][1]=callsByAgent[vA2[2][0]];
vA2[3][1]=callsByAgent[vA2[3][0]];
vA2[4][1]=callsByAgent[vA2[4][0]];
vA2[2][2]=apptsByAgent[vA2[2][0]];
vA2[3][2]=apptsByAgent[vA2[3][0]];
vA2[4][2]=apptsByAgent[vA2[4][0]];
rg2.setValues(vA2);
}
Here's what the new Generated Report Looks Like:
If you wish to be able to format the report you can run buildReport and take one of the sections and move it to the upper left corner A1:C5 and format it any way you like and then replace this line var rngA=buildReport() in reportSummaryNew() with this var rngA=buildReport1() yes just add a 1 between the 't' and '('. The buildReport1() function will copy the format from Format!A1:A5 so you can change the format easily any time you want just by formatting the contents of the sheet named 'Format';
Here's buildReport1()
function buildReport1()
{
var br='<br />';
var agentA=uniqueItemArray(4);
var clientA=uniqueItemArray(5);
var ss=SpreadsheetApp.getActive();
var trng=ss.getSheetByName('Format').getRange("A1:C5");
var sh=ss.insertSheet();
var shName=sh.getName();
sh.activate();
var rngA=[];
for(var i=0;i<=clientA.length;i++)
{
rngA[i]=sh.getRange(i*(agentA.length + 2) + 1,1,agentA.length + 2,3);
var vA=rngA[i].getValues();
trng.copyTo(rngA[i],{formatOnly:true});
if(i!=clientA.length)
{
vA[0][0]=clientA[i];
}
else
{
vA[0][0]='All';
}
vA[1][1]='Calls Made';
vA[1][2]='Appointments Booked';
for(var j=0;j<agentA.length;j++)
{
vA[j+2][0]=agentA[j];
}
rngA[i].setValues(vA);
}
return rngA;
}
And here's and image of how I formatted it.
Related
Test1 Sheet
Test2 Sheet
I want to compare News01 from Test1 A Column with Test2 A Column, and need to fetch the corresponding Test2 B column value
So the result should be Finance in Sheet1 B column
But If I use else, even when if statement is true it's going to else statement.
If I delete else statement, then if statement is working.
I don't know why when if statement is true, it's going to else statement by default
function test() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = sheet.getSheetByName("Test1");
var target_sheet = sheet.getSheetByName("Test2");
var lastRow = source_sheet.getLastRow();
var inputs = source_sheet.getRange('A' + lastRow).getValues().flat();
var days = target_sheet.getRange('A1:A').getValues().flat();
var codes = target_sheet.getRange('B1:B').getValues().flat();
inputs.forEach(function(input, count){
for(var i = 0; i < days.length; i++){
if(days[i].trim() == input.trim()){
source_sheet.getRange('B' + (count + source_sheet.getLastRow())).setValue(codes[i]);
Logger.log(codes[i]);
break;
}
else{
Logger.log("News not found")
}
}
});
}
You are logging News not found for each comparisons with all the rows of Test2, which is improper.
Instead, you should only log when the comparison is finished.
function test() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = sheet.getSheetByName("Test1");
var target_sheet = sheet.getSheetByName("Test2");
var lastRow = source_sheet.getLastRow();
var inputs = source_sheet.getRange('A' + lastRow).getValues().flat();
var days = target_sheet.getRange('A1:A').getValues().flat();
var codes = target_sheet.getRange('B1:B').getValues().flat();
inputs.forEach(function(input, count){
let found = false;
for(var i = 0; i < days.length; i++){
if(days[i].trim() == input.trim()){
source_sheet.getRange('B' + (count + source_sheet.getLastRow())).setValue(codes[i]);
Logger.log(codes[i]);
found = true;
break;
}
}
if (!found) { Logger.log("News not found"); }
});
}
Or simply,
function test() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = sheet.getSheetByName("Test1");
var target_sheet = sheet.getSheetByName("Test2");
var lastRow = source_sheet.getLastRow();
var inputs = source_sheet.getRange('A' + lastRow).getValues().flat();
var days = target_sheet.getRange('A1:A').getValues().flat();
var codes = target_sheet.getRange('B1:B').getValues().flat();
inputs.forEach(function(input, count){
for(var i = 0; i < days.length; i++){
if(days[i].trim() == input.trim()){
source_sheet.getRange('B' + (count + source_sheet.getLastRow())).setValue(codes[i]);
Logger.log(codes[i]);
return;
}
}
Logger.log("News not found");
});
}
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh1 = ss.getSheetByName("Sheet0");
var sh2 = ss.getSheetByName("Sheet1");
var lastRow = sh1.getLastRow();
var vs1 = sh1.getRange(1,1,sh1.getLastRow()).getValues().flat().map(e => e.trim());
var vs2 = sh2.getRange(1,1,sh2.getLastRow(),2).getValues();
vs2.forEach(r => {
if(~vs1.indexOf(r[0].trim())) {
Logger.log(r[1]);
}
});
}
Hello guys below is a link to my google sheet database please i want to implement a feature that will allow me pull data from google sheets to html table when they select a date range e.g( from 12/1/2019 to 12/7/2019) and a specific state(e.g California) will display only the records for california that fall into the date range please i will be grateful if i have the solution to this as it is a bottle neck for me to deliver on this project. Thanks[
code.gs
function getTableData(fac, dataaaa) {
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("data2");
var allSheetRowData=sheet.getDataRange().getValues();
var sheetHeaderData=allSheetRowData[0];
var dateColIndex = sheetHeaderData.indexOf("Date");
var stateColIndex = sheetHeaderData.indexOf("state");
var array=[];
var hey = fac.toString();
array.push(sheetHeaderData);
var dat = dataaaa.toString();
var rowData;
for(var i=1; i<allSheetRowData.length-1 ;i++){
if((allSheetRowData[i][dateColIndex]) == dat && allSheetRowData[i][stateColIndex]== hey){
rowData=allSheetRowData[i];
array.push(rowData);
Logger.log(rowData);
break;
}
}
return array;
}
function include (filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function extractAction () {
var stateVal = document.getElementById ('extractstate');
var datepic = document.getElementById ('extractdate').value;
if (stateVal[stateVal.selectedIndex].value == '') {
alerterror ('Please choose the state');
} else if (datepic == '') {
alerterror ('Please choose the Date');
} else {
var dataaaa = datepic.toString ();
var fac = stateVal.options[stateVal.selectedIndex].text;
alertsuccess ('You successfully pulled the data');
google.script.run
.withSuccessHandler (generateTable)
.getTableData (fac, dataaaa);
//generateTable();
}
}
function generateTable (dataArray) {
var newarray = TwoDimensional (dataArray, 2);
var newarray_2 = newarray.slice (1);
newarray_2.forEach (function (r) {
r.forEach (function (val, key) {
var arrayhead = newarray[0];
var count = 0;
console.log (r);
var tbody = document.getElementById ('tableID');
var row = tbody.insertRow (count++);
var cell1 = row.insertCell (0);
var cell2 = row.insertCell (1);
cell1.innerHTML = arrayhead[key];
cell2.innerHTML = val;
});
});
}
<table>
<tbody id="tableID">
</tbody>
</table>
html table like this
function getTableData(fac, data) {
if(fac && data) {
var sh=SpreadsheetApp.openByUrl(url).getSheetByName("data2");
var vA=sh.getDataRange().getValues();
var hA=vA[0];
var hObj={};
hA.forEach(function(e,i){hObj[e]=i;})
var array=[];
array.push(hA);
for(var i=1; i<vA.length-1 ;i++){
if((vA[i][hObj['date']])==data && vA[i][hObj['state']]==fac){
array.push(vA[i]);
}
}
return array;
}
}
You were using 'Date' for getting date header index but that doesn't agree with you image.
I would do it like this:
On the server side:
function getTableData(fac, data) {
if(fac && data) {
var sh=SpreadsheetApp.openByUrl(url).getSheetByName("data2");
var vA=sh.getDataRange().getValues();
var hA=vA[0];
var hObj={};
var html='<style>td,th{border:1px solid black}</style><table><tr>';
hA.forEach(function(e,i){hObj[e]=i;html+='<th>' + e + '</th>';});
html+='</tr>';
var array=[];
array.push(hA);
for(var i=1; i<vA.length-1 ;i++){
if((vA[i][hObj['date']])==data && vA[i][hObj['state']]==fac){
html+='<tr>';
vA[i].forEach(function(e,i){
html+='<td>' + e + '</td>';
})
html+='</tr>';
array.push(vA[i]);
}
}
html+='</table>';
return {array:array,html:html};
}
}
on the client side:
google.script.run
.withSuccessHandler (function(obj){
document.getElementById ('tableID').innerHTML=obj.html;
})
.getTableData (fac,dataaaa);
I am new to javascript or google apps script. I am using this function to import data into MySQL database from a google spreadsheet. This sheet has over 16000 records and I would want to breakdown the import into smaller batches of 2000 records. In the function createGASTrigger() how would I change my logic to grab first 2000 records from the spreadsheet in the first iteration and then the next 2000 records in second iteration and so on.
Function 1
var address = 'database_IP_address';
var rootPwd = 'root_password';
var user = 'user_name';
var userPwd = 'user_password';
var db = 'database_name';
var root = 'root';
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
function myFunction() {
var stime = new Date();
var col1;
var col2;
var col3;
var dbconnection = Jdbc.getConnection(dbUrl, root, rootPwd);
var statement = dbconnection.createStatement();
var googlesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');
var data = googlesheet.getDataRange().getValues();
dbconnection.setAutoCommit(false)
for (var i = 1; i < data.length; i++) {
col1 = data[i][0];
col2 = data[i][1];
col3 = data[i][2];
var sql = "{call [dbo].[sp_googlesheetimport](?,?,?)}";
statement = dbconnection.prepareCall(sql);
statement.setString(1, col1);
statement.setString(2, col2);
statement.setString(3, col3);
statement.addBatch();
}
statement.executeBatch();
dbconnection.commit();
statement.close();
dbconnection.close();
var etime = new Date();
Logger.log('Exec time: ' + (etime.getTime() - stime.getTime()));
}
Function 2
function createGASTrigger() {
var varUserPropertiesService = PropertiesService.getUserProperties();
var varUserTriggerId = varUserPropertiesService.getProperty("myFunction");
var varUserTrigger = ScriptApp.getProjectTriggers();
for (var i in varUserTrigger) {
if (varUserTrigger[i].getUniqueId() == varUserTriggerId)
try
{
ScriptApp.deleteTrigger(varUserTrigger[i]);
}
catch(e)
{
Utilities.sleep(30000);
ScriptApp.deleteTrigger(varUserTrigger[i]);
}
}
myFunction();
var userProperties = PropertiesService.getUserProperties();
try
{
var nextTrigger = ScriptApp.newTrigger("myFunction").timeBased().after(1 * 120 * 1000).create();
}
catch(e)
{
Utilities.sleep(30000);
var nextTrigger = ScriptApp.newTrigger("myFunction").timeBased().after(1 * 120 * 1000).create();
}
}
I haven't tested this but I think this is a good starting point.
function myFunction() {
var stime = new Date();
var col1;
var col2;
var col3;
var dbconnection = Jdbc.getConnection(dbUrl, root, rootPwd);
var statement = dbconnection.createStatement();
var googlesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');
var data = googlesheet.getDataRange().getValues();
var itrows=1000;
var complete=false;
if(PropertiesService.getScriptProperties().getProperty('iteration'))
{
var iteration=Number(PropertiesService.getScriptProperties().getProperty('iteration') + 1);
}
else
{
var iteration=Number(PropertiesService.getScriptProperties().setProperty('iteration', 1));
}
var max=itrows * iteration;
var min=max - itrows + 1;
if(max>data.length-1)
{
max=data.length-1;
complete=true;
}
dbconnection.setAutoCommit(false)
for (var i=min;i<=max;i++)
{
col1 = data[i][0];
col2 = data[i][1];
col3 = data[i][2];
var sql = "{call [dbo].[sp_googlesheetimport](?,?,?)}";
statement = dbconnection.prepareCall(sql);
statement.setString(1, col1);
statement.setString(2, col2);
statement.setString(3, col3);
statement.addBatch();
}
statement.executeBatch();
dbconnection.commit();
statement.close();
dbconnection.close();
if(complete)
{
PropertiesService.getScriptProperties().deleteProperty('iteration');
}
var etime = new Date();
Logger.log('Exec time: ' + (etime.getTime() - stime.getTime()));
}
function createGASTrigger() {
var varUserPropertiesService = PropertiesService.getUserProperties();
var varUserTriggerId = varUserPropertiesService.getProperty("myFunction");
var varUserTrigger = ScriptApp.getProjectTriggers();
for (var i=0;i<varUserTrigger.length;i++)
{
if (varUserTrigger[i].getUniqueId() == varUserTriggerId)
{
ScriptApp.deleteTrigger(varUserTrigger[i]);
break;
}
}
var userProperties = PropertiesService.getUserProperties();
var nextTrigger = ScriptApp.newTrigger("myFunction").timeBased().after(1 * 120 * 1000).create();
}
Either store a page value in PropertiesService.getScriptProperties() or add a value to the spreadsheet for all rows as you add them
I wish to alert all nodes text only. I want to go nested node and get text only
$(document).ready(function() {
var th1=0;
var th2=0;
var th3=0;
var th4=0;
var th5=0;
var th6=0;
var tbtn_nbr=0;
var tspan_nbr=0;
var tp_nbr=0;
var ta_nbr=0;
var tul_nbr=0;
var tli_nbr=0;
var title=document.getElementsByTagName('title')[0].innerHTML;
var total_div=document.getElementsByTagName('div').length;
var total_p=document.getElementsByTagName('p').length;
var total_a=document.getElementsByTagName('a').length;
var total_span=document.getElementsByTagName('span').length;
getdata("div", 0);
function getdata(tag_name, ti)
{
//alert(tag_name); alert(ti);
if(tag_name!='div'){ti--;}
//alert(ti);
var total_tag_lenght=document.getElementsByTagName(tag_name).length;
for(var ti; ti<=Number(total_tag_lenght); ti++){
var tag_inner=document.getElementsByTagName(tag_name)[ti].innerHTML;
alert(tag_inner);
ti_nbr=ti+1;
var words = tag_inner.split(" ");
var str=words[0];
var nd = str.search("<div");
var np = str.search("<p");
var na = str.search("<a");
var ns = str.search("<span");
var nh1 = str.search("<h1");
var nh2 = str.search("<h2");
var nh3 = str.search("<h3");
var nh4 = str.search("<h4");
var nh5 = str.search("<h5");
var nh6 = str.search("<h6");
var nbtn = str.search("<button");
var nul = str.search("<ul");
var nli = str.search("<li");
//alert(np);
if(nd>0)
{
getdata("div", ti_nbr);
}
else if(np>0)
{ //alert("hello");
tp_nbr++;
//alert(tp_nbr);
getdata("p", tp_nbr);
}
else if(na>0)
{ //alert("hello");
ta_nbr++;
getdata("a", ta_nbr);
}
else if(ns>0)
{ tspan_nbr++;
getdata("span", tspan_nbr);
}
else if(nh1>0)
{ th1_nbr++;
getdata("h1", th1_nbr);
}
else if(nh2>0)
{ th2_nbr++;
getdata("h2", th2_nbr);
}
else if(nh3>0)
{ th3_nbr++;
getdata("h3", th3_nbr);
}
else if(nh4>0)
{ th4_nbr++;
getdata("h4", th4_nbr);
}
else if(nh5>0)
{ th5_nbr++;
getdata("h5", th5_nbr);
}
else if(nh6>0)
{ th6_nbr++;
getdata("h6", th6_nbr);
}
else if(nbtn>0)
{ tbtn_nbr++;
getdata("button", tbtn_nbr);
}
else if(nul>0)
{ tul_nbr++;
getdata("ul", tul_nbr);
}
else if(nli>0)
{ tli_nbr++;
getdata("li", tli_nbr);
}
else
{
//alert(tag_inner);
}
}
}
});
Since you have jquery, you can select elements using "all" selector $("*").
Then you can iterate on them using "each" function
How can i run the below code only after the code 1 has load all its content from the external page ?
jQuery Script tried
//filters
$(window).bind("load", function() {
$(".filters li").on("click", function () {
id = ($(this).data("id")+'').split(',');
filter = $(this).data("filter");
$("#hotel-list .box").hide();
id[0] == "all" && $("#hotel-list .box").show() || id.forEach(function(v){
$('#hotel-list .box[data-'+filter+'*="'+v.trim()+'"]').show();
});
return false;
});
<!-- Count Star Rating -->
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars + two_stars;
$('.totals').text(totals);
<!-- Count Board -->
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb + board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
And the jQuery AJAX code is:
var datastring = location.search; // now you can update this var and use
$("#hotel-list").load("Rezults2.php"+ datastring + " #hotel-list> *");
So i need that the 1st codes to be executed only after the 2nd code has done its job ( from 3 to 9 secs )
ANy ideea on this ?
function runThisAfter() {
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
//etc...
}
$("#hotel-list").load("Rezults2.php", function(){ runThisAfter(); });
This will run "runThisAfter()" when load is complete.
Solution is:
$(document).ajaxComplete(function( event, xhr, settings ) {
// Your complete function here
});
Or in my Case full code:
$(document).ajaxComplete(function(event, xhr, settings) {
//Count STARS
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars +
two_stars;
$('.totals').text(totals);
//COUNT BOARD
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb +
board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function(url) {
var img = document.getElementsByTagName('img');
var i = 0,
l = img.length;
for (; i < l; i++) {
var t = img[i];
if (t.naturalWidth === 0) {
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
});