Introduction to Web Design - 12. JavaScript
12.1 Object Oriented Programming | 12.2 A Simple JavaScript | 12.3 The "noscript" tag | 12.4 The JavaScript Document Object Model | 12.5 JavaScript Dialog Boxes |
12.6 Data Types and Variables in JavaScript | 12.7 Decision Statements | 12.8 HTML Forms | 12.9 JavaScript Functions | 12.10 Example of HTML Form and a JavaScript |
12.11 Forms Checking | 12.12 Rollover Buttons | 12.13 Linking to an External JavaScript File | 12.14 Other JavaScript Capabililties | 12.15 Debugging Your JavaScripts
  1. Preface
  2. Markup Languages – A Definition and Some History
  3. Beginning HTML
  4. HTML Lists
  5. HTML Tables
  6. HTML - Color, Fonts and Special Characters
  7. HTML Links
  8. HTML Images
  9. HTML Frames
  10. Cascading Style Sheets
  11. MicroSoft PhotoDraw
  12. JavaScript
  13. HTML Forms and Form Handling
  14. VBScript
  15. MicroSoft FrontPage
  16. Active Server Pages
  17. Java Applets
  18. XML Meaning and More
  19. Macromedia Flash 5.0
  20. References
JavaScript is a programming language that has become the de facto standard for enhancing and adding functionality to web pages. JavaScript performs client-side scripting, making web pages more interactive. Client-side scripting means that the code works only on the user’s computer, not on the server-side.

JavaScript code is placed into web pages. The two major browsers contain JavaScript interpreters, which process and execute the code.

JavaScript and Java are not the same language. JavaScript is considered to be much simpler than Java and the languages have different syntax, keywords and conventions. Java is considered to be more powerful than JavaScript. JavaScript provides for some relatively simple user interactions. JavaScript cannot write files to either the server or the client’s computer and cannot read files from the client’s computer. JavaScript does not have graphics capabilities.

Unlike HTML, JavaScript is case sensitive. That means that it distinguishes between upper and lower case letters and considers the upper and lowercase version of the same letter to be different letters. Most JavaScript keywords use lowercase.

12.1 Object Oriented Programming

Before getting into JavaScript, it is a good idea to get a grip on the sorts of objects that this language deals with. In addition to basic data types, such as numbers, characters and strings, JavaScript deals with objects. An object can be a complex structure containing a number of values or properties or even other objects. For example, a browser window itself contains a number of other objects like an HTML document, a titlebar, a menubar, a toolbar, optional scrollbars and a statusbar along the bottom. These are all properties of the browser window object in JavaScript. Another important object in JavaScript is the web page in which the JavaScript code is embedded. The current web page is a JavaScript document object. One property of a document is the background color, bgcolor. The background color of the current web page can be accessed using “dot” notation such as document.bgcolor. The document is in turn a property of the window object and can be accessed with window.document. Because the document object is frequently referenced in JavaScript, the first part of the reference is usually omitted and one references the document object directly.

An object can also have methods and event handlers. These are functions that can access and change the properties of the object and detect user actions. One method for a document object is the write() method. Methods often have names that are or start with verbs. Note also that methods are followed by a set of parentheses which may or may not be empty, depending on the method. If the parentheses are not empty, the contents are called the ”parameters” or “arguments” of the method. Parameters provide additional information for use by the method. Methods are applied to objects with the “dot” notation. So, to use the write() method with the current document, one would write document.write(“Hello”).

12.2 A Simple JavaScript

The best way to learn any programming language is to practice it. Follow the steps below to create a webpage with a very simple JavaScript in it. Explanations of how the script works will be explained below.

  1. Open a new HTML file in Notepad and save it as “firstjscrpt.htm”. Add the following code to the file:

    
    <html>
    <head>
    <title>Simple JavaScript</title>
    
    <script type = "text/javascript" language = “javascript”>
      <!-- to hide script from old browsers
        document.write("<h2> Welcome to my first JavaScript page.</h2>");
        document.write("This doesn't seem to be too hard.<br />");
      // end of script hiding comment-->
    </script>
    	
    </head>
    
    <body >
     <p>
      Come back again sometime.
     </p>
    </body>
    </html>
    


    Before looking at the file in a browser, let’s examine the code for the script which is in the head section of the HTML file. The JavaScript code is contained within <script> … </script> tags. The type attribute in the beginning script tag specifies the MIME type of the script. Newer browsers recognize the type attribute. Older browsers used the language attribute to specify the language for the script. To be on the safe side, you can include both attributes as is done above.

    The JavaScript code is actually enclosed within an HTML comment tag. This hides the script from older browsers that don’t contain script interpreters.

    In the code above, there are two JavaScript commands. Both lines call the write() method on the current webpage using the dot notation. The write() method takes a string as an argument. Notice that each string parameter contains HTML tags. The first line contains HTML code for a level 2 heading. The second contains a line of text and a break tag. After the two lines of JavaScript code is the ending comment tag followed by the ending script tag.

    What will happen when this page is opened in a browser that can interpret scripts is this: The browser will encounter the script, and interpret it. In this case, it will execute the two commands to write to the current document. The script ends, and the browser will continue to display the remainder of the HTML page.

  2. Save the file and view it in a browser.

    Image of File in a Browser

    If you are thinking that the JavaScript code above is simply a more complicated way of displaying text on a web page than just writing HTML codes, you are correct. In order to do more interesting things with JavaScript, we have to get into more details about programming in general and JavaScript in particular.

12.3 The noscript Tag for Script-Disabled Browsers

Although they are becoming increasingly rare, there are still browsers in use that are not script-enabled. It is considered at least a courtesy to notify users of nonscript-enabled browsers that they may be missing aspects of a web page that uses scripts. This notification can be accomplished using the noscript tag which should be placed immediately after the closing script tag. For example, you may want to do the following:


<noscript>
	This page uses JavaScript.  To see the full page, please use a script-enabled browser.
</noscript>



Alternatively, you may want to use the noscript tag to direct the user to a version of the web page that does not use any JavaScript.

  • Add the noscript tags and content above immediately below the closing script tag in your file. Save the file and view it in a browser. You should not see any difference in the browser window.
  • To see the effect of the noscript tag, you can either view the web page in a non-script-enabled browser, if you have access to one, or you can disable scripts in your current browser. Options to disable scripts can be found in Preferences in Internet Explorer and under Internet Options in Netscape.

    12.4 The JavaScript Document Object Model

    As described in section 12.1, the Document Object Model (DOM) is a hierarchical abstraction representing the HTML document displayed in a browser. At the top of the hierarchy is the browser window. The document, history and location objects are one level below the window level. Under the document level, there are link, anchor and form levels.

    Older versions of Internet Explorer and Netscape had their own versions of a DOM. This meant that JavaScript that was written for one browser might not work in the other. In 2000, the W3C established a standard DOM called DOM1. The newest versions of both major browsers conform to the DOM1 standard. However, since older versions of the browsers are still in use, if you are writing JavaScript for a real-life website, you need to learn how to use all three DOMs.

    12.5 JavaScript Dialog Boxes: Alert, Prompt, and Confirm Boxes

    Dialog boxes are a means of interacting with the user by providing and collecting information. JavaScript provides three types of dialog boxes: the alert box, the prompt box and the confirm box.

    The alert box is the simplest dialog box. It presents a message to the user and includes a single “OK” button. The alert box is a method of the window object and takes one parameter, a string which appears as the message in the box. As mentioned above, the reference to the window can be omitted, so the following are equivalent statements.

    window.alert(“You are about to start the game.”);
    
    alert(“You are about to start the game.”);
    
    


    The confirm box can be used to let the user answer questions. This box provides two buttons: an “OK” button and a “Cancel” button. It also takes one string parameter which appears as a message in the box.

    window.confirm(“Do you want to start the game?”);
    
    confirm(“Do you want to start the game?”);
    
    


    The prompt box allows the user to enter text into a text box. This box provides an “OK” buttong and a “Cancel” button and text input box. This box also takes a string parameter which appears as a prompt in the box, telling the user what should be entered into the text box.

    window.prompt(“Enter your first name:”);
    
    prompt(“Enter your first name:”);
    
    


    1. Add commands for each type of dialog box within the script tags of your file.
    2. Save the file and view it in a browser. Make sure that you know the difference between each of these dialog windows.

    12.6 Data Types and Variables in JavaScript

    The dialog boxes above aren’t very interesting or useful on their own. In order to make them more useful, we should respond meaningfully to the user response to each of the dialog boxes. For example, we might want to use the user’s name in the web page to make it seem more personal. In order to do this, we need to save the user response to the dialog box so that we can do something appropriate with it. We can save user responses and/or other values in variables. Variables are used in all programming languages to store values so that the program can use them later. In order to use a variable in JavaScript, we must first declare the variable. The following line declare variables for three variables with the names, num1, num2 and sum.

    var num1, num2, sum;
    


    The names for the variables are chosen by the programmer. It is a good idea to choose variable names that are meaningful. In addition, there are some rules for variable names. First, you should keep in mind that JavaScript is case-sensitive. That means that “num1” is not the same variable as “Num1”, even though each is a valid variable name in JavaScript. Second, variable names can only be made up of letters, numbers and the underscore character, “_”.

    Declaring a variable causes the computer to reserve some memory to store the value. Whenever we want to access that memory location, to store or retrieve a value, we just use the name of the variable.

    We can store values in the memory location using the assignment operator which is the equal sign, “=”. The following lines store the value 5 in the memory space called “num1” and the value 3 in the memory space called “num2”.

    num1 = 5;
    num2 = 3;
    


    We can add the two stored values together and store them in the memory space called “sum” with the following line”

    sum = num1 + num2;
    


    What happens when this line is executed is that the value stored in num1 is retrieved, the value stored in num2 is retrieved, the two values are added together and the result is stored in the variable, sum. This example demonstrates a number of important notions. One is a math operation, which, in this case, is addition. The other standard math operations, subtraction, multiplication and division, are available and are represented by ‘-‘, ‘*’ and ‘/’ respectively. Another important notion to grasp here is that when using the assignment operator, ‘=’, it has a different meaning than it does in math. In programming languages, it does not mean “equals”. In programming languages, it performs an operation. Finally, it is important to note that any operation on the right hand side of the assignment operator will be performed before the assignment operation takes place. In this example, it means that the variable “sum” gets the result of the addition operation on num1 and num2.

    The values 5 and 3 are examples of integer data. The four basic types of data used in JavaScript are”
    • Integer - the basic counting number, positive and negative. Integer values have no decimal portions. 1, 4, 10000 and -345 are examples of integer data.
    • Floating point number - these are numbers that have a fractional portion expressed with a decimal point. 3.25, 0.0001 and 12345.01 are examples of floating point data.
    • String - text enclosed in quotation marks. A string can consist of one character or a whole sentence or paragraph. “b”, “This is a string.” and “500” are examples of string data.
    • Boolean - this data type can only hold the words true or false or the number 0 to represent false and a number 1 to represent true.


    Unlike many other programming languages, JavaScript uses loose data-typing. This means that the type of value that will be used with any variable is not needed in the variable declarations. This means that any type of value can be assigned to any variable at any time and it is up to you, the programmer, to keep things straight and not accidentally try to perform a mathematical operation on non-numeric values.

    The following lines declare four variables and assign values of different types to each:

    var num1, num2, message, response;
    
    num1 = 4;
    num2 = 3.25;
    message = “Error: please enter your area code”;
    response = true;
    


    Now that we can store values, we can do a number of things with them. As we saw above, we can use variables that have numeric value in math operations to get new values. We can also print out the values of variables by passing them as arguments to functions or methods. For example, the following lines write the values of num1, num2 and sum to the current document.

        document.write("The first number is ");
        document.write(num1);
        document.write("<br />");
        document.write("The second number is ");
        document.write(num2);
        document.write("<br />");
        document.write("The sum of the two numbers is ");
        document.write(sum);
        document.write("<br />");
    


    We could eliminate some of the calls to the write() method by using the concatenation operator, ‘+’. The lines below will provide exactly the same output as those above.

        document.write("The first number is " + num1 + "<br />");
        document.write("The second number is " + num2 + "<br />");
        document.write("The sum of the two numbers is " + sum + "<br />");
    


    Note that the syntax for the concatenation operator requires a string or a variable on both sides of the operator. Look at the following line:

    document.write(num1 + " + " + num2 + " is " + answer + "<br />");
    


    There are six items being concatenated to form the parameter to the write() method. It looks a bit confusing because one of the items being concatenated is a string with a plus sign in it. For clarification, the six items are:
    • num1
    • " + "
    • num2
    • " is "
    • sum
    • "<br />"
    1. Start a new HTML file in Notepad and save it as “jscript2.htm” .
    2. Add the beginning and closing tags for the head and the body sections. In the head section add the following enclosed in script tags:

       var num1, num2, sum;
      
      num1 = 4;
      num2 = 3.25;
      sum = num1 + num2;
      
      document.write("The first number is " + num1 + "<br />");
      document.write("The second number is " + num2 + "<br />");
      document.write("The sum of the two numbers is " + sum + "<br />");
      


    3. Save the file and view it in a browser.

      Image of File in a Browser

      We can use a string variable instead of a string as the parameter in a dialog box statement. For example, assuming that the variable message had been declared and assigned the value as below, we could create a dialog box as follows:

      var message;
      message = “Error: please enter your area code”;
      alert(message);
      


    4. Save your file as “jscript3.htm” and replace the code in the script with the code above. Save the file and view it in a browser.

      We can also store user responses from the dialog boxes in variables using the assignment operator. For example, the following prompts the users for their first name with a prompt box, stores the user entry in the variable username, prints a greeting with an alert box, and then prints the same greeting to the current document.

      var username;
      username = prompt("Enter your first name:");
      alert("Hello, " + username);
      document.write("Hello, " + username);
      


    5. Save your file as “jscript4.htm” and replace the code in the script with the code above. Save the file and view it in a browser.

      There is a slight complication if we want the user to enter a numeric value into a prompt text box. The complication is that all values returned from prompt window are returned as strings. If we want to perform math operations on these values, we have to convert them from string type to integer or floating point types. We can accomplish this with the parseInt(); or parseFloat(); functions, as shown by the following example:

      var response, numquarters, numpennies, sum;
      
      response = prompt(“How many quarters do you have?”);
      numquarters = parseInt(response);
      
      response = prompt(“How many pennies do you have?”);
      numpennies = parseFloat(response);
      
      sum = 0.25 * numquarters + numpennies * 0.01;
      
      alert(“The value of your quarters and pennies is “ + sum);
      


    6. Save your file as “jscript5.htm” and replace the code in the script with the code above. Save the file and view it in a browser.

    12.7 Decision Statements

    We could still run into problems if the user either does not enter anything into the prompt box, or enters something other than a number. If that occurs, the parseInt() and parseFloat() functions will return a special value, NaN, which stands for “not a number”. We can then check to see if NaN has been returned before trying to perform any math operations on the values. We can use the isNaN() function. This function will return true if the value provided as a parameter is NaN. For example, the code below checks to see if the first value entered by the user is not a number. If it is not, an error message is given to the user. If it is a number, the prompt for the next box is shown and the calculation is performed.

    response = prompt(“How many quarters do you have?”);
    numquarters = parseInt(response);
    
    if(isNaN(numquarters))
    {
       alert("The total of your coins cannot be calculated \n" +
       " because you didn’t enter a number for the number \n" +
       " of quarters. \n" + 
       "You can reload the page and start again, if you like.");
    }
    else
    {
       response = prompt(“How many pennies do you have?”);
       numpennies = parseFloat(response);
       sum = 0.25 * numquarters + numpennies * 0.01;
       alert(“The value of your quarters and pennies is “ + sum);
    }
    


    This code introduces a new structure, the if statement. Before getting into the if statement, there is another new concept introduced in this code. In the first alert box that informs the user of erroneous input entered for the number of quarters, the parameter for the alert box consists of a number of strings concatenated together. This is done instead of having one long string because if the string is too long, it will not fit into the editor window. If the string is broken over more than one line, JavaScript will not interpret it correctly. However, it will interpret concatenation that is spread over more than one line. The strings also contain a sequence of two characters ‘\n’. This is called an escape sequence that introduces a newline or line break into the string. This is important in this case because the string displayed in the alert box is so long, all of it might not fit on the screen if displayed in one long line.

    Now, onto the if statement.
    11.7.1 The if statement
    Up to this point in this tutorial, the statements we have included in between script tags were executed in sequence, one after the other. The if statement allows us to write two sequences of code, one of which will be executed if a certain condition is true and the other which will be executed if the condition is false. The condition in this example is a call to the function isNaN() with the value returned by the parseInt() function on the user input for the number of quarters.

    If the value entered by the user was “not a number”, the isNaN() function will return true. If the condition of an if statement is true, the statements following the condition will be executed. If there is more than one statement to be executed when the condition is true, they must be grouped together by curly brackets, {…}. If there is only one statement to be executed, the curly brackets can be omitted. However, since the if statement can fail to work correctly if there is more than one statement and the curly brackets are omitted, they can always be included without a problem. In this example, when the condition is true, there is only one statement that will be executed, even though that statement extends over more than one line. When the condition on the if statement is false, the alternate set of statements will be executed. In this case, we prompt the user for the number of pennies and perform a calculation.

    The general form of the if statements is

    if( some condition )
    {
        statements to be executed when condition is true
    }
    else
    {
        statements to be executed when condition is false
    }
    
    


    1. Enter the code above for calculating the value of quarters and pennies enclosed in script tags and save the file as “jscript6.htm”. Save the file and view it in a browser.
    2. Try entering a letter in for the number of the quarters. You should get an alert box with the error message.
    3. Notice how the text in the error message alert box is broken into four separate lines by the line break escape characters (\n) in the string parameter to the alert box.
    4. Reload the page and this time, enter in a number for the number of quarters. Enter a number for the number of quarters. You should get a prompt for the number of pennies and then the value of the coins. Make sure that the calculation is correct.

      Many times, the condition for an if statement is a comparison between two values. For example, the code below displays a prompt box that asks the user if they are thinking of something that is an animal, vegetable or mineral. It then compares the user input to those strings and displays another prompt box with another question. The comparison is done with the equals operator, ‘==’. Care must be taken not to use the assignment operator, ‘=’, instead of the equals operator. Other comparisons that can be used are not-equal, ‘!=’, greater than, ‘>’, greater than or equal, ‘>=’, less than, ‘<’, and less than or equal to, ‘<=’.

      var category;
      
      category = 
        prompt(“Think of an object. \n Is it animal, vegetable or mineral?”);
      
      if(category == “animal”)
      {	prompt(“Is it a dog?”);}
      else if(category == “vegetable”)
      {	prompt(“Is it a carrot?”);}
      else if(category == “mineral”)
      {	prompt(“Is it a diamond?”);}
      else
      {	prompt(“Is it an intangible object?”);}
      


    5. Enter the code above for guessing the object, enclosed in script tags and save the file as “jscript8.htm”. Save the file and view it in a browser.
    6. To thoroughly check this code, you should run it at least four times: once answering “animal”, once answering “vegetable”, once answering “mineral” and once entering in anything else.

      Any condition can be combined with any other condition to create compound conditions using the logic operators: AND, ‘&&’, OR, ‘||’ and NOT, ‘!’.

      if((category == “vegetable”) || (category == “mineral”))
      {	prompt(“Is it green?”);}
      


      11.7.2 The switch statement
      If a choice needs to be made between several discreet values, the switch statement can be used instead of nested if statements. The JavaScript switch statement is very similar in syntax to the C++ switch statement, but is more versatile than the C++ version because it is not limited to integer or Boolean values for the variable. The general form of the switch statement is :

      switch(variable)
      {
        case value1:
      	statement;
      	…
      	break;
        case value2:
      	statement;
      	…
      	break;
        …
        default: 
      	statement;
      	…
      }
      


      The first line of the switch statement has the word “switch”, followed by a variable in parentheses. The variable can be of any type except null or undefined. That means it can have a numeric or string value. The variable will be compared to the value following each “case” word in the curly braces. More than one case/value pair can be used for one set of statements (see the example below). When the switch statement executes, if the value of the variable matches the value in a case, the statements following will be executed until the break statement. When the break statement is encountered, the remaining statements in the curly braces are ignored. If the break statement is omitted, execution will continue through the curly braces, which is probably not desired. The default case statements, which is optional, will be executed if the variable value does not match any of the cases. The default case statements do not need a break statement, since they are at the end of the switch statement anyway.

      var operation, num1, num2;
      
      operation = 
         prompt(“Do you wish to \n 1.add\n 2.subtract”);
      num1 = 
         parseFloat(prompt(“Enter in the first number”));
      num2 = 
         parseFloat(prompt(“Enter in the second number”));
      
      switch(operation)
      {
        case “1”: case “add”: case “+”:
      	alert(num1 + “ + “ + num2 + “ is “ + (num1 + num2));
      	break;
        case “2”: case “subtract”: case “-“:
      	alert(num1 + “ - “ + num2 + “ is “ + (num1 - num2));
      	break;
        default: 
      	alert(“I can only add and subtract.”);
      }
      


      12.8 HTML Forms and JavaScripts

      The JavaScript prompt windows that we have seen so far have limited usefulness because they can accept only one piece of data at a time. HTML forms allow us to put any number of different types of input devices on a web page. As we have seen, JavaScript can be used to check for appropriate user input in web page forms and to perform other actions based upon user input. Now that we have seen how to use the if statement, it is easy to imagine how this can be accomplished. But first, we need to look at the HTML necessary to create an HTML form.

      An HTML form must be enclosed within <form> … </form> tags. The form tag takes a name attribute, so that we can refer to the form by that name in a script. For example,

      <form name = "coins">
        …
      </form>
      


      Within the form tags, we can put instructions or prompts to the user, which are in HTML text. But most importantly, we can use form elements like text boxes, selection lists, check boxes, radio boxes and buttons to get input from the user. This is done using the <input> … </input>, <textarea> … </textarea>, <select> … </select> tags.

      The input tag can be used to The beginning input tag takes a number of attributes. Each input element should be given a name, with the name attribute. Each input element must use the type attribute to determine what it is. Possibly values for the type attribute are “text”, “checkbox”, “radio”, “button”, “reset”, and “submit”.

      A type attribute value of “text” provides a small text area for the user to type in. The “checkbox” value provides a small square box that the user can check or un-check to indicate a choice. The “radio” value provides a small circle that the user can check or uncheck. However, radio boxes usually occur in groups in which only one can be selected at any time. This is accomplished by giving all of the radio boxes the same name. A “button” value creates a button with a label that can invoke some action. The “reset” and “submit” buttons are fairly self-explanatory. More will be said about submitting forms in a later section of these web pages. For example, the lines below will print the line of text asking the user to enter a first name. On the same line will be a text box that the user can type in text. The size attribute limits the size of the box to the size of 12 letters. The value attribute sets the initial value to an empty string (the text box will be blank initially).

      Enter your first name:
        <input type = "text" 
      	name = "firstname" 
      	size = 12 
      	value = "">
        <br />
      


      Checkboxes are boxes that can be marked as checked or unchecked and are often used to set or unset options. Checkboxes are created with the <input> tag and a type attribute of “checkbox”. The name attribute is used to identify the check box. Text after the checkbox indicates the yes/no choice for the user. The checked attribute is set to true if the box is checked. The prompt below asks the user to check what types of coins the user has. The unchecked property will ensure that the checkboxes will be unchecked when first displayed to the user.

      What types of coins do you have?
        <br />
        <input type = "checkbox" 
      	name = "pennies" unchecked > Pennies<br />
        <input type = "checkbox" 
      	name = "nickels" unchecked> Nickels<br />
        <input type = "checkbox" 
      	name = "dimes" unchecked> Dimes<br />
        <input type = "checkbox" 
      	name = "quarters" unchecked> Quarters<br />
      


      While checkboxes might occur alone, radio buttons occur in groups or sets. A set of radio buttons will allow only one choice to be checked out of the set. Radio buttons are created using the <input> tag with a type attribute of “radio”. The set of radio buttons is identified with the name attribute. That is, all of the radio buttons in the set must have the same name. Each choice in the set is identified by the name and an index number. In the example below, the first radio button will be referred to as gender[0]. The numbering begins with zero, which is consistent with the index values for arrays in many programming languages.

      Gender:
        <input type = "radio" name = "gender" value = false> Female
        <input type = "radio" name = "gender" value = false> Male	
        <br />
      


      A Reset button is a button that resets all of the form elements to their default values. Reset buttons are created with the <input> tag and a type attribute value of “reset”.

      <input type = "reset">
      


      Submit buttons send the form data to the server. How the server might deal with the form data will discussed in a later section. For now, just know that submit buttons are created with <input> tags and a type attribute value of “submit”. The value attribute string will appear as text on the button.

      <input type = “submit” value = “Submit Order”>
      


      The textarea tag is used to create multiple line text boxes and can display multiple paragraphs of text. Scrollbars will appear if the text inside the box exceeds the size of the text to be displayed. For example, the lines below prompt the user for an explanation. The beginning textarea tag has a name attribute and the size defined by rows and columns. The initial text in the textarea will be the sentence within the textarea tags.

      In 100 words or less, explain the problem 
      	you are having with the unit. <br />
      <textarea name = “problem” rows = 5 cols = 60> 
      	Type the explanation of the problem here 
      </textarea>
      


      The select tag is used to provide the user with a list of choices. The list of selections can be set to allow the user to choose only one or multiple choices from the list.

      Choose a vacation destination from the list: <br />
      <select name = “destination” size = 5>
      <option name = “dest1” value = “LON”> London </option>
      <option name = “dest2” value = “NYC”> New York City </option>
      <option name = “dest3” value = “PAR”> Paris </option>
      <option name = “dest4” value = “MUN”> Munich </option>
      <option name = “dest5” value = “HON”> Honolulu </option>
      </select>
      


      The example in the following section on JavaScript functions provides examples of using form elements in JavaScript code to interact with the user.

      12.9 JavaScript Functions

      Functions provide a means of grouping sections of related code together. Functions are given names and can be called at any time. Functions can take parameters (or arguments) just as the methods or functions such as isNaN() that we saw above. Functions can also return values. For example, the isNaN() function returns true or false depending upon whether the value given as the parameter is or is not a number. The statements in a function are not executed until the function is called.

      Functions are defined within script tags by using the word “function”, followed by a function name you choose. The function name should be meaningful and indicate what the function does. The name is followed by a set of parentheses. Inside the parentheses are list of the function parameters or input to the function. The function statements follow, enclosed in a set of curly braces. Here is an example of a very simple function:

      function welcome(name)
      {
       document.write(“Hello, “ + name + “<br /> Welcome! <br />”);
      }
      


      This function is called “welcome”. It takes one parameter called "name" which is used in the function statement enclosed in curly braces.

      To call the function, use the name of the function, followed by a set of parentheses which contain the correct number of parameters. Note that if the function takes more than one parameter, they must be in the correct order. Here is an example of calling the “welcome” function:

      var firstname;
      
      firstname = prompt(“please enter your first name”);
      welcome(firstname);
      


      Note that the variable used in the function call does not have the same name as the parameter in the function definition.
      1. Create a new HTML file called “jscript9.htm”. In the head section of the file put the following Javascript code that contains a function definition and a call to the function.

        <script type = "text/javascript">
          <!--
            /* here is the function definition*/
            function welcome(name)
            {
               document.write(“Hello, “ + name + 
                 “<br /> Welcome! <br />”);
            }
        
           var firstname;
        
           firstname = prompt(“please enter your first name”);
           /* here is the function call*/
           welcome(firstname);    
          // -->
        </script>
        


      2. Save the file and view it in a browser. Note that the function definition comes before the function call. Note also that comments in JavaScript begin with ‘/*’ and end with ‘*/’.
      3. Now, delete the call to the function. Save the file and view it in a browser. Note that the prompt for the user name appears, but no message is written to the document. The statements in the function are not executed unless the function is called.

      12.10 A Complete Example of an HTML form and a JavaScript Function

      Below is a longer more complex example of an HTML form and a JavaScript function. Both are more complicated than the previous examples. Examine the code below and then read the discussion following it. The line numbers in the file are there so that specific lines can be referred to in the discussion below the code. They should be not included in an actual HTML file.

      1.	<?xml version = "1.0"?>
      
      2.	<!DOCTYPE html PUBLIC
      "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
      
      3.	<html xmlns="http://www.w3.org/1999/xhtml">
      
      4.	<head>
      5.	<title>Simple JavaScript</title>
      
      6.	<script type = "text/javascript" language = "javascript">
      7.	<!--
      
      8.	function calculate_coins()
      9.	{
      10.	var firstname, lastname, title;  /*user information*/
      
      11.      /*number of each type of coin*/
      12.	var numquarters, numdimes, numnickels, numpennies; 
      
      13.      /*Boolean variables that determine whether user has
      14.	a particular type of coin*/
      15.	var hasquarters, hasdimes, hasnickels, haspennies; 
      
      16.      firstname = document.coins.firstname.value;
      17.	if(firstname == "")
      18.	   {alert("You didn’t enter your first name.");}
      19.	lastname = document.coins.lastname.value;
      20.	if(firstname == "")
      21.	   {alert("You didn’t enter your last name.");}
      22.	if(document.coins.gender[0].checked == true)
      23.	  {title = "Ms.";}
      24.	else
      25.	  {title = "Mr.";}
      
      
      26.      if(document.coins.pennies.checked == true)
      27.	   numpennies = parseInt(document.coins.npennies.value);
      28.	else
      29.	   numpennies = 0;
      
      30.      if(document.coins.nickels.checked == true)
      31.	   numnickels = parseInt(document.coins.nnickels.value);
      32.	else
      33.	   numnickels = 0;
      
      34.      if(document.coins.dimes.checked == true)
      35.	   numdimes = parseInt(document.coins.ndimes.value);
      36.	else
      37.	   numdimes = 0;
      
      38.      if(document.coins.quarters.checked == true)
      39.	   numquarters = document.coins.nquarters.value;
      40.	else
      41.	   numquarters = 0;
      
      42.      if(isNaN(numpennies) || isNaN(numnickels) || isNaN(numdimes)
         || isNaN(numquarters))
      43.      {
      44.	   alert("One of the values you entered for the number of coins \n" + "
      			" is invalid.  Please correct the value and click the button again.");
      45.	}
      46.	else
      47.	{  document.coins.result.value = "$" + 
                  ((numquarters*0.25) + (numdimes*0.10) + (numnickels*0.05) + 
                        (numpennies*0.01));
      
      48.      alert("Thank you " + title +
      " " + firstname + " " + lastname +
      " for using the Coin Calculator.");
      49.      }
      
      50.      } /*end of function*/
      51.	// -->
      52.	</script>
      
      53.      <noscript>
      54.	This page uses JavaScript.  To see the full page, please use a script-enabled browser.
      55.	</noscript>
      56.	</head>
      
      57.      <body >
      
      58.      <form name = "coins">
      59.	Enter your first name:
      60.	<input type = "text" name = "firstname" size = 12 value = "">
      61.	<br />
      62.	Enter your last name:
      63.	<input type = "text" name = "lastname" size = 25 value = "">
      64.	<br />
      65.	Gender:
      66.	<input type = "radio" name = "gender" value = false> Female
      67.	<input type = "radio" name = "gender" value = false> Male	
      68.	<br />
      69.	What types of coins do you have?
      70.	<br />
      71.      <input type = "checkbox" name = "pennies" unchecked  onclick = 
      72.             "window.status = 'Pennies' "> Pennies<br />
      73.      <input type = "checkbox" name = "nickels" unchecked onclick = 
      74.             "document.bgColor = '#9f9f9f' ""> Nickels<br />
      75.      <input type = "checkbox" name = "dimes" unchecked onclick = 
      76.             "document.fgColor = 'purple' "> Dimes<br />
      77.      <input type = "checkbox" name = "quarters" unchecked onclick = 
      78.            "document.title = 'Coin Calculator' "> Quarters<br />
      
      79.      Number of Pennies: 
      80.	<input type = "text" name = "npennies" value = "" size = 6><br />
      81.	Number of Nickels: 
      82.	<input type = "text" name = "nnickels" value = "" size = 6 ><br />
      83.	Number of Dimes: 
      84.	<input type = "text" name = "ndimes" value = "" size = 6> br />
      85.	Number of Quarters: 
      86.	<input type = "text" name = "nquarters" value = "" size = 6><br />< br />
      
      87.      Click the button to calculate the value of the coins.  <br />
      88.	<input type = "button" name = "calcbutton" 
                    value = "Calculate Value" 
              onclick ="calculate_coins()"> 
      89.      <br /> <br />
      90.	<input type = "text" name = "result" size = 10 value = "$0.00">
      
      91.      <br />
      92.	<br />
      93.	<input type = "reset">
      
      </form>
      </body>
      </html>
      


      The function named “calculate_coins” will be discussed in detail below, but notice that the entire script in the head section of the document is composed of the function definition and that there no call to the function within the script. The function is called when the user clicks on the “calcbutton” in the form.

      Find the beginning of the form in the body section of the file on line 58. Lines 59 through 64 prompt the user for his first and last name and provide text boxes for the input.

      Lines 65 - 68 implement 2 radio buttons for the user to indicate her gender. Recall that radio buttons are grouped together in a set by virtue of having the same name. These buttons both have the name “gender”. When a user clicks one, the other will automatically be unchecked since only one of a set of radio buttons can be checked at any time.

      Lines 69 through 78 implement four checkboxes. Checkboxes are independent boxes and implement user choices by being checked or unchecked. These particular checkboxes implement a change in other form components when they are clicked by including the onclick attribute. The changes implemented have nothing to do with the goal of this webpage. They are included here to demonstrate some aspects of the document that can be changed using JavaScript. The first changes the text in the status bar of the document. The status bar is located at the very bottom of the browser window.

      Lines 79 - 86 put prompts and text boxes for the user to input the number of the four types of coins.

      Line 88 creates a button with the text “Calculate Value” on it. When this button is clicked, the function “calculate_coins” will be called.

      Line 90 is a text box that will contain the value of the coins after the calcbutton is clicked.

      Line 93 is a reset button that resets all of the values in the form.

      Now, let’s look at the “calculate_coins” function defined in the head section of this file. The function definition begins on line 8. This function takes no parameters, so the parentheses following the name are empty. However, the parentheses must always be included.

      Lines 10 - 15 declare variables that will be used in the function. Note the comments accompanying the variable declarations to indicate how they are used. This is useful here particularly because there are so many variables being declared.

      Line 16 sets the value of the function variable firstname to the value of the text box of the same name in the form coins. Notice that in order to retrieve the value of the text box, we must refer to the value property of the text box, firstname, which is a component of the form, coins, which is a component of the current document.

      Lines 17 and 18 are an if statement that checks for entry of the user’s firstname and prints an error message if nothing was entered in that field.

      Lines 19 through 21 repeat lines 16 through 18 for the user’s lastname.

      Lines 22 through 25 set the value for the function variable, title, based upon the value of the radio buttons in the set named “gender” in the form. Notice that the first radio button is referred to as document.coins.gender[0]. The condition of the if statement in line 22 compares the checked property of this button to true. If the user has checked this button, the title variable is set to “Ms.”; otherwise it is set to “Mr.”.

      Lines 26 through 29 contains an if statement that sets the value of the variable numpennies, based on whether the Pennies checkbox has been checked. If it has, the value of the npennies text box is retrieved, converted from a string to an integer with the parseInt() function and assigned to the numpennies variable. Otherwise the variable is set to zero.

      Lines 30 through 41 perform the same actions for the number of nickels, dimes and quarters.

      Lines 42 through 47 check that all of the values for the numbers of coins are numbers. If any are not numbers, an error message is given to the user with an alert box. If they are numbers, the calculation for the total value is performed and assigned to the value of the result text box.

      The function ends with an alert box that thanks the user by name for using this page. See example file coinform.htm .

      It should appear as follows:

      Image of Form in a Browser

      12.11 Forms Checking

      JavaScript is often used to check user input into forms before the data is sent to the server to be processed. As seen in the example above, the numbers for the coins are checked to make sure that the user has entered numeric values before the calculation is performed. The same sort of checks can be performed by JavaScript code before sending form data to the server. For example, you may want to make sure that the user has entered in information into text boxes by comparing the value of the textboxes to the empty string (“”). If the user has not entered information into a textbox, an alert box can remind the user to fill in the information.

      12.12 Rollover Buttons

      When the user moves the mouse cursor over a rollover button (a button implemented with an image) the button changes its appearance. This is done by replacing the original image with another image. Rollover buttons use the onmouseover and onmouseout events. The onmouseover event sets the display to the alternate image. The onmouseout event resets the display to the original image. This example also uses the onclick event to display an alert box when the user clicks the image. Notice that the onmouseover, onmouseout and onclick events take string as values. These strings contain JavaScript code. Inside of these strings, string need to be represent for the image src attribute and the parameter for the alert box. These inner strings use single quotes instead of double quotes. If double quotes were used, the computer would interpret the first double quote of the inner string to be the ending double quote of the outer string.

      <html>
      <head>
        <title> A simple rollover event </title>
      </head>
      <body>
      <img src = "images/clickme.gif" 
           onmouseover = "document.images[0].src = 'images/clickmenow.gif';" 
           onmouseout = "document.images[0].src = 'images/clickme.gif';"
           onclick = "alert('very good');">
      </body>
      </html>
      


      You can use the onmouseover and onmouseout events with links, image maps and images.

      See the example file rollover.htm.

      It should appear initially as:

      Image of Button in a Browser

      If you place the mouse cursor over the button, it should appear as:

      Image of Button in a Browser

      12.13 Linking to an External JavaScript File

      Script code does not need to be written in the head section of an HTML document. The JavaScript code can exist in a separate file. The <script> tag still must be in the head section of the document, but the beginning script tag can include an src attribute. The value of this attribute is the URL of the file containing the script code. The script tags are not included in the external file containing the code. Only the code statements need to be included in this file. For example, we could place the following function definition in a separate file called “welcome.js” (JavaScript code files typically have a js extension).

      function welcome()
      {
         var name;
      
         name = prompt("please enter your first name"); 
         document.write("Hello, " + name + "<br /> Welcome! <br />");
      }
      


      Then in an HTML file, we include the filename as the src attribute of the script tag in the head section of the file. The function is called when the image in the body section of the file is clicked.

      <html>
      <head>
      <title> A simple exteranl code example </title>
      <script type = "text/javascript" src = "welcome.js">
      </script>	
      </head>
      <body>
      <img src = "images/clickme.gif" 
           onmouseover = "document.images[0].src = 'images/clickmenow.gif';" 
           onmouseout = "document.images[0].src = 'images/clickme.gif';"
           onclick = "welcome();">
      </body>
      </html>
      


      12.14 Other JavaScript Capabilities

      12.14.1 Window and Document Objects
      Not all window and document properties have been discussed above. In general, JavaScript allows access to most document properties either directly or via methods. The window object has other properties including history and location that can be accessed. The document object includes a hierarchical structure containing the elements in the HTML pages that facilitates access to those elements.

      New browser windows can be opened, closed, brought into focus, moved, re-sized and printed using JavaScript window methods.
      12.14.2 Handling Events
      Some events that can be detected using JavaScript such as mouseclicks, and mouseover, have already been discussed above. JavaScript can also detect double-clicks, when a form element has the focus, when a key has been pressed, when a menu item has been selected, and when pages are loaded and unloaded.
      12.14.3 String Manipulation
      JavaScript has a number of string manipulation and conversion functions for use with string variables. Substrings can be extracted using the substring() method, or the slice() method. As we have seen, strings can be concatenated using the concatenation operator represented by the plus sign, ‘+’. The length() method returns the length of a string. The search() method looks for substring in another string. Other methods can be used to format strings in order to display them on an HTML page, locate specific characters, split strings, and more.
      12.14.4 Using Dates and Times
      JavaScript can access the current date and time with the getDate(), getDay(), Get Hours(), GetFullYear(), GetMinutes(), GetMonth(), getTime() methods for Date objects. The following lines create a Date object, assign it to the variable “today” and then writes today’s date to the document.

      var today = new Date();
      document.write(“<br /> Today is “ + today.getDate());
      
      12.14.5 Math Operations
      JavaScript includes the standard math operations of addition, subtraction, multiplication, division, and modulus. It also has functions for incrementing and decrementing integer variables.

      Other math functions that are available include the absolute value, ceiling, floor, sine, cosine, tangent, log, minimum, maximum and square root.
      12.14.6 Arrays
      Related variables that all have the same type can be grouped together in arrays. The individual values in the array are accessed using the array name and an integer index or subscript. Arrays are declared with a name for the array being assigned new Array(arraysize) where arraysize is an integer indicating how many individual elements are needed in the array. An example of an array declaration is:

      array1 = new Array(5);
      


      This will declare an array of size 5 to the variable “array1”. The individual elements of the array are accessed with the array name and the index number in square brackets. Index values begin at zero, so the first element is accessed with array1[0], the second with array1[1], etc.
      12.14.7 Iteration
      JavaScript implements iteration with for and while loops. The syntax for both is similar to that used in C++.
      12.14.8 Timers
      JavaScript has a function, window.setTimeout(), that let certain actions to be executed at different times. The function takes two parameters. The first is the statement to be executed and the second is a time value in milliseconds (5 seconds = 5000 milliseconds). For example, the following line will change the background color to grey after 10 seconds:

      window.setTimeout(“document.bgcolor = ‘#9B9B9B’ “, 10000);
      


      12.14.9 Detecting the User’s Browser, Operating System, Whether JavaScript is Enabled, and Using Cookies
      The navigator object has properties and methods that can determine aspects of the user’s system. The properties include the appName, appVersion. The javaEnabled() method returns true if java (not JavaScript) is enabled in the user’s browser.

      Cookies are small files containing some data that help maintain “state”. User preferences might be kept in a cookie, so that when the user visits the sight again, the cookie can be retrieved and the preferences implemented. Cookies are written to the user’s computer.
      12.14.10 More about HTML Forms
      In addition to providing access to the values of HTML form elements, JavaScript can also be used to disable or enable form elements and control the focus of the form.
      12.14.11 Frames
      In pages that use frames, each frame can be accessed using its name. The document in a frame can be written to, frame re-sizing can be detected and more, using JavaScript.

      12.15 Debugging Your JavaScripts

      Debugging is the process of removing errors from programming code. Syntax errors will be detected by the browser.

      Netscape Communicator has a JavaScript console that lets you view any errors generated by your JavaScript code. To open the console in Netscape 6, go to the Tools menu and choose JavaScript Console. For earlier versions of Netscape (version 4 and up) type javascript: in the URL text box to access the JavaScript Console.

      In Internet Explorer, you must make sure that the user preference for displaying JavaScript errors is checked.

      Once all of the syntax errors are corrected, you must check for logic errors. You must make sure that the page works correctly by testing it with different values. The easiest way to do this with JavaScript is to output intermediate values with text boxes or alert messages.

      References

      1. Anderson-Freed, S. (2002) Weaving a Website: Programming in HTML, Javascript, Perl and Java.
      2. Dietel, H. M., Dietel, P. J. & Neito, T. R. (2001) Internet & World Wide Web: How to Program. 2nd Edition. Prentice Hall, NJ.
  • Cynthia J. Martincic
    cynthia.martincic@email.stvincent.edu
    CIS Department
    Saint Vincent College
    Latrobe, PA 15650