JavaScript TutorialDatatypes in JavaScriptEvaluating JavaScriptFunctional JavaScriptJavaScript .postMessage() and MessageEventJavaScript AJAXJavaScript Anti-patternsJavaScript Arithmetic (Math)JavaScript ArraysJavaScript Arrow FunctionsJavaScript Async functions (async/await)JavaScript Async IteratorsJavaScript Automatic Semicolon Insertion - ASIJavaScript Battery Status APIJavaScript Behavioral Design PatternsJavaScript Binary DataJavaScript Bitwise operatorsJavaScript Bitwise Operators - Real World Examples (snippets)JavaScript BOM (Browser Object Model)JavaScript Built-in ConstantsJavaScript CallbacksJavaScript ClassesJavaScript CommentsJavaScript Comparison OperationsJavaScript ConditionsJavaScript ConsoleJavaScript Constructor functionsJavaScript Context (this)JavaScript CookiesJavaScript Creational Design PatternsJavaScript Custom ElementsJavaScript Data attributesJavaScript Data ManipulationJavaScript DateJavaScript Date ComparisonJavaScript DebuggingJavaScript Declarations and AssignmentsJavaScript Destructuring assignmentJavaScript Detecting browserJavaScript EnumerationsJavaScript Error HandlingJavaScript Escape SequencesJavaScript EventsJavaScript execCommand and contenteditableJavaScript FetchJavaScript File API, Blobs and FileReadersJavaScript Fluent APIJavaScript FunctionsJavaScript GeneratorsJavaScript GeolocationJavaScript Global error handling in browsersJavaScript HistoryJavaScript How to make iterator usable inside async callback functionJavaScript IndexedDBJavaScript InheritanceJavaScript Intervals and TimeoutsJavaScript JSONJavaScript Linters - Ensuring code qualityJavaScript LocalizationJavaScript LoopsJavaScript MapJavaScript Memory efficiencyJavaScript Method ChainingJavaScript Modals - PromptsJavaScript Modularization TechniquesJavaScript ModulesJavaScript NamespacingJavaScript Navigator ObjectJavaScript Notifications APIJavaScript ObjectsJavaScript Performance TipsJavaScript PromisesJavaScript Prototypes, objectsJavaScript ProxyJavaScript Regular expressionsJavaScript requestAnimationFrameJavaScript Reserved KeywordsJavaScript Same Origin Policy & Cross-Origin CommunicationJavaScript ScopeJavaScript ScreenJavaScript Security issuesJavaScript Selection APIJavaScript Server-sent eventsJavaScript SetJavaScript Setters and GettersJavaScript Strict modeJavaScript StringsJavaScript SymbolsJavaScript Tail Call OptimizationJavaScript Template Literals

JavaScript Modals - Prompts

From WikiOD

Syntax[edit | edit source]

  • alert( message )
  • confirm( message )
  • prompt( message [, optionalValue])
  • print()

Remarks[edit | edit source]

About User Prompts[edit | edit source]

User Prompts are methods part of the Web Application API used to invoke Browser modals requesting a user action such as confirmation or input.


Show a modal popup with a message to the user.

Requires the user to click [OK] to dismiss.

alert("Hello World");

More information below in "Using alert()".

boolean = window.confirm(message)

Show a modal popup with the provided message.

Provides [OK] and [Cancel] buttons which will respond with a boolean value true / false respectively.

confirm("Delete this comment?");

result = window.prompt(message, defaultValue)

Show a modal popup with the provided message and an input field with an optional pre-filled value.

Returns as result the user provided input value.

prompt("Enter your website address", "http://");

More information below in "Usage of prompt()".


Opens a modal with document print options.


Persistent Prompt Modal[edit | edit source]

When using prompt a user can always click Cancel and no value will be returned.

To prevent empty values and make it more persistent:

<h2>Welcome <span id="name"></span>!</h2>
// Persistent Prompt modal
var userName;
while(!userName) {
  userName = prompt("Enter your name", "");
  if(!userName) {
    alert("Please, we need your name!");
  } else {
    document.getElementById("name").innerHTML = userName;

jsFiddle demo

Confirm to Delete element[edit | edit source]

A way to use confirm() is when some UI action does some destructive changes to the page and is better accompanied by a notification and a user confirmation - like i.e. before deleting a post message:

<div id="post-102">
  <p>I like Confirm modals.</p>
  <a data-deletepost="post-102">Delete post</a>
<div id="post-103">
  <p>That's way too cool!</p>
  <a data-deletepost="post-103">Delete post</a>
// Collect all buttons
var deleteBtn = document.querySelectorAll("[data-deletepost]");

function deleteParentPost(event) {
  event.preventDefault(); // Prevent page scroll jump on anchor click

  if( confirm("Really Delete this post?") ) {
    var post = document.getElementById( this.dataset.deletepost );
    // TODO: remove that post from database
  } // else, do nothing


// Assign click event to buttons
[], function(btn) {
  btn.addEventListener("click", deleteParentPost, false);

jsFiddle demo

Usage of alert()[edit | edit source]

The alert() method of the window object displays an alert box with a specified message and an OK or Cancel button. The text of that button depends on the browser and can't be modified.


alert("Hello world!");
// Or, alternatively...
window.alert("Hello world!");


Image of alert

An alert box is often used if you want to make sure information comes through to the user.

Note: The alert box takes the focus away from the current window, and forces the browser to read the message. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed. Also it stops the further code execution, until user clicks OK. (in particular, the timers which were set with setInterval() or setTimeout() don't tick either). The alert box only works in browsers, and its design cannot be modified.

Parameter Description
message Required. Specifies the text to display in the alert box, or an object converted into a string and displayed.

Return value

alert function doesn't return any value

Usage of prompt()[edit | edit source]

Prompt will display a dialog to the user requesting their input. You can provide a message that will be placed above the text field. The return value is a string representing the input provided by the user.

var name = prompt("What's your name?");
console.log("Hello, " + name);

You can also pass prompt() a second parameter, which will be displayed as the default text in the prompt's text field.

var name = prompt('What\'s your name?', ' Name...');
console.log('Hello, ' + name);
Parameter Description
message Required. Text to display above the text field of the prompt.
default Optional. Default text to display in the text field when the prompt is displayed.