Javascript alert, confirm, and prompt boxes
Javascript provides a few popup boxes to interact with the user. More specifically, alert, confirmation, and prompt boxes.
This tutorial focuses on:
- Displaying an alert box
- Displaying a confirmation box
- Displaying a prompt box
Displaying an alert box
An alert box can be displayed using Javascript's alert() function.
Syntax:alert("Text to display in the alert box");
Example:<input type="button" onclick="alert('Hi, I am an alert box!');" value="Click here for a message" />
Displaying a confirmation box
A confirmation box is used to let the user make a choice. A confirmation box will appear will with an "OK" button and a "Cancel" button. Different actions will occur depending on what button the user clicks. You can specify this course of action with conditional logic.
A confirmation box can be displayed using Javascript's confirm() function.
Syntax:confirm("Text to display in the confirmation box");
Example:<html>
<head>
<script type="text/javascript">
function confirmGetMessage() {
//display a confirmation box asking the visitor if they want to get a message
var theAnswer = confirm("Get a message?");
//if the user presses the "OK" button display the message "Javascript is cool!!"
if (theAnswer){
alert("Javascript is cool.");
}
//otherwise display another message
else{
alert("Here is a message anyway.");
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmGetMessage()" value="Click me for some reason" />
</form>
</body>
</html>
Displaying a prompt box
A prompt box is used to get data from the user. A prompt box will appear with an "OK" button and a "Cancel" button. Different actions will occur depending on what button the user clicks. If the user clicks the "OK" button, the value entered into the prompt box will be set. If the user clicks the "Cancel" button, a null value (empty string) will be set, or a default value if you set it as the second argument in the function.
A prompt box can be displayed using Javascript's prompt() function.
Syntax:prompt("Text to display in the prompt box, "Default value");
Example:<html>
<head>
<script type="text/javascript">
function promptMessage() {
//display the prompt box to get the value from the user
var favColor = prompt("What is your favorite color?", "");
//if the user enters a value display a message in an alert box
//with the value that the user entered
if (favColor != null){
alert("Your favorite color is " + favColor);
}
//otherwise display a message informing the user that no value was entered
else {
alert("You did not specify your favorite color");
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="promptMessage()" value="Click here to specify your favorite color" />
</form>
</body>
</html>