Teach Yourself Web Publishing with HTML 4 in 21 Days

Chapter 20: Working with JavaScripts




This chapter discusses four examples of using JavaScript. Objectives for the chapter are:

  • creating a random link generator three ways
  • using JavaScript for form validation
Laura continues our lesson in JavaScript programming by creating two functions on a page that affect what a link actually jumps to. In writing a program, it is a good idea to plan what you expect to do, what tools you need to use, what tools you need to build, and what you will have when you are done.

The first method she uses to create our random link is an inline script call to a JavaScript function. She needs:

  • a function to pick a random number
  • a function to assign a link, based on the random number
  • a command to write the link on the page
  • a trigger to get the whole thing to work
Following her earlier examples, Laura puts her script inside the <head> section of the page. She uses opening and closing <script> tags, both enclosed inside the opening and closing <head> tags. Between the <script> tags, she places opening and closing HTML remark tags, to keep from bothering anyone using a browser that does not run scripts.

As an aside, I originally ran the three versions of Laura's scripts through Netscape Navigator (3 and 4) and Internet Explorer 3. They all ran the first example, but IE3 did not like her second and third versions. I recently ran her new code through IE5, and had no problems.

Back to the first program. Laura explains what she does as she goes along, so I'll make some comments on the result:

<!-- the script need to be hidden from other browsers
The line above is an opening HTML comment marker, which does what it says. Note that the remark is not closed here, it is closed after the body of the script. Then comes her picklink function.
function picklink() {
// Remember to alter linknumber so it reflects the number of links 
// you define
var linknumber = 4 ;
var linktext = "nolink.html" ;
var randomnumber = random() ;
var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;
// Add as many links as you want here
if ( linkselect == 1 )
   { linktext="http://www.netscape.com/" }
if ( linkselect == 2 )
   { linktext="http://www.webcom.com/taketwo/" }
if ( linkselect == 3 )
   { linktext="http://java.sun.com/" }
if ( linkselect == 4 )
   { linktext="http://www.realaudio.com/" }
document.write('<A href="' + linktext + '">randomly selected</A>') ;

I originally modified the code for this function slightly, to illustrate that it could follow C rules more closely. Laura has made the modifications for us in this edition.

A function is a code module, a subprogram that does a particular thing for you. This one is to pick a link to use from a short list. A function is an object. Anything that exists in memory is an object. A variable is an object, too. Before we can use an object in JavaScript, we must define it, and that is what Laura is doing here.

Inside the function, she uses four variables, and they are defined on the first four lines of the function. The first unusual one is randomnumber, which is defined as the result of running (calling) another function which she calls random(). That function has not appeared in the program yet, but that is fine. We are not running the picklink function yet, just teaching the page how to run it. We will teach the page how to run the random() function next, before we call either one.

The other unusual variable is linkselect, which is defined to be the result of a mathematical expression. What actually happens here depends on what happens in the random() function. Let's look at it:

function random() {
    var curdate = new Date();
    var work = curdate.getTime() + curdate.getDate();
    return ((work * 29 + 1) % 1-24 ) / 1024;
This function creates a variable called curdate, that is a copy of an object that the JavaScript enabled browser knows about, called Date(). Objects that are built into JavaScript, like this one, have a capitalized name. Laura knows that the Date object, and hence, her curdate variable, has built in methods called getTime() and getDate(), which she uses to put a number into the variable she calls work. She then performs some math on the value of work, in order to generate as random a number as she can. The result will be a fraction, somewhere between zero and one.

The value of the fraction generated by random() is stored in the variable called randomnumber and then that value is used in the next line:

var randomnumber = random() ;
var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;
Working from the inside of the parentheses out, we take the value of linknumber, which is the number of links Laura has to choose from, and subtract one. Then we multiply by the fraction obtained from the random() function. This will give us some number between zero and one less than the linknumber. Then we round off the number, using the Math.round() method (that our browser knows about) and add one, in case rounding led us to a zero. Now you know why people just trust random number generators, instead of figuring them out.

Laura then uses four if statements to set the value of the variable linktext. The next line is a C++ style remark, which is the style used while inside a JavaScript program. Remember, you have to shift mental gears here. C++ style remarks are used to make remarks inside a JavaScript program. HTML style remarks are used to hide the program itself from browsers that do not understand JavaScript.

The last line of the picklink function,

document.write('<A HREF="' + linktext + '">randomly selected</A>') ;

writes the link we can construct to the document we are in. I am trying to make it clearer with colors. The elements that I have shown in blue characters above are parts of the command. The elements that I have shown in red characters are actual characters that are forced into the HTML code. The yellow word on a blue background is special, it means to use the actual value currently stored in the variable. Of course, HTML code does not use color. The key here is the proper use of single and double quotes. Since we want to insert actual double quotes into the HTML code, we enclose the character strings that we want to insert (including those double quotes) inside pairs of single quotes.

How does it know to write it in the correct place? It doesn't. That is handled by the placement of the call to the picklink function in the page itself.

Visit a <script language="JavaScript">picklink()</script>
site from my list of favorites.
The function runs when the page is drawn on the screen, because the line above says to run a JavaScript function (that had better be known to the browser or defined on this page). The function ends with the command to write to the document, and it will replace the text <script language="JavaScript">picklink()</script>.

Laura's second example of how to do this is easy, if you understand the first example. This time she places a real anchor tag in her page, but places an onClick event handler in that tag. The actual URL in the HREF attribute of the anchor tag will never be used, because the onClick event handler says to run the picklink() function when the link is clicked, and to replace the URL with whatever the picklink() function selects. In addition to this change, the picklink() function itself must be modified. We no longer use the document.write method, but simply return the value of the variable linktext. A bit more elegant, and the user would be treated to a trip to a URL that is not disclosed before embarking for it. However, as noted above, this method did not work in IE3, due to a syntax difference between JavaScript and Jscript. Testing it in IE 5, I find that it works now.

The third variation Laura offers us is to declare an array to hold the choices of URLs. On pages 621 and 622, she first creates the array, then loads the elements of the array with text strings, the URLs in question. The discussion of creating the array will bother my C programmers. Trust her, she knows what she's doing.

Differences this time: Laura has not really prepared you to do much exploration in the area of constructor functions. This is a topic covered in C++, and should be left there for now. We will be content that the first two methods work well enough.

The second type of JavaScript used in the chapter is form validation. This can also be thought of as error trapping. There is nothing that will keep a user from submitting any of the forms Laura discusses in earlier chapters of this text, even if they are missing critical information. This puts a burden on the CGI script that we submit to, in that it must check whether enough information has been sent to fulfill the request. If we are creating a record in a database, we will not want to create it, and perhaps cannot create it if there is information missing. So, Laura says to make a script on the page that will check the form first, triggered by the click of the submit button.

The modification of the form begins with adapting the opening FORM tag. She inserts an event handler, onSubmit, after the ACTION parameter. This is used to call a JavaScript program that checks whether we want to submit the form. If we determine that the form is bad, we return the value "false", which halts the submission. If the form is determined to be fine, we return the value "true", which does not affect submission.

In the script, we depend on the fact that Laura has passed the form itself to the script as a parameter (an argument in parentheses). This is necessary for the program to know about any of the form objects it checks. Seems odd, that it wouldn't know, but C and C++ programs, and JavaScript programs, too, view variables as private and local, unless passed to the program. In other words, the program knows nothing about the form unless we tell it about the form.

Essentially, Laura uses two tests of data validity in her program. She first tests whether the value of the object "theName" is blank or empty. (The double pipe operator ( || ) is the standard C logical operator for OR.) If either of these conditions are true, she calls the alert() function, and passes it a message for the user.

if (thisform.theName.value == null || 
              thisform.theName.value == "" )
      alert ("Please enter your name") ;
      thisform.theName.focus() ;
      return false ;
After the alert, she sets the focus on the field that needs editing. This places the screen cursor there, aiding the user in changing the data. Finally, she returns the value "false", which prevents submission.

The second error check is to tell if any radio button in a required set has been selected. She creates a flag variable which she calls "selected". She sets its value to "false", then runs through a loop that checks the value of each of the radio buttons. If any button in the set is has been clicked, its status property will be set to "true". If she finds such a button, she sets the value of the flag to "true". At the end of the loop, she tests the value of the flag. If it is "false" she alerts the user, and returns the value "false". Why no change of focus? She can't. If you set the focus on a radio button, you have selected it, which is the same as clicking it, and that is what the user must do.

   var selected = false ;
   for ( var i = 0; i <= 2 ; ++i ) {
       if ( thisform.theSex[i].status == true )
          { selected = true }
   if ( selected == false ) {
      alert ("Please choose your sex") ;
      return false ;
   return true
As a last note, Laura discusses the construction of arrays several times in the chapter. She states that the index of an array member, like member[index], is meant to indicate its position in the array. She talks about the array constructor she demonstrates making arrays whose index numbers really start with 0, but we only use the members from index 1 on.

She left out an important point for the C students. If we create an array with four members, the index numbers of those members are 0 through 3, not 4. So, when she says we create an array whose size is four, and that we do not use the 0 index, and that we can and do use 1 through 4, she ignores the fact that she is talking about an array of FIVE members, not four. JavaScript was meant to protect the user from such realities. If it doesn't bother you, don't worry about it. Some of us, on the other hand, need to know where the magician palmed the little red ball. (And if you really want to know such things, I recommend a shop found in various casinos in Las Vegas called Houdini's Magic Shop. If you can't go there, try this link. Houdini's Magic Shop)