Have you ever thought, “When my program runs, I wish I could prompt the user to type in custom text or numbers”?
For instance, instead of opening the code editor every time to rewrite text manually, wouldn’t it be so convenient if clicking a button opened a neat pop-up dialog asking, “Please enter the restaurant name you’d like to add today”? That way, even colleagues without any programming background can use your tools with ease.
In our previous lesson (Lesson 25), we covered Ui.alert() for displaying simple notification messages. Today, we’re diving into an incredibly useful method that lets you capture direct text input from your users: Ui.prompt()!
In this guide, we’ll build a practical tool to quickly add new restaurants to a personal favorite—a “Sapporo Soup Curry Tour List”—directly from an interactive prompt dialog. We will cover basic syntax, how to extract entered text, handling conditional branching when the Cancel button is pressed, and common pitfalls beginners face, explained in the clearest, most accessible way possible!
1. What Is Ui.prompt()? Understanding the Input Dialog Basics
Ui.prompt() is a Google Apps Script method that displays a pop-up dialog box equipped with a text field right on your Google Sheets screen, allowing you to capture whatever characters the user types in.
Differences Between Ui.alert() and Ui.prompt()
While both Ui.alert() (from Lesson 25) and Ui.prompt() generate pop-up modal dialogs on screen, their core purposes are distinctly different.
| Item | Ui.alert() (Alert) | Ui.prompt() (Prompt) |
| Primary Role | Show announcements or confirm actions | Prompt users to input text or numbers |
| UI Elements | Message + Buttons (OK, Cancel, etc.) | Message + Text input field + Buttons |
| Returned Data | Which button was clicked | Selected button + Entered text string |
| Analogy | Notice board (read and stamp acknowledgment) | Order form (write your name and request) |
Think of It as a “Delivery Package” (PromptResponse)
When you execute Ui.prompt(), the user interacts by typing text into the input field and clicking the OK button.
When this happens, GAS packages both the typed text and the clicked button into a single object called a PromptResponse and delivers it back to your script.
All we have to do is “open” this package in our code and inspect its contents: “Which button did they press?” and “What text did they write?”
2. STEP 1: Preparation! Setting Up the “Sapporo Soup Curry Tour List” Sheet
First, let’s prepare our practice Google Spreadsheet to interact with via GAS!
Steps
- Create a new Google Spreadsheet in your browser and name the file “Sapporo Soup Curry Tour List”.
- Rename the sheet tab at the bottom to “Chuo Ward Area”.
- Enter the following header information in Row 1:
| A | B | C | |
| 1 | Date Added | Store Name | Notes |
| 2 | 2026/09/20 | GARAKU | Rich Japanese dashi broth, absolutely delicious! |
- Once entered, leave the “Chuo Ward Area” sheet open as the active tab.
3. STEP 2: Hands-On: Running the Simplest Ui.prompt()
With our sheet ready, let’s open the GAS script editor and display the simplest possible text prompt dialog!
1. Writing the Code
From the Google Sheets menu bar, navigate to Extensions > Apps Script, clear out any template code in the editor, and paste the snippet below:
function showSimplePrompt() {
// 1. Get the Spreadsheet UI instance
var ui = SpreadsheetApp.getUi();
// 2. Display the prompt dialog and capture the result in the 'response' package
var response = ui.prompt("Please enter your recommended soup curry restaurant:");
// 3. Extract the text entered by the user
var inputText = response.getResponseText();
// 4. Output the extracted text to the log (using Logger.log from Lesson 1)
Logger.log("Entered restaurant: " + inputText);
}
2. Key Points in the Code
SpreadsheetApp.getUi(): As introduced in Lesson 25, to pop up any dialog on the active spreadsheet interface, you must first retrieve the parentUienvironment object.ui.prompt("Message"): Displays an input dialog featuring the specified prompt message.response.getResponseText(): The dedicated method to extract the text string entered into the input box by the user.
3. Save and Run
- Click Save (the floppy disk icon) at the top of the editor.
- Make sure the selected function is set to
showSimplePrompt, then click Run. - Switch back to your Google Sheets browser tab.
You’ll see a clean dialog with a text input field centered right on your screen!
Type “Ramai” into the text box and click the “OK” button in the bottom right corner.
Return to the GAS editor and inspect the Execution log. You should see output matching this:
Info Entered restaurant: Ramai
Our script smoothly captured the text entered directly by the user!
4. STEP 3: Critical Knowledge: Checking Clicked Buttons and Extracting Text
While our initial example works, it suffers from a fatal flaw for real-world usage.
If the user clicks “Cancel” without typing anything, or closes the prompt via the “X” close button at top-right, the script continues running anyway and processes blank data.
To write robust, production-ready automations, let’s master the complete syntax combining button evaluation and input extraction!
Syntax Variations for Ui.prompt() (Titles, Prompts, and Buttons)
Ui.prompt() supports three different argument patterns depending on your interface requirements:
// Pattern 1: Body prompt only (automatically includes OK / Cancel buttons)
ui.prompt("Please enter the restaurant name:");
// Pattern 2: Title + Body prompt + Button set specification
ui.prompt("New Entry", "Please enter the restaurant name:", ui.ButtonSet.OK_CANCEL);
// Pattern 3: Custom button sets (e.g., YES_NO)
ui.prompt("Confirmation", "Are you sure you want to delete this? Provide a reason:", ui.ButtonSet.YES_NO);
In everyday workplace automation, Pattern 2—which explicitly defines a title, prompt message, and clear button set—is by far the most commonly used standard.
Two Essential Methods to Unpack PromptResponse
From the returned response object, use these two core methods to retrieve your data:
response.getSelectedButton(): Identifies which button the user selected (such asui.Button.OKorui.Button.CANCEL).response.getResponseText(): Retrieves the exact text typed into the input field as a string.
Practical Code with Conditional Branching
Let’s write a script that intelligently handles user actions based on the specific button clicked.
function showPromptWithCondition() {
var ui = SpreadsheetApp.getUi();
// Display the dialog (specifying title, prompt message, and button set)
var response = ui.prompt(
"Soup Curry Restaurant Registration",
"Please enter a recommended soup curry restaurant in Sapporo:",
ui.ButtonSet.OK_CANCEL
);
// Get the clicked button
var button = response.getSelectedButton();
// Get the entered text
var text = response.getResponseText();
// Handle scenario when "OK" is clicked
if (button == ui.Button.OK) {
ui.alert("You entered '" + text + "'! Proceeding with registration.");
}
// Handle scenario when "Cancel" is clicked
else if (button == ui.Button.CANCEL) {
ui.alert("Registration was canceled.");
}
// Handle scenario when closed via the 'X' button
else {
ui.alert("Dialog was closed.");
}
}
By branching with an if statement like this, you prevent unintended logic from firing whenever a user opts out or closes the modal!
5. STEP 4: Real-World Workflow: Appending User Input into Google Sheets
Now let’s bring everything together into a practical tool that you can immediately apply to office tasks or personal side projects!
We will build a workflow that takes text input entered into the prompt dialog and automatically appends it to the last row of our spreadsheet (reviewing Lesson 7’s appendRow).
We’ll also add input validation to gracefully catch empty submissions if someone clicks OK without typing anything!
Implementation: Auto-Registration Script for New Restaurants
function registerNewStore() {
var ui = SpreadsheetApp.getUi();
// 1. Display the input prompt dialog
var response = ui.prompt(
"[Sapporo Soup Curry Tour] Add New Restaurant",
"Please enter the name of the soup curry restaurant:",
ui.ButtonSet.OK_CANCEL
);
// 2. Retrieve selected button and input text
var button = response.getSelectedButton();
var storeName = response.getResponseText();
// 3. Execute only when the OK button is clicked
if (button == ui.Button.OK) {
// [Check] Validate that input is not an empty string
if (storeName === "") {
ui.alert("⚠️ Restaurant name cannot be blank. Please enter a name and try again.");
return; // Stop execution here
}
// 4. Get active spreadsheet and sheet (reviewing Lessons 2 & 3)
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// 5. Append current timestamp and store name as an array (reviewing Lesson 7 appendRow)
var today = new Date();
sheet.appendRow([today, storeName, "Added via Ui.prompt()"]);
// 6. Display a success message (reviewing Lesson 25 Ui.alert)
ui.alert("🎉 Success", "Added '" + storeName + "' to your list!", ui.ButtonSet.OK);
} else {
// When Cancel or the 'X' button is clicked
ui.alert("Operation canceled.");
}
}
Code Explanation and How to Use It
storeName === ""checks if the user submitted an empty box. If so, an alert informs them, andreturn;terminates the function safely before corrupting your dataset.- Only when OK is clicked with valid text will
sheet.appendRow()fire, seamlessly appending the date, restaurant name, and note to the bottom row of your active sheet.
By attaching this registerNewStore function to an on-sheet clickable button (covered in Lesson 8), anyone on your team can add records with a simple click without ever touching the code!
6. Common Pitfalls: 5 Traps Beginners Encounter (and Solutions)
When working with Ui.prompt(), beginners often hit specific road bumps. Here are the top 5 mistakes and how you can sidestep them cleanly.
Trap 1: Forgetting to Call SpreadsheetApp.getUi()
// ✕ Incorrect: Causes ReferenceError (ui is undefined)
var response = Ui.prompt("Enter text");
// ◯ Correct
var ui = SpreadsheetApp.getUi();
var response = ui.prompt("Enter text");
Ui is not a global standalone object available out of the box. You must always instantiate it via SpreadsheetApp.getUi() before invoking dialog methods.
Trap 2: Forgetting getResponseText() and Printing the Object
// ✕ Incorrect
var storeName = response; // Holds the entire PromptResponse object
ui.alert("Input: " + storeName); // Displays: "Input: PromptResponse"
// ◯ Correct
var storeName = response.getResponseText(); // Extracts the actual string!
prompt() returns a PromptResponse wrapper object. To fetch the actual string entered, never forget to append .getResponseText().
Trap 3: Numeric Input Is Captured as a String
Even if a user inputs numbers like 500 into the prompt box, getResponseText() returns it as text string “500”.
If you perform addition directly, JavaScript concatenates strings: "500" + 100 yields "500100" rather than 600.
When handling numeric math, parse your string using Number() or parseInt():
var inputText = response.getResponseText();
var price = Number(inputText); // Converts string data to a numeric type!
Trap 4: Skipping Button Checks and Adding Blank Rows
If you run appendRow() without verifying getSelectedButton() == ui.Button.OK, empty records will be added whenever someone changes their mind and hits Cancel.
Make it a rule of thumb to enclose your sheet updates inside an if (button == ui.Button.OK) block!
Trap 5: Running Direct from Editor and Missing the Dialog
When you click “Run” inside the GAS editor, the dialog appears on the Google Sheet tab, not in the script console. If you stay on the script editor screen, it may appear as though execution is frozen.
Furthermore, running Ui.prompt() through time-driven triggers (like a scheduled daily run at 8 AM) will crash with an error because there is no active user session. Remember: UI prompts are strictly intended for interactive sessions where a human has the sheet open.
7. Summary & What’s Next
In this tutorial, we explored how to collect user text inputs dynamically using Ui.prompt().
Key Takeaways
Ui.prompt()displays an interactive pop-up box with an input field.- The response returns packaged as a
PromptResponseobject. - Use
response.getSelectedButton()to check whether OK or Cancel was chosen. - Use
response.getResponseText()to extract the submitted text. - Always include empty string validation (
storeName === "") and type conversion (Number()) for dependable apps.
With these techniques, your scripts are no longer one-way automations—you can now create truly engaging, two-way interactive tools that communicate with your users!
While Ui.alert() and Ui.prompt() are quick and handy, you might soon run into situations where you think: “I need a bigger input form” or “I want users to submit multiple fields (restaurant name, spice level, price) at once!”
In our next article (Lesson 27), we will explore Ui.showModalDialog(), which empowers you to build completely custom dialog interfaces using full HTML and CSS styling!
You’ll be able to build sleek, web-app-like interfaces directly inside Google Sheets, so stay tuned!
