Home > Software engineering >  Get the value of a button on google app script
Get the value of a button on google app script

Time:11-03

I created a custom menu on the UI of google sheets with different buttons like I show in the code bellow:

function onOpen(e) {
  
  SpreadsheetApp.getUi() // Or DocumentApp, SlidesApp, or FormApp.
      .createMenu('WOZTELL')
      .addItem('FAQ LVL 1', 'InstallFAQ1')
      .addToUi();
}

My question if I can get the value "FAQ LVL 1" when someones presses the button.

CodePudding user response:

Issue:

There's no way to get this information, and no way to tell which item menu was clicked if multiple items are attached to the same function, since you cannot pass arguments to such functions.

In these cases, I think the best approach is to have a function that accepts an argument, and multiple functions (one for each menu item) that call the former function with the desired argument:

function mainFunction(arg) {
  // ...stuff using your arg...
}
function InstallFAQ1() {
  mainFunction("FAQ LVL 1");
}
function InstallFAQ2() {
  mainFunction("FAQ LVL 2");
}
//...and so on...

Related feature request:

CodePudding user response:

To my knowledge, you cannot get the caption of the button or any other kind of information when a user clicks an item in a custom menu.

But, since you know that the called function is InstallFAQ1, you already know that the caption is "FAQ LVL 1", no ?

How to still make the code readable and to keep a common behaviour

Let's say you have three items (and so three different labels), you can associate for each one custom function that only sends the label to the generic one.

const LABEL_1 = 'FAQ LVL 1'
const LABEL_2 = 'Another one'
const LABEL_3 'And another again'

function onOpen(e) {
  
  SpreadsheetApp.getUi() // Or DocumentApp, SlidesApp, or FormApp.
      .createMenu('WOZTELL')
      .addItem(LABEL_1, 'f1')
      .addItem(LABEL_2, 'f2')
      .addItem(LABEL_3, 'f3')
      .addToUi();
}

function f1() {
  fGeneric(LABEL_1)
}

function f2() {
  fGeneric(LABEL_2)
}

function f3() {
  fGeneric(LABEL_3)
}

function fGeneric(label) {
  switch(label) {
    case LABEL_1: // stuff to do
  ...
  }
}

I think that's the best you can do.

  • Related