JavaScript Popup Alert
JavaScript Basics

JavaScript Popup Alert

JavaScript Popup Boxes

JavaScript provides three types of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box

An alert box is used to ensure that information is delivered to the user. The user must click "OK" to proceed.

Syntax

window.alert("sometext");

The window.alert() method can be called without the window prefix.

Example

alert("I am an alert box!");

Confirm Box

A confirm box is used to ask the user to verify or accept something. The user must click either "OK" or "Cancel" to proceed.

  • If the user clicks "OK", the box returns true.
  • If the user clicks "Cancel", the box returns false.
Syntax

window.confirm("sometext");

The window.confirm() method can be called without the window prefix.

Example
if (confirm("Press a button!")) {  txt = "You pressed OK!";} else {  txt = "You pressed Cancel!";}

Prompt Box

A prompt box is used to ask the user to input a value before entering a page. The user must click either "OK" or "Cancel" to proceed after entering an input value.

  • If the user clicks "OK", the box returns the input value.
  • If the user clicks "Cancel", the box returns null.
Syntax

window.prompt("sometext","defaultText");

The window.prompt() method can be called without the window prefix.

Example
let person = prompt("Please enter your name", "Harry Potter");let text;if (person == null || person == "") {  text = "User cancelled the prompt.";} else {  text = "Hello " + person + "! How are you today?";}

Line Breaks

To display line breaks inside a popup box, use a backslash followed by the character n.

Example

alert("Hello\nHow are you?");

Take a look into your desired course