Using google apps script I'm having trouble running a js function which passes parameters. When I add the parameters it will always run the code when the page loads instead of when the button is clicked.

Direct from the HtmlService example, it is OK - it runs when the button is pressed...

document.getElementById('button1').onclick = doSomething;

But when I add a parameter to the call (and function) as below, it runs just once when the page loads (and not when the button is pressed)...

document.getElementById('button1').onclick = doSomething('with_this_parameter');

Any insight into this behaviour would be greatly appreciated... sorry if the answer is obvious!


When you say

document.getElementById('button1').onclick = doSomething('with_this_parameter');

This means call doSomething('with_this_parameter') and then assign the returned value to document.getElementById('button1').onclick. Hence that is why it gets called when code reaches that line. Whether the value is assignable to that property or not is another question, but that is why it gets called.

Use it like this

document.getElementById('button1').onclick = function(){
    doSomething('with_this_parameter');
}

Reference: This solution was given by Mark Linus.


Do like this:

document.getElementById('button1').onclick = function(){
    doSomething('with_this_parameter');
}

I usually do clickHandlers like so:

 // create button here or get button...
 var button1 = document.getElementById('button1').setName('button1');
 var clickHandler = app.createServerClickHandler('doSomething');
 button.addClickHandler(clickHandler);

 function doSomething(e){
   var button1 = e.parameter.button1;
   <do something with var button>
 }

I'm not sure what parameter you are adding, but you need to add a callback element to pass it if it isn't passed by the button itself via a .setId/getId or .setTag/getTag. If it is from a textbox:

 var textbox = app.createTextBox(); 
 var button1 =
 app.createButton.setName('button1'); 
 var clickHandler =        
 app.createServerClickHandler('doSomething').addCallbackElement(textBox);
 button1.addClickHandler(clickHandler);

Hope this helps!


To assign a reference of function to some variable, you do:

var a = doSomething;

where doSomething is a function.

But when you have to pass parameters and assign that function

var a = doSomething(b);

this will cause trouble as while assigning the function to the variable, it gets called and not when it is intended to be called.

To overcome this, you can use arrow functions or simple function to call your own function with params.

var c = () => doSomething(d);

This actually is understood as var c = anonymous_function;

or

var c = function() {
    doSomething(d);
}

Hence you can do:

document.getElementById('button1').onclick = () => doSomething('with_this_parameter');