How to get user input in string-form on a google script

14,850

When you call one of the ui.prompt() methods, it opens the dialog and interacts with the user. When the user dismisses the dialog, ui.prompt() returns the PromptResponse object which contains all the results of that interaction.

You can then query the PromptResponse object (i.e. call response.getResponseText() and response.getSelectedButton()) to find out what text the user entered and what button the user clicked in the dialog.

The CalendarApp object does not have a getUI() method nor a "Tools > Script editor" menu command.

Instead, attach an Apps Script UI to a Google Sheet, Doc, or Form or create a standalone script and run it from there. The script can prompt the user for input and then call on the Calendar API to do something like add a Calendar event.

Also, consider looking for a date-picker library.

Example in a Google Sheets script

/** Demonstrates a simple way to prompt the user for a date. */
function promptForDate() {
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Create a Calendar Event', 'Enter a date in MMDDYYYY form', ui.ButtonSet.OK_CANCEL);

  if (response.getSelectedButton() == ui.Button.OK) {
    Logger.log('TODO: Create a Calendar Event for date %s', response.getResponseText());
    ui.alert('TODO: Create a Calendar Event for date ' + response.getResponseText());
  } else if (response.getSelectedButton() == ui.Button.CANCEL) {
   Logger.log('The user canceled the dialog.');
  } else {
   Logger.log('The user closed the dialog.');
  }
}

/** Adds a menu to the Google Sheet. */
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Menu')
      .addItem('Prompt For Date', 'promptForDate')
      .addToUi();
}
Share:
14,850
Anthony
Author by

Anthony

Updated on August 01, 2022

Comments

  • Anthony
    Anthony over 1 year

    I am making a program that requires you to ask the user for an input of a date (which I will take in through them just inputting a date through MMDDYYY form). I'm just confused on how to implement this, as my script incorporates the use of Google Calendar.

    In this site: https://developers.google.com/apps-script/reference/base/prompt-response

    They have a class called PromptResponse, which is instantiated through doing DocumentApp.getUI() or SpreadsheetApp.getUI();

    Can I do this by doing CalendarApp.getUI()? Or do I need another way?

    And if I can do it that way, for the method getResponseText(), when I call it, does it ask the user then and there (looking at the way they used it in the link)? Thanks!