JavaScript Popups


Three types of message boxes can be created in JavaScript: alert boxes, confirm boxes, and prompt boxes.


Alert Box

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

When an alert box appears, the user needs to click the OK button to continue.

Syntax

window.alert("sometext");

window.alert()The method can be used directly without the window object, using thealert()method.

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 alert box">

</body>
</html>

Try it yourself »


Confirm Box

Confirm boxes are often used to verify whether to accept user actions.

When a confirm box pops up, the user can click "Confirm" or "Cancel" to confirm the user's action.

When you click "Confirm", the confirm box returns true; if you click "Cancel", the confirm box returns false.

Syntax

window.confirm("sometext");

window.confirm()The method can be used directly without the window object, using theconfirm()method.

Example

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

Try it yourself »


Prompt Box

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

When a prompt box appears, the user needs to enter a value and then click the Confirm or Cancel button to continue.

If the user clicks Confirm, the return value is the entered value. If the user clicks Cancel, the return value is null.

Syntax

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

window.prompt()The method can be used directly without the window object, using theprompt()method.

Example

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

Try it yourself »


Line Breaks

Popups use backslash + "n" (\n) to set line breaks.

Example

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

Try it yourself »
Other Extensions