JavaScript Popup Boxes
JavaScript provides three types of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
A pop-up box is commonly employed to ensure that important information reaches the user.
When a pop-up alert appears, the user needs to click "OK" to continue.
Syntax
window.alert("sometext");
You can use the alert() method without including the "window" prefix.
Confirm Box
A confirm box is commonly used when you need the user to confirm or agree to something.
When a message box appears, the user must choose between "OK" or "Cancel" to continue.
When you press "OK", the box shows true. When you press "Cancel", the box showsfalse.
Syntax
window.confirm("sometext");
You can use the confirm() method without typing "window." before it.
Prompt Box
A prompt box is commonly used to ask the user to enter information before accessing a webpage.
When a message box appears, the user must choose either "OK" or "Cancel" after entering a value to continue.
When the user clicks "OK," the box gives back the entered value. If the user clicks "Cancel," the box gives back null.
Syntax
window.prompt("sometext","defaultText");
You can use the prompt() method without including the "window" prefix.
Line Breaks
To make line breaks show up in a popup box, use a backslash and then the letter "n."
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p>Line-breaks in a popup box.</p>
<button onclick="alert('Hello\nHow are you?')">Try it</button>
</body>
</html>