Alerts and Confirmations in Javascript

JavaScript is usually used in fairly subtle, professional ways. Ways that arn't flashy enough to make you even notice that you've just seen a JavaScript in action.

But hey, we're here to learn, so there's nothing wrong with making use of some tacky scripts just for kicks/to learn on.

<html> <head> <script language="JavaScript"> function getName() { var first = prompt("Write your first name in the box below", "First Name"); var last = prompt("Write your last name in the box below", "Last Name"); alert(first + " " + last + " - that's the name you entered, right?"); } </script> </head> <body> <b><a href="" onClick="javascript:getName(); return false;"> Enter Your Name Here</a></b> </body> </html>

So, what does this do? This produces a plain HTML page with a link titled "Enter Your Name Here" in plain view. Clicking on the link produces a JavaScript prompt so that the user can type in their first name, and then their last name. Then, the user sees an alert box with some simple text within, their name included as they entered it in the JavaScript form.

As you can see from the code above, inside the HEAD tag we have a simple JavaScript function. Inside the function, we have prompt commands that tell the script to prompt the user for some information. At the beginning of those commands, we have the simple creation of a variable, IE: "var first = ..." - obviously, in that case, the name of the variable is "first".

At the end of the function, we have a simple command:

alert(first + " " + last + " - that's the name you entered, right?");

This should be fairly self-explanatory: the "alert" command obviously produces an alert box. Inside, we have the "first" variable, then a blank space, then the "last" variable, and then the ending string of text. The first and last variables are whatever the user enters them as.

And finally: for the link, we use a simple JavaScript command to call the function in the HEAD tag, using the "onClick" event handler, which simply tells the script that when the link is clicked, it should process the code inside the onClick tag - which in this case, simply says to process the getName() function. In addition, the "return false" command is there to ignore the actual clicking of the link once it has been clicked, so that you're not actually sent to some other page.