Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick function runs automatically

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!

like image 840
T-L Avatar asked Jan 20 '13 14:01

T-L


2 Answers

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.

like image 87
Hanky Panky Avatar answered Nov 15 '22 10:11

Hanky Panky


Do like this:

document.getElementById('button1').onclick = function(){
    doSomething('with_this_parameter');
}
like image 12
Danilo Valente Avatar answered Nov 15 '22 09:11

Danilo Valente