user1636547
user1636547

Reputation: 314

Google Apps Script - Share widgets between functions

This is my first time working with Google apps scripts, and I'm a bit confused as to how to access widgets from multiple functions.

Basically, I'd like to have a button that updates a label widget. So the label has some default text, but then updates to show some other text after an 'Update' button is pressed.

From what I've read, the only things that can be passed into event handlers are objects with a setName method. A label widget doesn't have this, so what can I do to update the value of a widget in my doGet function from the other handler function?

Here is an idea of what I'd like to do (but can't get to work):

function doGet() {
  var app = UiApp.createApplication();

  // Create the label
  var myLabel = app.createLabel('this is my label')
  app.add(myLabel)

  // Create the update button
  var updateButton = app.createButton('Update Label');
  app.add(updateButton)

  // Assign the update button handler
  var updateButtonHandler = app.createServerHandler('updateValues');
  updateButton.addClickHandler(updateButtonHandler);

  return app;
}

function updateValues() {
  var app = UiApp.getActiveApplication();

  // Update the label
  app.myLabel.setLabel('This is my updated label')

  return app;
}

I've been scouring the internet for hours trying to find a solution but can't seem to figure it out. Any suggestions?

Upvotes: 0

Views: 185

Answers (1)

Serge insas
Serge insas

Reputation: 46802

What you mention about getting the value of a widget from an object name property is to GET the value of a widget, not to SET it. (in this case uppercase is not to "shout" but simply to get attention :-))

And the example of the Label is typically an example of a widget that you cannot read the value...

What you are looking for is a way to set widget value : you have to get the element by its ID : see example below in your updated code:

function doGet() {
  var app = UiApp.createApplication();
  // Create the label
  var myLabel = app.createLabel('this is my label').setId('label');
  app.add(myLabel)
  // Create the update button
  var updateButton = app.createButton('Update Label');
  app.add(updateButton)
  // Assign the update button handler
  var updateButtonHandler = app.createServerHandler('updateValues');
  updateButton.addClickHandler(updateButtonHandler);
  return app;
}

function updateValues() {
  var app = UiApp.getActiveApplication();
  // Update the label
  var label = app.getElementById('label').setText('This is my updated label');
  return app;
}

Upvotes: 1

Related Questions