JavaScript Dialogue boxes

JavaScript provides three types of dialogue boxes that allows you to display messages to the user and prompt them for input: alert, confirm, and prompt.

Here's an overview of each type:

Alert box: An alert box displays a message to the user and requires them to click the OK button to dismiss it. Here's an example:

alert("Hello, world!");

This code will display an alert box with the message "Hello, world!".

Confirm box: A confirm box displays a message to the user and requires them to choose between two buttons (OK and Cancel) to confirm or cancel an action. Here's an example:

let result = confirm("Are you sure you want to delete this item?"); if (result == true) { // delete the item } 
else { // do nothing }

This code will display a confirm box with the message "Are you sure you want to delete this item?". If the user clicks OK, the confirm() function returns true, and the code in the first block is executed. If the user clicks Cancel, the function returns false, and the code in the second block is executed.

Prompt box: A prompt box displays a message to the user and prompts them to enter a value. The user can enter a value and click OK to confirm it or click Cancel to dismiss the prompt. Here's an example:

let name = prompt("Please enter your name:"); 
if (name != null) { alert("Hello, " + name + "!"); }

This code will display a prompt box with the message "Please enter your name:". If the user enters a name and clicks OK, the prompt() function returns the entered value as a string, which is then stored in the name variable. If the user clicks Cancel, the function returns null, and the code inside the if block is not executed.

Note that dialogue boxes can be useful for displaying important information or requesting user input, but they can also be disruptive and annoying if overused. Use them judiciously to provide a good user experience.

Last updated