JavaScript Dialog Boxes. Here’s What You Need To Know

Posted by TotalDC

Previously we covered JavaScript Navigator, now lets learn how to create JavaScript dialog boxes.

Creating JavaScript Dialog Boxes

In JavaScript you can create dialog boxes or popups to interact with the user. You can use them to notify users or to receive users input.

There is three different types of dialog boxes – alert, confirm and prompt boxes.

Keep in mind that the appearance of these dialog boxes is determined by the operating system or browser settings and can’t be modified with the CSS. Dialog boxes are modal windows; when a dialog box is displayed the code execution stops, and resumes only after it has been dismissed.

How To Create Alert Dialog Box In JavaScript

An alert dialog box is the simplest dialog box. Basically it enables you to display a short message to the user. To do that you need to use the alert() method. You’ve already seen a lot of alert examples in the previous chapters. Let’s take a look at the example:

let message = "Hi! Click OK to continue.";
alert(message);
 
/* The following line won't execute until you dismiss previous alert */
alert("This is another random alert box.");

How To Create Confirm Dialog Box In JavaScript

A confirm dialog box allows user to confirm or cancel an action. A confirm dialog is very similar to an alert dialog but with additional Cancel button not only with the OK button.

To create this type of dialog box you need to use confirm() method. This method returns true or false depending on the user choice. That’s why its result is often assigned to a variable when it is used. Here’s how it looks:

let result = confirm("Are you sure?");
 
if(result) {
    console.log("You clicked OK button!");
} else {
    console.log("You clicked Cancel button!");
}

How To Create Prompt Dialog Box In JavaScript

The prompt dialog box is used to prompt the user to enter information. A prompt dialog box includes a text input field, an OK and a Cancel button.

For this you have to use prompt() method. This method returns the text entered in the input field if OK button is clicked and if not – null is returned. Here’s how it all looks:

let name = prompt("What's your name?");
 
if(name.length > 0 && name != "null") {
    console.log("Hi, " + name);
} else {
    console.log("User without any name");
}

Keep in mind that the value returned by the prompt() method is always a string. This means if the user enters 10 in the input field, the string “10” is returned instead of the number 10.

Therefore, if you want to use the returned value as a number you must covert it or cast to Number, like this: let age = Number(prompt(“What’s your age?”));

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: