JavaScript Popup Boxes
In JavaScript we can create three kinds of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click “OK” to proceed.
sample code:
<html>
<head>
<script type=”text/javascript”>
function display_alert()
{
alert(”This is alert box!!”)
}
</script>
</head>
<body>
<input type=”button” onclick=”display_alert()” value=”Display alert box” />
</body>
</html>
Alert box with line breaks
<html>
<head>
<script type=”text/javascript”>
function display_alert()
{
alert(”Hello again! This is how we” + ‘\n’ + “add line breaks to an alert box!”)
}
</script>
</head>
<body>
<input type=”button” onclick=”display_alert()” value=”Display alert box” />
</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed.
If the user clicks “OK”, the box returns true. If the user clicks “Cancel”, the box returns false.
<html>
<head>
<script type=”text/javascript”>
function display_confirm()
{
var r=confirm(”Press a button”)
if (r==true)
{
document.write(”You pressed OK!”)
}
else
{
document.write(”You pressed Cancel!”)
}
}
</script>
</head>
<body>
<input type=”button” onclick=”display_confirm()” value=”Display a confirm box” />
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.
If the user clicks “OK” the box returns the input value. If the user clicks “Cancel” the box returns null.
<html>
<head>
<script type=”text/javascript”>
function display_prompt()
{
var name=prompt(”Please enter your name”,”Gary Harwell”)
if (name!=null && name!=”")
{
document.write(”Hello ” + name + “! How are you today?”)
}
}
</script>
</head>
<body>
<input type=”button” onclick=”display_prompt()” value=”Display a prompt box” />
</body>
</html>
