Using window.prompt()
suggest changewindow.prompt() displays a modal text-input dialog:
const answer = window.prompt("How old are you?", "");
if (answer === null) {
console.log("The user cancelled the dialog");
} else {
console.log(`Entered: ${answer}`);
}
The return value is a string when the user accepts the dialog and null when the user cancels it. An empty string can therefore mean that the user accepted without entering text; test explicitly for null.
If a number is required, validate the entire input rather than assuming Number() or parseInt() produced a usable value:
const input = window.prompt("Enter an integer:");
const value = input === null || input.trim() === "" ? NaN : Number(input);
if (!Number.isInteger(value)) {
console.log("No valid integer was provided");
}
The dialog blocks interaction with its page while it is open, and browsers may suppress it in background pages, sandboxed frames, or abusive repeated use. Prefer an HTML form or <dialog> for application interfaces that need styling, accessibility control, or reliable asynchronous behavior.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents