Home » JavaScript » JavaScript Dialog Boxes

JavaScript Dialog Boxes

JavaScript Dialog boxes make a webpage interactive and attractive to user. They are used to give important notification to the user and also can take inputs from them. Different types of boxes provides different features and are used for various purposes. Three different types of dialog boxes are alert box, confirm box, and prompt boxes.

Three different types of dialog boxes:

  • Alert Box
  • Confirm Box
  • Prompt Box

JavaScript Alert Dialog Box

An alert dialog box displays a short message or notification to the user. It includes only an OK button. It just give some information, necessary to the user and it can be invoked at various events possible in javascript.

Note : The whole page becomes unusable whenever an alert box invokes and can become usable only after clicking the OK button.

Alert dialog boxes can be created with alert() method.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Alert Dialog Box </title>
</head>
<body>
<script>
var message = "Hello World! Click OK to continue.";
alert(message);
alert("This is another alert box.");
</script>
</body>
</html>

JavaScript Confirm Dialog Boxes

A confirm dialog box is used to ask for user confirmation over any matter. It has two buttons OK and CANCEL. If the user agrees with whatever written in the box, then he he can click on OK, and then specified action will take place. If the user disagrees, then he can click on CANCEL.

It returns a Boolean value depending on whether the user clicks OK(true) or CANCEL(false) button and then a specified action takes place.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Confirm Dialog Box </title>
</head>
<body>
<script>
var result = confirm("Are you sure?");
if(result) {
document.write("You clicked OK button!");
} else {
document.write("You clicked Cancel button!");
}
</script>
</body>
</html>

JavaScript Prompt Dialog Box

The prompt dialog box is used to get some input from the user. There are also two buttons OK and CANCEL like confirm box. It returns the text entered in the input field when the user clicks the OK, and null if user clicks the CANCEL.

A Prompt box can be created by using prompt() function.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Prompt Dialog Box </title>
</head>
<body>
<script>
var name = prompt("What's your name?");
if(name.length > 0 && name != "null") {
document.write("Hi, " + name);
} else {
document.write("Hello Anonymous!");
}
</script>
</body>
</html>

Note : Even if you enter a number in prompt box, it will be stored as a string, as it always return a string.











Follow Us: