JS Pop-up Boxes

In JS we can create three kinds of pop-up boxes :—

  • Alert box
  • Confirm box
  • Prompt box

 

1. Alert Box

An alert box is often used if we 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.

Syntax:

alert("sometext");

See coding example below:

<html>
<head>
<script type="text/javascript">
function disp_alert() {
     alert("Hello again! This is how we" + '\n' + "add line breaks to an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="disp_alert()" value="Display alert box"/>
</body>
</html>

 

2. Confirm Box

A confirm box is often used if we 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.

 

Syntax:

confirm("sometext");

See coding example below:

<html>
<head>
<script type="text/javascript">
function disp_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="disp_confirm()" value="Display a confirm box" />
</body>
</html>

 

3. Prompt Box

A prompt box is often used if we 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.

Syntax:

alert("sometext"", "defaultvalue");

See coding example below:

<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name = prompt("Please enter the subject", "JavaScript");

if (name!=null && name!="")
{
document.write("Hello " + name + "! How is the progress?");
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_prompt()" value="Display a prompt box" />
</body>
</html>