Issues with Triggers on Google Script - javascript

I have the following function which works perfectly fine when I run it manually.
function LastUpdate() {
var thisSS = SpreadsheetApp.getActiveSpreadsheet();
var sheet = thisSS.getSheetByName('Roster');
var data = Session.getActiveUser().getEmail();
var Edit = 0;
var time = TimeStamp();
var Row;
Row = findInColumn("L", data);
Edit = checkEdits(Row);
if (Edit == 1)
{
sheet.getRange(Row,20).setValue(time);
}
}
I set up a trigger manually by going to Resources -> Triggers and selected the above Function to execute onEdit. Basically, whenever a cell in the sheet is edited, I want to automatically trigger this function to execute. I am not sure what the issue is !
Any help would be much appreciated.
EDIT - I tried to do this and this also does not work
function onEdit(e)
{
LastUpdate ()
}

Why don't you use the simple onEdit trigger instead of the installed trigger? Since you're looking for the latest edit made by the active user that might be a much easier, faster and more stable solution.
function onEdit(e){
var range = e.range; //edited range
range.getColumn();
range.setValue();
//etc
}

Related

Trying to pull user email when they check a checkbox

I am trying to pull an active user's email when they check a box. I wish to paste the active user's email in a separate column (adjacent currently, but the ability to be flexible would be nice). I have done this before in a different worksheet, but for some reason I cannot get it to work on this one. I can get it to paste a simple variable, or even the edit date, so I am thinking there must be something erroring out with the user specifically. I am on a work owned domain with company addresses, but so is the other sheet that is working. Anyway, here is what I have currently (amature, be gentle):
function onEditAdded(e) {
var activeSheet = e.source.getActiveSheet();
if (activeSheet.getName() == "New Hires") {
var aCell = e.source.getActiveCell(), col = aCell.getColumn();
if (col == 20) {
var dateCell = aCell.offset(0,1);
if (aCell.getValue() === true) {
var email = Session.getActiveUser().getEmail();
Logger.log(email);
dateCell.setValue(email);
} else {
dateCell.setValue("");
}
}
}
}
I test your code and it should run without issues.
You just need to add it as an Installable Triggers
Manually create installable trigger:
Open your Apps Script project.
click Triggers alarm.
At the bottom right, click Add Trigger.
Select and configure the type of trigger you want to create.
Click Save.
function onEditAdded(e) {
var activeSheet = e.source.getActiveSheet();
if (activeSheet.getName() == "New Hires") {
var aCell = e.source.getActiveCell(), col = aCell.getColumn();
if (col == 1) {
var dateCell = aCell.offset(0,1);
if (aCell.getValue() === true) {
var email = Session.getActiveUser().getEmail();
Logger.log(email);
dateCell.setValue('user#example.com');
} else {
dateCell.setValue("");
}
}
}
}
Output:
You can also explore on how to create installable triggers programmatically, so that you wont need to add it manually every time you copy this script to a different workbook.
References:
https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_programmatically
Is there any way to automatically create installable triggers?

Multiplication of two input table element values on html form row not working (Google Webapp)

I am trying to create an order form as a table, where a user enters a quantity required for a product in a row and the corresponding value is calculated by multiplying the user entry by the price held in another element of the same row of the table.
The form is loaded as a WebApp via Google and uses an Apps Script to retrieve the table values from a Google Sheet. The form loads OK with the data as expected but I just can't get the calculation part to work.
If I click the "place Order" button at the bottom of the form, the numberUsed values are included as parameters in the URL so it looks as though the values are updating in those elements but I haven't been able to access them to do the calculation and display it in the element called "value".
I am a novice programmer so I am sure it is something basic I am doing wrong (or not doing). I have created a JSBin https://jsbin.com/siwerat/edit?html,js,console,output and I have tried several variations of code derived from other answers and videos over the last couple of weeks without success so any help will be much appreciated.
//var numRows;
document.addEventListener('DOMContentLoaded', function() {
//new
var elems = document.querySelectorAll('cart');
var instances = M.FormSelect.init(elems);
// end new
document.getElementByname("cart").addEventListener("submit", getValues); //used to submit form - needs validation
//document.getElementByName("numberUsed").addEventListener("oninput",getValues);//used to submit form - needs validation
});
function test(event) {
"use strict";
event.preventDefault();
console.log("getValues function triggered");
}
function getValues() {
event.preventDefault();
var rows = document.querySelectorAll("package-row");
rows.forEach(function(currentRow) {
var numberUsed = Number(currentRow.querySelector('#numberUsed').value);
var price = Number(currentRow.querySelector('#price').value);
//var inPackage = Number(currentRow.querySelector('#inPackage').value);
var inPackage = 1;
var revenue = 1;
document.querySelectorAll('numberUsed');
if (numberUsed == "") {
if (isNaN(inPackage) || isNaN(price)) {
return;
}
revenue = price * inPackage;
} else {
if (isNaN(numberUsed) || isNaN(price)) {
return;
}
revenue = price * numberUsed;
}
var value = revenue * 5;
//currentRow.querySelector("#revenue").innerHTML = revenue;
currentRow.querySelector("#value").innerHTML = value;
});
}
Thanks Rafa for the guidance. After further reading/analysis I have got it working. The Event bubbling video by Learn Google Spreadsheets: [https://www.youtube.com/watch?v=fYpGe5ngujk][1] and an article on EncodeDNA.com (Dynamically create HTML table and Button using Javascript) helped narrow down the issues I had to get a solution.

How to populate jqGrid filter toolbar and search when the page loads (ASP.net webforms)

Currently, I'm trying to populate the filterToolbar with values taken in from a cookie. If there is cookie data for the filters, I want it to fill the respective textboxes and filter the jqGrid for that data.
I'm using ASP.net webforms, so most of my data is initialized already. How/where could I add javascript in order to get this going?
I actually figured out what I was doing.
So what I ended up doing as a solution was adding a timeout function in the document.ready function
$(document).ready(function () {
// some code
setTimeout(function () {
$('#Jqgrid1')[0].triggerToolbar();
}, 500)
//some code
}
My guess is that I couldn't use the $('#grid')[0].toggleToolbar() to force it because whenever I tried to use it, it was before the whole grid was finish setting up.
In the ASP webform, I had several functions registered.
<cc1:JQGrid ID="Jqgrid1" runat="server"
Height="630"
SearchDialogSettings-Draggable="true"
EnableViewState="false"
AutoWidth="True" >
<ClientSideEvents
LoadComplete="Jqgrid1_LoadComplete"
GridInitialized="initGrid"
/>
<%-- grid code --%>
</cc1:JQGrid>
The LoadComplete is executed after the grid is loaded. I tried doing triggering my toolbar there, but didn't work. My guess is, again, it was too early in the grid execution to use the triggerToolbar() function.
The same went for the GridInitialized events (even though both events would seem to imply to me that the grid is done doing its thing... but whatever...)
The way that I read my cookies in was actually in the GridInitialized event handler.
function initGrid() {
var myJqGrid = $(this);
var valueName = 'GridFilters';
var myCookie = document.cookie;
var gridFilterString;
var gridFilterArray;
var currentFilter;
var myCookie_arr;
var myDic = {};
if (myCookie.indexOf(valueName) > -1) { // don't even bother if the cookie isn't there...
myCookie_arr = myCookie.split("; "); // looking for the cookie I need
// read cookies into an array
for (var i = 0; i < myCookie_arr.length; i++)
{
parts = myCookie_arr[i].split("=");
first = parts.shift(); // remove cookie name
myDic[first.trim()] = parts.join("=").trim(); // handles multiple equality expressions in one cookie
}
if (myDic.hasOwnProperty("GridFilters"))
gridFilterString = myDic["GridFilters"];
if (gridFilterString != "NONE") {
myFiltersDic = {}
myFiltersArr = gridFilterString.split("&")
for (var i = 0; i < myFiltersArr.length; i++) {
parts = myFiltersArr[i].split("=");
myFiltersDic[parts[0].trim()] = parts[1].trim();
}
myParams = $(this).jqGrid("getGridParam", "postData");
var filters = []
for (keys in myFiltersDic) {
$('#gs_' + keys.trim()).val(myFiltersDic[keys].trim());
}
$.cookie('m_blnSearchIsHidden', "0", "/");
if (!isLoaded)
{
$(this)[0].toggleToolbar();
}
isLoaded = true;
}
}
}

jquery function not firing on load

looking for some help on a dumb problem.
I have these functions:
function update_pred(){
var sum_pred = 0;
$('.pred').each(function(){
var importo_pred = this.value;
importo_pred = importo_pred.replace(",",".");
sum_pred += parseFloat(importo_pred);
$('#pred_tot').html(sum_pred);
});
}
function update_ipo(){
var sum_ipo = 0;
$('.ipo').each(function(){
var importo_ipo = this.value;
console.log(importo_ipo);
importo_ipo = importo_ipo.replace(",",".");
sum_ipo += parseFloat(importo_ipo);
console.log(sum_ipo);
$('#ipo_tot').html(sum_ipo);
});
}
These are supposed to update a table cell based on the values of some other field with a specific class.
If I call each of these functions from a change event in Jquery everything works fine.
What is not working is this:
$(document).ready(function(){
update_pred();
update_ipo();
});
I am not able to fire the two functions on page load. I load each value from mysql and I want to display the sums on load.
What do I miss?
Thanks for the help as usual!
Solved. The problem was related to this piece of code:
$('.ipo').each(function(){
$(this).change(function(){
update_ipo();
});
});
Turning it to the right form of:
$('.ipo').change(function(){ update_ipo(); });
did the trick.
This code was working by itself but was hanging all other javascript from working.

How is it possible, that ajaxing is much more slower in Chrome and IE than Mozilla?

I would like to ask you to find the point, why the site -I'm working on- is slow.
the conditions of the problem:
large row count (so I think maybe the problem is related to this.)
there is ajaxing event (I have tired to comment it out and the problem disappeared)
using not Mozilla (this freeze effect appear in IE and Chrome)
description of the problem (see the image):
I change the value of input
after there is an ajax call (in order to calculate prize) and it takes in FF about 30 ms otherwise more than 1 s
there is a freeze until the ajax finished (but ajax is not set to async:false)
only after that can I change the next input
I have tired to reproduce the error, but I could't. So see the original site:
site: foto/fotokidolgozas/elohivas-beallitasok.php
Log in and pass: d838292#rtrtr.com
Update: It works now fine, the trick is the following:
I use hidden input fields, their values are json_encode-d strings. I can process them anytime with js.
Thank you for any help!
Code:
$('#cikkek,#magic_bar').on("change","select,textarea,input[type!=hidden]",function(event_object){
if( $(this).attr('name') == "kijelolve" && !$(this).parents('#magic_bar').length)return true;
var cikk_id = $(this).parents('.cikk').attr('id');
var cikk_tipus = $("input[name=cikk_tipus]").val();
var tulajdonsag = $(this).attr('name');
var ertek = $(this).val();
if(ertek == "-1")return false;
if($(this).is('[type=checkbox]'))ertek = $(this).prop("checked")?'1':'0';
if(cikk_tipus=='fotokidolgozas' && (tulajdonsag=='meret'||tulajdonsag=='vagas'))
{
var sor = $(event_object.target).parents('.cikk');
var act_meret = sor.find('select[name=meret]').val();
var act_fill = sor.find('select[name=vagas]').val();
var act_zold_class = sor.find("input[name=zold_"+act_meret+"]").val()=="1" ?"zold":"feher" ;
var name = "src_"+act_meret+"_"+act_fill;
var name2 = "szoveges_uzenet_"+act_meret+"_"+act_fill;
sor.find(".img_cont").find("img").attr("src",sor.find("input[name="+name+"]").val());
sor.find(".szoveges_uzenet").text(sor.find("input[name="+name2+"]").val());
sor.find(".dpi_megfelel").text(sor.find("input[name=minoseg_"+act_meret+"]").val()+" ("+sor.find("input[name=dpi_"+act_meret+"]").val()+" dpi)");
sor.find("select[name=meret]").removeClass("feher zold").addClass(act_zold_class);
}
var before = now();
//this is the ajax part
if(ajax_modositaskor)
$.post('/_fn/cikk/mod.php',{
'cikk_tipus':cikk_tipus,
'cikk_id':cikk_id,
'tulajdonsag':tulajdonsag,
'ertek':ertek
},function(a){
var elapsed = now() - before;
if(a[0]!="1")
{
//error
alert(a[0]);
return;
}
if(a[1]!="-1")
{
//there is new price
$(event_object.target).parents('.cikk').find('.ar').text(a[1]);
}
if(a[2]!="-1")$('#cikkek_ara').text(a[2]);
osszegzest_frissit(a[3]);
var php_time = Math.round(a[4])
a_min = Math.min(a_min,elapsed);
p_min = Math.min(p_min,parseFloat(php_time));
a_max = Math.max(a_max,elapsed);
p_max = Math.max(p_max,parseFloat(php_time));
if(!a_avg)a_avg = elapsed;else a_avg= Math.round((a_avg+elapsed)/2);
if(!p_avg)p_avg = php_time;else p_avg = Math.round((p_avg+php_time)/2);
trace("ajax="+elapsed+"\tphp="+php_time+"\tajax_min="+a_min+"\tphp_min="+p_min+"\tajax_max="+a_max+" \tphp_max="+p_max+"\tajax_avg="+a_avg+" \tphp_avg="+p_avg);
},"json").error(function() { postHiba() });
});
The problem was that the hidden data was too large (see my other question), and it decreased the processing time. (Firefox seems to be well coded, because this does not mattered)
Now the problem is fixed.

Categories

Resources