Giving choices in alerts
Click on the link below:
When I click on this link, I get a confirm box asking me whether I want to go to the link or not. If I choose OK then the browser takes me to the link. If I click cancel I stay where I am. Here is the code:
Did you find that whole page daunting? Have you noticed that there are only a few lines of code. I have shown the whole page because some lines of Java Script are in the <head> section and other lines are in the body.
Code in the Head!
Here is the actual Java Script in the HEAD:
Firstly, you may have noted that instead of our familiar 'alert' code we now have:
Which is almost exactly the same as the alert code, except ALERT has been replaced with CONFIRM! So instead of having a message box with an OK button, you get a message box with an OK button and a CANCEL button.
Making it Functional
We can organise our code by using a function, which is the name of a set of code. In this example, we have a function called ConfirmChoice:
Functions always have the two brackets, although sometimes the brackets contain something, such as a variable. In this case they are empty. Did you notice that curly bracket? We need this and its opposite number to make clear where our function begins and ends. The next line of code is simply:
We know about the confirm bit, and answer is a variable which contains the value of the confirm. This can be "0" for CANCEL or "1" for OK. So answer has a value of 0 or 1. What the function ConfirmChoice does is determined by this code which follows it:
Firstly the ! doesn't mean the program is surprised, it means 'not'. So != means not equal to.Having got that sorted, we can read the code. So when the function ConfirmAlert is called, it will make a confirm message box asking if we really want to go to that URL. When the user clicks OK or CANCEL, the variable 'answer' has a value of 0 or 1. If it isn't 0, then the location 'index.html' will be loaded. Otherwise, it hasn't been told to do anything so it won't load anything. So if OK is clicked the Browser goes to the index page, and if CANCEL is clicked it will stay where it is and do nothing more. However, all this is in the HEAD so we haven't looked at the business end yet.
And now - the Link!
This seems like a fairly normal link. It has a character '#' because some editors don't like empty tags and mess with them. We need a tag or something to use the onClick event. We could have used an image or a form button. In this case, when we click on the text, the function ConfirmChoice() in the HEAD gets working and everything we have discussed above occurs.
A neater way to do the link is like this:
What we have learned
You can now use a confirm button!
Copyright © 1998