Google Script Active Cell Value and MsgBox - javascript

I am trying to get the following code to work. I want a msgbox to appear that has the value of the cell that is being edited. This should be very simple, but I cannot get it to work. Here is the code:
function onEdit(event) {
var s = event.source.getActiveSheet();
var lastColumnRow = s.getLastColumn();
var r = event.source.getActiveRange();
var editRange = s.getActiveRange();
var editCol = editRange.getColumn();
var editRow = editRange.getRow();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
}
Thanks in advance!

The problem is just that you missed a pair of parenthesis after getActiveCell.
To help you find problems in functions that you cannot run directly (since you wouldn't get the event object). You can either wrap it in a try-catch, like this:
function onEdit(event) {
try {
var s = event.source.getActiveSheet();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
} catch(err) {
Browser.msgBox(err);
}
}
Or create the event object manually, and call a "test" function instead.
function testOnEdit() {
onEdit({source:SpreadsheetApp.getActive()});
}
function onEdit(event) {
var s = event.source.getActiveSheet();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
}

Related

How do I use two variables in my function?

So I have multiple script. One script retrieves data from a Googlesheet and parses it as JSON. The other one uses this to output it to HTML.
My first:
function getStatistics() {
var sheet = SpreadsheetApp.openById("ID");
var rowsData = sheet.getRange("A:A").getValues();
var result = JSON.stringify(rowsData);
var funcNumber = 1;
return result;
}
This retrieves the data from a spreadsheet in column A.
The second script, here I want to use both 'Result' and 'Funcnumber' in my function.
function onSuccess(data, funcNumber) {
var dataJson = JSON.parse(data);
var newColumn = document.createElement("div");
newColumn.className = "column";
for(var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
Using the Json result to PARSE the HTML works. But retrieving 'funcNumber' from the function not. Then finally I call the first function with this line:
google.script.run.withSuccessHandler(onSuccess).getStatistics();
Does anybody know how to use both result and funcNumber in my second function?
function getStatistics() {
var ss = SpreadsheetApp.openById("ID");
const sheet = ss.getSheetByName('Sheet1');
let result = {data:JSON.stringify(sheet.getRange(1,1,sheet.getLastRow(),1).getValues()),funcNumber:1}
return result;
}
function onSuccess(obj) {
var dataJson = JSON.parse(obj.data).flat();
var newColumn = document.createElement("div");
newColumn.className = "column";
for (var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + obj.funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
A single column or row is still a 2d array
Following is the way to make the call in Google script to return the value for the 2nd parameter.
google.script.run
.withSuccessHandler(onSuccess)
.withUserObject(funcNumber)
.getStatistics()
WithUserObject() needs to be called after the withSuccessHandler.
See the documentation below on Google script
withUserObject(object)
Sets an object to pass as a second parameter to the success and failure handlers. This "user object" — not to be confused with the User class — lets the callback functions respond to the context in which the client contacted the server. Because user objects are not sent to the server, they are not subject to the restrictions on parameters and return values for server calls. User objects cannot, however, be objects constructed with the new operator.

How a function with parameter `findRow(s)` is called on a specific script?

This code works perfectly well. I just don't understand why.
Can someone explain how function findRow(s) is "called"?
I don't see what makes function findRow(s) run.
I see how they've defined the var rA=findRow(resp.getResponseText());
It doesn't seem to make sense to me that this makes the function run.
I'm obviously very green at this... does the act of just defining the variable make that next function "work"?
Or is it the Logger.log part that starts the work?
function findAString(){
var ss=SpreadsheetApp.getActive();
var sh1=ss.getActiveSheet();
var sh2=ss.getSheetByName('Completed');
var resp=SpreadsheetApp.getUi().prompt("Enter a String");
var s=resp.getResponseText();
if(s){
var rA=findRow(s);
if (rA.length>0){
sh2.getRange(sh2.getLastRow()+1,1,rA.length,rA[0].length).setValues(rA);
var rows='<br /><h3>Order details have been moved to the Completed tab</h3><br />';
rows+=Utilities.formatString(resp.getResponseText());
for(var i=0;i<rA.length;i++){
rows+=Utilities.formatString('<br /> %s',rA[i].join('<br />'));
}
rows+='<br /><br /><input type="button" value="Exit" onClick="google.script.host.close();" />';
if(rows){
var ui=HtmlService.createHtmlOutput(rows);
SpreadsheetApp.getUi().showModelessDialog(ui, 'Search Results')
}
}
}else{
throw('Error: Invalid Response');
}
}
function findRow(s) { ;// the actual search function
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getActiveSheet()
var rA=[];
var vA=sh.getDataRange().getValues();
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++){
if(vA[i][j].toString().indexOf(s)>-1){
rA.push(vA[i]);
break;
}
}
}
return rA;
var sourcesheet = ss.getSheetByName('Form Responses 2');
var targetsheet = ss.getSheetByName('Completed');
var targetrange = targetsheet.getRange(targetsheet.getLastRow(), 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn());
var rangeValues = sourcesheet.getRange(2, 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn()).getValues();
targetrange.setValues(rangeValues);
}
As you already mentioned findRow function is called by
var rA=findRow(resp.getResponseText());
Considering that a few code lines it is var s=resp.getResponseText();, you could rewrite it to save some characters like this:
var rA=findRow(s);
Above the above line is
var resp=SpreadsheetApp.getUi().prompt("Enter a String");
This line assigns a PromptResponse object to resp. The PromptResponse object has the method getResponseText() which returns a String object.
The Logger.log(rA) just logs the String value to the log.
References
Functions

Jquery can't pass variable through function

$(document).ready(function() {
//var audit_to_del;
//var type;
//var option_selected;
//var progress;
function redirect(audit_type) {
var page;
switch(audit_type){
case 'Simple 123':
page = 'smeg';
break;
}//end switch
return page;
}
$('#audit_summary_list_div').on("click", ".go_btn", function(e){
var audit_to_del = $(this).prev('.audit_to_del').val();
var type = $(this).closest('tr').find('.audit_type').text();
var option_selected = $(this).closest('td').prev().find('.option_select').val();
var progress = $(this).closest('tr').find('.progress').text();
var location = redirect(type);
alert(location);
});
});
If I pass a literal value through the function it works and returns 'smeg'
var location = redirect('Simple 123');
If I alert(type) the value is correctly shown as Simple 123
If I try to use
var location = redirect(type);
I get an undefined error
I have tried created global variables and then using them in the function
Your text has white-space in it making the condition false. Try that :
var location = redirect($.trim(type));

how can i access a variable in one javascript in another javascript?

Hi guys This is my code of two javascript.i want to access variable defined in first javascript into another script.
1)
<script>
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
</script>
2)
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editor.getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
</script>
Now my problem is i want to access the editor defined in first javascript as
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
in second javascript.
anyone has answer of this then please help me to do so
If you leave out var while defining variables they will be globally accessible.
So
pre = this;
instead of
var pre = this;
would make pre accessible from every function.
the only way I can think is to pass the variable into the other functions as a variable
function otherJavaFile.myFunction (myVariable);
or alter a variable in the HTML i.e. the custom data-value and then the other script can access it. I don't like global variables.
// Sheet 1
$("#myDiv").attr("data-variable",yourValue);
// Sheet 2
var secondVariable = $("#myDiv").attr("data-variable");
buddy i am not comfortable with jquery...
I hope you are looking forward for the iframes/frames on same document[window sharing].
Based on my knowledge of Javascript DOM to access a variable defined in one document inside another document.You have to use document.importNode(original Node as in other document,boolean) method as per DOM 2.
Do something like this for javacript code ...
documentI(original variable/node present here)- iframe.contentDocument.getElementsByTagName(/Tag name of Node/)...
documentII(node to be cloned here)-
document.importNode(originalNode,True)
I hope this works

Javascript to Read/Count Sharepoint 2010 List Items

I am having a lot of trouble with this. Essentially, I am trying to count the number of times Decommission appears in a particular list column. From what I can tell, the javascript is correct, but it doesn't work. Can anyone provide some guidance? Thanks!
<script type="text/javascript">
var myItems = null;
var siteUrl = &apos;https://chartiscorp.sp.ex3.secureserver.net/&apos;
function SuperDuper()
{
var queryString = &apos;<View><Query><Where><Gt><FieldRef name="End State" /><Value Type="String">Decommission</Value></Gt></Where></Query></View>&apos;;
var myContext = new SP.ClientContext(siteUrl);
var myWeb = myContext.get_web();
var myList = myWeb.get_lists().getByTitle(&apos;System_Information&apos;);
var myQuery = new SP.CamlQuery();
myQuery.set_viewXml(queryString);
myItems = myList.getItems(myQuery);
myContext.load(myItems,&apos;Includes(End State)&apos;);
myContext.executeQueryAsynch(Function.createDelegate(this,SuperDuperSuccess),Function.createDelegate(this,SuperDuperFail));
}
function SuperDuperFail(sender, args)
{
alert(&apos;Failed &apos; + args.get_message());
}
function SuperDuperSuccess(sender, args)
{
var endStateEnumerator = myItems.getEnumerator();
var decommCount = 0;
while(endStateEnumerator.moveNext())
{
//var currentEndState = endStateEnumerator.get_current();
decommCount = decommCount + 1;
}
alert(decommCount);
}
window.onload = SuperDuper;
</script>
What is the error?
Have you tried to see the script error it is throwing?
In function SuperDuperSuccess() you can simply put
var count=0;
count=this.myItems.get_count();
No need to write while loop .
Pls try to put alert and after some line and see what is coming.

Categories

Resources