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');
}
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');
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!
Related
As it says in the title, I'm trying to create a button element in JavaScript, but when I try to set its onclick attribute, it just ignores it. I've looked at other questions with this topic on this site (such as this one), but everyone answers to put it in with HTML, like so:
<button id="buttonid" onclick="click(this);">
But my program dynamically creates the HTML buttons entirely with JavaScript (they're aligned on a table, so using a for loop is very useful. Plus I'm more familiar with JavaScript). Like this:
var b = document.createElement("button");
b.id = "buttonid";
b.onClick = "click(this);"; //I've tried many variations with no success
document.appendChild(b);
The button element is never declared in the HTML. I need a way to add the onclick attribute using JavaScript alone. I'm not very experienced with JQuery, so I would prefer just JavaScript.
Thank you in advance.
PS, I've tried all the following methods with both lowercase .onclick and camelcase .onClick:
b.onClick = "click(this);"; //just simply doesn't work
b.onClick = click(this); //actually runs the program there, with some ambiguous "this" object
b.onClick = click; //passes the actual function, but disallows the ability to pass the button's object (via "this")
You can use addEventListener to add the listener to the button and bind to pass the button as this for the handler function.
b.addEventListener(`click`, click.bind(b));
Or if you want to use onClick, just use bind:
b.onClick = click.bind(b);
Try this
var b = document.createElement("button");
b.onClick = function(){
alert("on click handler");
};
Try b.onClick = function(){ console.log("test"); }
I am not sure what your "click" function is. Maybe it isn't declared yet or something. Or what is happening is your function is named click "function click(){...}" which instead needs to be click = function(){...}
(function(){
// create the button
var buttonB = document.createElement('button');
buttonB.id = 'buttonB';
var textB = document.createTextNode('Button B');
buttonB.appendChild( textB );
// set the click event on the button
buttonB.addEventListener('click', function(){
// console.log('test');
// console.log( this );
clickFunc( this );
});
// populate the DOM-body with the button
document.body.appendChild( buttonB );
})();
function clickFunc( that ){
console.log( that );
}
Sorry if my question seems naive (a bit of a newbie here), but I seem not to be able to get a simple answer to my question.
In JavaScript I try something like this
window.onload = init; *// ok, this assigns to the window load event a function that doesn't execute straight away*
// now I define my init()function
function init(){
// say...
alert('Noise!');
/* but here is my dillema...
Next say I want to assign to an button.onclick event a function that only executes when I click the button.
But (!here it is...!) I want to pass arguments to this function from here without causing to execute because it (obviously) has brackets.
Something like: */
var button = document.getElementById('button');
var promptInput = prompt("Name?");
button.onclick = printName(promtInput); // I only want to print name on button click
}
function printName(name){
alert(name);
}
So... OK, I know the example is stupid. Simply moving all prompt gathering inside printName() function and assign to button.onclick a bracketless printName function will solve the problem. I know. But, still. Is there a way to pass args to functions you don't want to execute immediately? Or it really is a rule (or 'by definition') you only use functions that await execution when you don't plan to pass args via it?
Or how do you best to this thing otherwise?
Thanks a lot!
Ty
button.onclick = function() {
printName(promptInput);
};
You can use Function.prototype.bind():
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
For example:
button.onclick = printName.bind(null, promtInput);
You could put the data that you would normally pass as an argument into some other holding location. You can either put it in a hidden HTML element, or you can use the sessionStorage API to keep it. So your code would look like this:
var button = document.getElementById('button');
var promptInput = prompt("Name?");
sessionStorage.setItem('MyName', promptInput);
button.onclick = printName; // I only want to print name on button click
}
function printName(){
alert(sessionStorage.getItem('MyName');
}
My query is regarding using Javascript to change the value of an onclick function that already exists on the page.
There's a button. This button has the following onclick function:
onclick="if (confirm('Yahdy Yahdy yah?')) { someFunction(); }; return false;"
I would like to change the onclick function using Javascript to just be as follows and or extract the someFunction(); and run that directly without having to go through the confirmation. As I understand it, you can't confirm a confirm through scripting, so my only option is to run someFunction(); directly. My question is, how do I access someFunction() directly as someFunction() contains randomly generated values each time the page loads.
onclick="someFunction();"
That's basically what I'd like, so I can then call onclick() directly. I'm happy to use vanilla or jQuery to go about this.
TLDR: I want to extract PART of the old onclick function and make a new onclick function with JUST that part.
You can do this:
var code = obj.onclick.toString();
That will give you the javascript code assigned to that click handler to which you can search through it, find what you're looking for and reassign the click handler to something else.
I have no idea if this is the best way to do it, but here's something that worked for me:
function nullConfirm() { return true;};
(function() {
var obj = document.getElementById("test");
var code = obj.onclick.toString();
code = code.replace("confirm(", "nullConfirm(");
var matches = code.match(/\{(.*)\}/);
if (matches) {
obj.onclick = function() {
eval(matches[1]);
}
}
})();
I'm new to Javascript and I have a problem passing a variable from function to function:
$(document).ready(function () {
$('input[type=checkbox]:checked').removeAttr('checked');
var filename = document.getElementById("Tagg").value;
var checkboxesH = $('input[type="checkbox"][name="tags[]"]');
checkboxesH.change(function () {
$('input[type="text"][name="tags"]').val(filename);
var current = checkboxesH.filter(':checked').length;
});
});
in the checkboxesH.change function, filename is always null! why? When the page opens, there is a string in the textfield tags.
Thank you.
Javascript passes the value of the variable at the time of the function creation. To fix this problem you should simply call
document.getElementById("Tagg")).value
in your .change() function directly. This way, it will reflect the state at change time, not when the change event handler was created.
In JavaScript I can assign onclick by traditional way:
button.onclick = engineStop();
But how can I assign to onclick a function with parameter(s)?
This does not work >>
button.onclick = engineStop(this);
The function needs to receive this parameter to know which button has been clicked on.
Please advice... (no jQuery)
button.onclick = function() {engineStop(this);};
Using an anonymous function.
Like this:
function engineStop(param){
return function(){
//engineStop function's body here,
//which uses 'param' argument
};
}
button.onclick = engineStop(this);