LESSON 09 – Pop Up Messages
THREE TYPES
Javascript
supports three types of pop up messages:
·
alert
box (review)
·
confirm
box
·
prompt
box
ALERT BOX (REVIEW)
You have
already used the alert box so this will be review.
The
alert box is brought up by the alert("msg") function. The user sees the message inside a small
window and then hits OK to make the window go away.
Here is
how an Alert box looks like:
CONFIRM BOX
The
confirm box displays a message but gives the user the option to hit OK or
CANCEL. The user’s choice is stored
inside a variable.
Here is
how a Confirm box looks like:
CREATING A CONFIRM BOX
We use
the confirm("msg") function.
However, just like a math function, this function will return a value
depending on whether the use hit OK or Cancel.
If the user hits OK, the value true is returned. If the user hits Cancel, the value false is
returned.
Example:
We created the above Confirm Box using this line of code:
var ans = confirm("Hit Ok if
you are a Canadian citizen.");
Note that the variable ans would be
set to true if OK is hit. It would be
set to false if Cancel is hit.
FULL EXAMPLE 1 – CONFIRM BOX
The
following script asks the user if he/she likes hockey. An appropriate message is displayed based on
the user’s click.
<script type="text/javascript">
var x = confirm("Hit Ok if you like hockey.");
if(x==true)
{
document.write("Right on!
Hockey is awesome!");
}
else
{
document.write("You don't like hockey?");
}
</script>
Click here to see this script in action.
PROMPT BOX
We use a
prompt box to allow the user to enter information in a text field. It is a different option to the use of a
text field inside a regular form.
Here is
how a Prompt box looks like:
CREATING A PROMPT BOX
Just
like a confirm box, a prompt box returns a value to the code. The value it returns is the value that is in
the text field.
EXAMPLE
The
above Prompt box was created by the following statement:
var name = prompt("What is your name?",
"User");
Note
that the first string is what appears above your text field in the box. The second string is the text that appears
by default inside the text field.
FULL EXAMPLE 2 – PROMPT BOX
The
following script will ask the user to enter their name. It will say hello to the name.
<script type="text/javascript">
var name = prompt("What is your name?",
"User");
document.write("Hello there " + name);
</script>
Click here to see this script in action.
FULL EXAMPLE 3 – MULTIPLE PROMPT BOXES
The
following script will ask the user for his/her first name in a prompt box. It will then ask the user for his/her second
name in a second prompt box. Then, a
message will be displayed.
<script type="text/javascript">
var fname = prompt("What is your first name?",
"User");
var lname = prompt("What is your last name?",
"User");
document.write("Hello there " + fname + "
" + lname);
</script>
Click here to see this script in action.