
Lesson 2-Alert, confirm, prompt!
Ok, before we start analyzing the exact details of how to write programs in JavaScript, lets first start off with an example showing some practical uses of JavaScript. In this section, we'll take a look at:
An
introduction to a JavaScript program: the
three Basic User Interaction methods (commands) of JavaScript.
With JavaScript, you can pump into your pages some life by providing user interactions scripts. For example, you can have a box pop up asking for surfers to type in his/her name and then display it accordingly. You could also have a confirmation box that gives users a choice whether or not to proceed with a specified action, such as enter a restricted site. These are just among the endless possibilities that are out there; fortunately, there are only three methods (commands) you'll need to learn to be able to achieve all of them. The three are:
window.alert()
window.confirm()
window.prompt()
Lets look at them in detail:
The first one is:
window.alert()
This command pops up a message box displaying whatever you put in it. For example:
window.alert("My name is George. Welcome!")
As you can see, whatever you put inside the quotation marks, it will display it.
The second one is:
window.confirm()
Confirm is used to confirm a user about certain action, and
decides between two choices depending on what the user chooses.
| Click here for output: |
var x=window.confirm("Are you sure you are
ok?")
if (x)
window.alert("Good!")
else
window.alert("Too bad")
There are several concepts that are new here, and I'll go over them. First of all, "var x=" is a variable declaration; it declares a variable that will store the result of the confirm box. All variables are created this way. X will get the result, namely, "true" or "false". Then we use a "if else" statement to give the script the ability to choose between two paths, depending on whether the answer is true or false.
The third one is:
window.prompt()
Prompt is used to allow a user to enter something, and do something with that info:
| Click here for output: |
var y=window.prompt("please enter your
name")
window.alert(y)
The concept here is very similar. Store whatever the user typed in the prompt box, using y. Then display it.
Ok, having looked at the three methods (commands), let me introduce you to an alternate way of writing the methods that will not only save you some time, but will lead naturally into our next discussion.
In all our examples above, we wrote the three methods as follows:
window.alert()
window.confirm()
window.prompt()
Actually, we could ALWAYS simply write the following instead:
alert()
confirm()
prompt()
For example:
alert("this is really good on my wrist!")
The above three commands we have just gone through all have practical (and annoying sometimes) uses that I'm sure you've seen on the web. Try them out, play around with them, but don't get too close to them!