Alerts and Confirmations in Javascript

Here's something else, give this code a try:

<html> <head> </head> <body> <script language="JavaScript"> if (confirm("Wouldn't you rather go to")) { window.location = ""; alert("Okay, it is...hang on!"); } else { alert("No Yahoo? Okay then."); } </script> </body> </html>

No code in the HEAD tag this time, because we're not using any functions. Technically, you can put a function anywhere you want for the most part, but keeping it in the HEAD tag is the easiest way to go about it.

Now, what this script does, is it waits for the page to load, and when it is, it prompts you with one of those alert boxes - only this time, in addition to the "OK" button, there's also a "Cancel" button. If you press "OK" it will redirect you to (or another URL - simply modify the url to do so). If you press "Cancel" you'll stay on that page.

This is an example of a simple JavaScript confirmation prompt. As you can imagine, this can be quite useful. Combining commands like "onClick" and this confirm prompt, you can make useful little scripts, such as a JavaScript that asks the user for a confirmation when they click the "Reset" button the form, to make sure they meant to clear the form.

Those are some of the basics of JavaScript forms and alerts - try mixing commands to achieve different effects - virtually every event handler in JavaScript can be used in some sort of conjunction with another - so go give it a try!