How to write a "reusable" function for google sheets? [duplicate] - javascript

This question already has answers here:
Set anonymous/dynamic functions to Menu
(3 answers)
Increment Cell value by one by clicking
(3 answers)
button click is only working on Windows & not working on Android mobile sheet
(2 answers)
Closed 2 years ago.
I need to do the same operations on different cells and I am trying to write a generic script. I give a trivial example that explains my problem below.
Let's say that I want to click on a button and decrease the value of the cell A1 by 1. That's straightforward. I define the following function
function dec_cell_def(){
var cell = fr = SpreadsheetApp.getActiveSheet().getRange("A1")
cell.setValue(cell.getValue() - 1)
}
Then assign the "script" dec_cell_def to any button and I am done.
Let's say now, that I want to do this for many different cells. I could of course write a function for each one, but this is hardly a solution. So I thought the following would work. I define the function cell_dec that take as an argument the label of a cell and returns a function that decreases the value of the cell:
function dec_cell(label){
() => {
var cell = fr = SpreadsheetApp.getActiveSheet().getRange(label)
cell.setValue(cell.getValue() - 1)
}
}
However when I assign the "script" dec_cell("A1") to a button, I am told that the script does not exist. What is the proper way to do that?
PS. I know that I can get the selected cell and act on it, but I would like to have a fixed target for my function.
Edit: I meant that I want to do this for few cells but not all at once. I would like to create a button for each cell and I would like to avoid copy-pasting the same code. I think that none of the suggested questions answer that.

Related

I need javascript/html assistance with making a textfield (not)readOnly [duplicate]

This question already has answers here:
remove readonly from input
(2 answers)
Closed 2 years ago.
I find myself at a loss. I am charged with the seemingly trivial task of making a text field (not) read only, if some condition is true. well, I have hit the wall.
I have tried various versions of the following:
if(someTextBox.enable==false){
someTextBox.enable=true;}
including
someTextBox.setAttribute("enable", true);
and even
someTextBox.setAttribute("readOnly", true);
I am using Chrome devtools, and can see various incarnations of null, including ignored if-clauses.
You can simply do:
document.getElementById("myText").readOnly = false;

Simple format of text on front-end of my website (replace characters)? [duplicate]

This question already has answers here:
Remove first character from a string if it is a comma
(4 answers)
Closed 3 years ago.
My website uses product references in this style: "R202020"
I want them to be shown like this for the users of my website: "BA2202020"
So basically I'm looking for a script, which formats the style of my reference numbers (should affect a ".reference" class I've created) by:
Removing the "R" in the original reference - replacing it with a "BA2" in stead - leaving the rest as it is (the "202020" part).
How can I do this?
Find 1st character of your string using string[0] and replace that with your desire value like below.
var string=$('.YourClass').text();
var result = string.replace(string[0],'BA2');
$('.YourClass').text(result);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='YourClass'>R202020</span>
Try replace method. https://www.w3schools.com/jsref/jsref_replace.asp
'R202020'.replace('R2','BA2') // BA202020

Page does not update on setTimeout? [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 6 years ago.
I wrote a script that will read in a text file and attempt to find duplicate entries in the dataset with the user-entered parameters. As the dataset is quite large, the page tends to freeze. I referenced this post here:
Prevent long running javascript from locking up browser
To perform my calculations in chunks using setTimeout(). I am trying to get a percentage complete to display on the page, but it won't display until the script finishes running (both Chrome and Firefox).
This is my pump function:
function pump(initDataset, dataset, output, chunk){
chunk = calculateChunk(initDataset, dataset, output, chunk);
document.getElementById("d_notif_container").style.display="block";
document.getElementById("d_percent").innerHTML = NOTIF_SEARCH_START + percentComplete + "%"; //This is a div
document.getElementById("i_pc").value = percentComplete; //This is an input text field
if(percentComplete < 100){
console.log("Running on chunk " + chunk);
setTimeout(pump(initDataset, dataset, output, chunk), TIMEOUT_DELAY);
}
else {
comparisonComplete(output);
}
}
I attempted to display in two different ways, using innerHTML and value (two different elements). The percentComplete is a global variable that is updated in calculateChunk().
The strangest thing is, if I inspect one of those elements, I can watch the HTML change counting the percent (in Chrome). It just simply does not show on the actual page until the script is done running. I've tried changing the timeout up to 1000 as well with not luck.
Any idea why this is happening?
This code
setTimeout(pump(initDataset, dataset, output, chunk), TIMEOUT_DELAY);
calls pump and passes its return value into setTimeout, exactly the way foo(bar()) calls bar and passes its return value into foo.
If you want to call pump after a timeout with those values, you can use Function#bind to do it:
setTimeout(pump.bind(null, initDataset, dataset, output, chunk), TIMEOUT_DELAY);
// ------------^^^^^^^^^^
Function#bind returns a new function that, when called, will use the given this value (the first argument) and arguments you give bind.

Calculator Javascript/Jquery storing variables

I am a new student understanding javascript. I am currently having a difficult time understanding a simple concept on storing a variable on my calculator side project. My problem is when a operator (+,-,/,*) is clicked, I want to store the first value as a variable (first user input). Then after the user clicks on the digits again, the display screen will clear and display the second variable (or the second user input). Then if the operator button or equals button is pressed it will calculate the two variables (so var + var2). I have used a global variable for variable1, but I am having trouble assigning the second variable with the user input after clearing the item. I have a feeling there is a simple answer to this question, but I want to know what I am fundamentally doing wrong so I can start reviewing all the topics I need to do cover again. Anyways any help will be great! Thanks
'http://codepen.io/kevk87/pen/EVoEaa`
First thing, you have a syntax error in your statement that is causing jQuery to not select the right element. I have fixed that in my snippet below.
Second, you need to implement the equal operator to put all of this together. Meanwhile, to address your problem and point you in the right direction, You aren't really capturing the second element. Everytime the user clicks on an operator, you are reassigning the value that is on the screen to 'number' variable, then clearing the screen and assigning the value that is on the screen(which is clear because you just cleared it) to 'number2'.
One way to get around this is to check and see if the 'number' variable has a value, if so then you assign the next value to the 'number2' variable. Here's a snippet of code that does this.
$(".operator").on("click",function() {
if (number == null) {
number = $("#screen").html();
}
else {
number2 = $("#screen").html();
$("#screen").html("");
}
});
You forgot the # selector on the line $("screen").html("");, jQuery won't select the correct element. Also you haven't implemented the equal operator yet.
$(".operator").on("click",function() {
number = $("#screen").html();
$("screen").html("");
number2 = $("#screen").html();
});

how to call a javascript function from a geogebra script?

In Geogebra let's define a JavaScript global function from a button (property):
function ggbOnInit() {
}
function test(par) {
return par * math.random();
}
How do I call that function from a Geogebra script attached to that button ("on click" property)?
The following Geogebra script:
Sequence[test(3),k,1,5]
launches an error message " unknown command test", whereas a sequence of five random numbers between 0 and 3 were waited.
In order to call your Global JavaScript function your "On click" script must be of type JavaScript and not GeoGebra Script.
I found this possible solution.
Create a button and in the "On Click" section, with "JavaScript" selected at the bottom, insert the code:
ggbApplet.evalCommand("list={0}");
if (! ggbApplet.exists("par")) {ggbApplet.evalCommand("par=200")};
for(var i =1;i<5;i++)
ggbApplet.evalCommand("SetValue[list," +i+", par* random()]");
The par parameter can be set as a Geogebra variable or inside the code (that last value will be used in case the variable doesn't exist).
Anyway I couldn't find how to use a function in the Global Javascript tab or how to use the Javascript math.random() command.
The problem is that the JavaScript commands available inside Geogebra are probably a limited set of the JavaScript available outside it, but I'm not sure about that.
I'm not sure whether you want to get five random integers or decimal numbers. If you want to get five random integers between 0 and 3 you can easily do it with GeoGebra scripting.
You can first create an empty list writing for example list={} into Input Bar and then fill it with a button or create it dynamically with a button.
Create a button, open Object Properties, go to Scripting tab and inside On Click tab write next line:
list=Sequence[RandomBetween[0,3],k,1,5]
Be sure that you've chosen "GeoGebra Script" in drop-down menu.
IF YOU WANT FIVE RANDOM DECIMAL NUMBERS between 0 and 3 do the same but with little different code line:
list1=Sequence[random()+RandomBetween[0,2],k,1,5]
Hope this helped...

Categories