JavaScript Pop-up Window


You can create three kinds of message boxes in JavaScript: an alert box, a confirmation box, and a prompt box.


Alert box

Alert boxes are often used to ensure that the user can get certain information.

When the alert box appears, the user needs to tap the ok button to proceed.

Grammar

window.alert("sometext");

window.alert() method can use the alert() method without a window object.

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
     alert("Hello, I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="Show warning box">
</body>
</html>

Try It! 


Confirmation box

Confirmation boxes are typically used to verify that user actions are accepted.

When the confirmation card pops up, the user can click "confirm" or "cancel" to determine the user action.

When you click "confirm", the confirmation box returns true, and if you click "cancel", the confirmation box returns false.

Grammar

window.confirm("sometext");

window.confirm() method can be used without a window object and directly using the confirm() method.

Example

var r=confirm("press the button");
if (r==true)
{
     x="You pressed the \"OK\" button!";
}
else
{
     x="You pressed the \"Cancel\" button!";
}

Try It! 


Prompt box

Prompt boxes are often used to prompt the user to enter a value before entering the page.

When the prompt box appears, the user needs to enter a certain value and then click the confirm or cancel button to continue the manipulation.

If the user clicks confirm, the return value is the value entered. if the user clicks cancel, the return value is null.

Grammar

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

window.prompt() method can use the prompt() method without a window object.

Example

var person=prompt("Please enter your name","Harry Potter");
if (person!=null && person!="")
{
     x="Hello "+ person + "! How do you feel today?";
     document.getElementById("demo").innerHTML=x;
}

Try It! 


Line breaks

Pop-ups use backslash + "n" (\n) to set the line break.

Example

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

Try It!