1. FACULTY OF NATURAL AND APPLIED
SCIENCE
DEPARTMENT OF MATHEMATICS AND
COMPUTER SCINCE
CSC 3311
INTERNET PROGRAMMING I
LECTURE NOTE 2
BY
UMAR DANJUMA MAIWADA
1
2. JavaScript
JavaScript is an easy-to-use object scripting language designed for creating live online
applications that link together objects and resources on both clients and servers. While Java is
used by programmers to create new objects and applets, JavaScript is designed for use by HTML
page authors and enterprise application developers to dynamically script the behavior of objects
running on either the client or the server. JavaScript’s design and concepts represent the next
generation of software for the Internet. JavaScript is:
• Designed for creating network-centric applications
• Complementary to and integrated with Java
• Complementary to and integrated with HTML
• Open and cross-platform
With JavaScript, an HTML page might contain a form that processes data on the client side. A
server-side JavaScript might pull data out of a relational database and format it in HTML on the
fly. A page might contain JavaScript scripts that run on both the client and the server.
JavaScript was originally created by Netscape. Microsoft’s version of JavaScript is called
JScript. Both Netscape and Microsoft have been instrumental in the standardization of
JavaScript/Jscript by the ECMA (European Computer Manufacturer’s Association) as
ECMAScript.
Basic JavaScript Structure
In order to run client-side JavaScript, you must embed the code in the HTML document.
Obviously, you cannot place JavaScript statements in the source code in just any location. There
are several different ways to embed JavaScript scripts in HTML:
• As statements and functions using the <SCRIPT> tag.
• As event handlers using HTML tag attributes.
• As short statements resembling URLs.
The <SCRIPT> Tag (Internal Scripts)
The <SCRIPT> tag is used to enclose JavaScript code in HTML documents. Here is the
general syntax:
<SCRIPT LANGUAGE="JavaScript">
[JavaScript statements...]
</SCRIPT>
The <SCRIPT LANGUAGE="JavaScript"> tag acts like all other HTML tags. Notice that it
must be followed by its closing counterpart, </SCRIPT>. Every statement you put between the
two tags is interpreted as JavaScript code. This is probably the most common method for
inserting JavaScript into HTML documents.
The LANGUAGE attribute is used to specify the scripting language. At present, the <SCRIPT>
tag supports various languages including JavaScript and VBScript. JavaScript is the default
scripting language, so the LANGUAGE definition is not required. JavaScript is case sensitive,
but HTML is not. It does not matter whether you write <SCRIPT> or <script>, but try to be
consistent.
2
3. External Scripts
Netscape Navigator 3.0 introduced a new SRC attribute for the <SCRIPT> tag, which enables the
use of external scripts; that is, you can use a JavaScript script that is located in another file. This
feature will eventually allow people to hide their scripts from the public.
Hiding the Script
You have probably asked yourself what happens when someone loads your page with an old
browser that does not support JavaScript. The solution to this problem is based on the
commenting tags of both HTML and JavaScript.
Commenting tags in Netscape Navigator and in Internet Explorer are <!-- and -->. The first one
opens the comment block, and the second one closes it. A simple comment in a plain HTML
document looks like this:
<!-- copyright 2001 -->
There are two types of comments in JavaScript:
• // to begin a short comment that does not exceed the length of one line
• /* and */ to enclose a comment of any length
The JavaScript interpreter ignores the opening HTML comment tag in JavaScript code. Take a
look at the syntax you should use to hide the code from old browsers that do not support
JavaScript:
<SCRIPT LANGUAGE="JavaScript">
<!-- hide code from old browsers
JavaScript statements...
// end code hiding -->
</SCRIPT>
Placing JavaScript Code
When you want to place the script somewhere in the HTML document, you need to choose
where to put it. Technically, you may place it anywhere between the <HTML> and </HTML>
tags that enclose the whole document. Actually, the two possibilities are the <HEAD></HEAD>
portion and the <BODY></BODY> portion. Because the <HEAD></HEAD> portion is
evaluated first, some developers choose to place their JavaScript here. A single HTML document
may contain any number of scripts. You can place some of the scripts in the <HEAD></HEAD>
portion and others in the <BODY></BODY> portion of the page. The following code
demonstrates this:
3
4. <HTML>
<HEAD>
<TITLE>Multiple scripts</TITLE>
<SCRIPT LANGUAGE="JavaScript">
[JavaScript statements...]
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
[JavaScript statements...]
</SCRIPT>
</HEAD>
<BODY>
<H1>This is a complex structure</H1>
<SCRIPT LANGUAGE="JavaScript">
[JavaScript statements...]
</SCRIPT>
</BODY>
</HTML>
Conventions
JavaScript syntax is very similar to C, C++, and Java. It includes functions, expressions,
statements, operators, and more.
Using the Semicolon
The JavaScript interpreter does not pay any attention to carriage return characters in the source. It
is possible to put numerous statements on the same line, but you must separate them with a
semicolon (;). You can also add a semicolon at the end of a statement that occupies its own line,
but it is not necessary. Take a look at the following statements:
document.write ("Hello"); alert ("Good bye")
document.write("Hello")
alert("Good bye")
document.write("Hello");
alert("Good bye");
All three sets are legal, and their results are identical.
JavaScript is Case Sensitive
You saw earlier that JavaScript is a case-sensitive language. This applies to all aspects of the
language, including variable names (identifiers), functions, and methods (discussed later). The
statement document.write(), for example, is legal, but document.Write() is not.
Using Quotes
In JavaScript, you often use quotes to, among other things, delimit strings. A common problem
arises when using a pair of quotes inside another pair of quotes. Since the interpreter must
recognize each set of quotes in order to pair them correctly, the creators of JavaScript made it
possible to use two different types of quotes: double quotes (") and single quotes ('). If you need
only one set of quotes, you can choose either of them as long as you terminate the quote with the
same type of quote you used to open it. If you do not follow this rule, you will get a JavaScript
error: “unterminated string literal.” You must always alternate quotes properly:
document.write("<IMG SRC='cool.gif'>")
4
5. Your First Script
First of all, launch your text editor. Type Example-1. The following script is interpreted and
executed immediately when you load the page containing it.
<HTML>
<HEAD>
<TITLE>Hello World.</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide code from old browsers
document.write("<H1>Hello World.</H1>")
// end code hiding -->
</SCRIPT>
</BODY>
</HTML>
Example-1
If you entered the code properly you should see something in your browser similar to Figure-1.
Figure-1
Notice that its structure is the same as that of any other HTML document. The only new concept
is the <SCRIPT> tag. I put the script in the <BODY>…</BODY> portion of the page, though
you may put it anywhere between the <HTML> and </HTML> tags. For now, think of
document.write() as a way to print expressions to the page. write() is actually a method of the
document object. The write() method supports any HTML syntax. Be aware, also, that all strings
must be included in quotes.
Data Types in JavaScript
Variables hold information which must be of a specific type. These types are referred to as data
types. There are four data types in JavaScript: numbers, strings, Boolean, and null values. As
opposed to other languages, a variable data type is not declared explicitly but rather implicitly
5
6. according to its initial value assignment. Also unique to JavaScript, there is no explicit distinction
between integer and real-valued numbers.
All of these data types are specified in Table-1.
Identifiers
Each variable is identified by a variable name, also known as an identifier. Each variable name is
associated with a specific memory location, and the interpreter uses it to determine its location.
There are strict rules for naming variables:
• The first character of an identifier must be either a letter (uppercase or lowercase) or an
underscore (_).
• All other characters can be letters, underscores, or digits (0-9).
• An identifier cannot be one of the language’s reserved words. Reserved words consist of
all JavaScript keywords as well as other tokens reserved for future versions.
An identifier length is not limited, and you should take advantage of this feature to select
meaningful names.
The following identifiers are legal:
gameCount
_hamburger
_123456789_
look_at_me
Number16
but the following ones are illegal:
with // reserved word
^fastTimer // first character is illegal
911phoneNumber // cannot start with a digit
04-825-6408 // first character is illegal
// "-" is an illegal character
***important*** // * is not a legal character
10_guesses // first character cannot be a digit
Keywords are words that have special meanings in a programming language. You cannot use
keywords to name variables or functions you create in a script (such as variables, functions, etc.).
The list of keywords is the basic vocabulary of the language.
6
7. The word if, for example, is a keyword. You do not have to memorize the list, because you will
gradually remember it as you use the words in your scripts.
Variable Declaration
Before you use a variable, you need to create it. JavaScript is a loosely typed language, which
means that you do not have to explicitly specify the data type of a variable when you create it. As
needed, data types are converted automatically during the course of the script execution. In
strongly typed languages the variable must be created of a specific type.
There are two ways to create a variable. The first type of declaration includes the var keyword,
followed by the name of the variable:
var variableName
When interpreting this statement, the browser creates a link between the name of the variable and
its memory address, so successive references can be done by name. Unlike some programming
languages, declarations are not limited to a specific zone but can be done anywhere throughout
the script.
The action of assigning an initial value to a variable is called initialization. You give the variable
a value using the most common assignment operator—the equal sign:
var variableName = initialValue
You only need to use the var keyword when you create the variable. When you want to refer to
the variable, you only use its name. Assign a value to a variable (after it has been declared) in the
following fashion:
variableName = anyValue
You use var only once per variable. A global variable can be created simply by assigning it a
value without the var keyword. Local variables inside functions, on the other hand, must be
declared with the var keyword. As in many other programming languages, JavaScript allows you
to declare numerous variables in the same statement, using a comma to separate them:
var variableName1 = initialValue1, variableName2 = initialValue2, …
7
9. substitution only. For example, you cannot specify the entity "&{text};" with the variable text =
"<H1>Hi!</H1>"—it is not a valid value for a tag attribute.
Type Conversion
As mentioned above, data types are converted automatically as needed during the course of script
execution. A variable may hold a numeric value at one point of the script and a string at another.
The following statements constitute a valid JavaScript script:
var myVar = 12
myVar = "university"
The first statement assigns a numeric value to myVar, and the second one assigns it a string.
Such conversions are not allowed in strictly typed languages such as C++ and Java. While they
are possible in JavaScript, they are not recommended. Using this technique makes for very
sloppy programming.
Operators
Every programming language has operators. An operator is simply a symbol that tells the
compiler (or interpreter) to perform a certain action. The basic arithmetic operators are common
to most programming languages. These are addition (+), subtraction (–), multiplication (*), and
division (/). These should be very familiar to most people.
The order of precedence of operators follows the standard mathematical rules of multiplication,
division, addition, and subtraction. However, when your code has multiple operations in a single
line, it is usually a good idea to use parentheses to clarify what you want to occur: 3 * 4/2 + 1 can
be ambiguous, whereas 3 * ( (4/2) + 1) is very clear.
C, C++, and Java programmers will already be familiar with the increment and decrement
operators. The increment operator is formed by placing two plus signs after a variable, such as
this:
var somenumber
somenumber++
This line of code increments the value of somenumber by one. Had we written:
somenumber - -
9
10. It would have decreased the value by one.
It is very important that you realize that where you place increment and decrement operators is
critical. If you place the increment operator after a variable such as:
var somenumber = 10
var someothernumber
someothernumber = somenumber++
The assignment operation will take place before the evaluation operation. In other words, first
someothernumber will be set equal to the value of somenumber, then the value of somenumber
will be incremented. In our example that means that someothernumber will equal 10 and
somenumber will equal 11. If you wish to rewrite the statement so that the increment takes place
first, just reposition the increment sign:
someothernumber = ++somenumber
In this case, somenumber is incremented to 11 and then that value is assigned to
someothernumber. You’ve already learned how to assign a value to a variable or to initialize it,
using the equal assignment operator. As the following piece of code demonstrates, you can also
Perform calculations when you assign a value:
/* 1 */ var answer
/* 2 */ answer = 4 * 2 + 9
/* 3 */ document.write(answer)
Line 1 includes the declaration of the variable answer. The second line shows how the variable
answer is assigned the result of a simple mathematical expression. At this point, the variable
holds a value of 17. Referring to the variable answer is the same as referring to the number 17.
For this reason, the statement on line 3 prints the number 17.
Mixing Strings and Numbers
Mixing strings and numbers is sometimes necessary for certain operations. Since this is tricky
and can generate unexpected results, you should be familiar with its exact rules. Take a look at
the following expressions, numbered by lines.
/* 1 */ 8 + 8 // 16
/* 2 */ "8" + 8 // "88"
/* 3 */ 8 + "8" // "88"
/* 4 */ "8" + "8" // "88"
/* 5 */ 8 + 8 + "8" // "168"
/* 6 */ 8 + "8" + 8 // "888"
These expressions all use the string concatenation operator which is also the numeric plus
operator.
Whenever a string is found during the expression evaluation, the accumulated value thus far is
converted to a string. The remaining numeric values on the right-hand side are automatically
converted to strings when concatenated to this accumulated value. If you want to convert a single
number to a string, you can use one of the following three methods:
var newVar = " " + numericValue
var newVar = new String(numericValue)
var newVar = numericValue.toString()
10
11. The first method is simple. You use the concatenation operator, which instructs JavaScript to
convert the number to a string and then append it to a null string.
Equality and Relational Operators
The relational operators all have the same level of precedence and associate from left to right.
The equality operators both have the same level of precedence, which is lower than the
precedence of the relational operators. The equality operators also associate from left to right.
Table below summarized the operators.
Functions
Defining functions
Functions are defined using the keyword function, followed by the name of the function. The
same rules that apply to variable names apply to functions. Since a function usually does
something besides storing a value, it is common to include a verb in its name. The function’s
parameters are written in brackets after the name. A command block follows the parameters. The
syntax of a function definition is:
function functionName([parameters])
{
[statements]
}
Parameters are local variables that are assigned values when the function is called. At this point,
you should always give a name to every parameter. In a formal syntax specification, the square
brackets ([]) usually denote optional elements. Since a function does not have to have parameters
or statements, they are both enclosed in such brackets. The curly braces enclosing the function
body can be placed anywhere, following the parameters’ section. The following functions are
valid:
function functionName([parameters]) {[statement1]; [statement2]; …}
function functionName([parameters])
{
[statement1]
[statement2]
}
The following example demonstrates a function declaration:
11
12. <HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide script contents from old browsers
function square(number)
{
document.write("The call passed ",
number, // the function's parameter
" to the function.<BR>",
number, // the function's parameter
" square is ",
number * number,
".<BR>")
}
// *** add function call
// end hiding contents from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Calling Functions
In order to execute the set of statements located in the function block, you must call the function.
The syntax of a function call is:
functionName([arguments])
By adding the statement square(5) to Example above, at the specified place, we call the function.
The statements in the function are executed, and the following message is output:
The call passed 5 to the function.
5 square is 25.
You can also call a function from within another function, as the following example
demonstrates:
<HTML>
<HEAD>
<TITLE>Calling a function from within another function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide script contents from old browsers
function makeBar()
{
var output = "<HR ALIGN='left' WIDTH=400>"
document.write(output)
}
function makeHeader(text, color, size)
{
var output = "<FONT COLOR='" + color + "' SIZE=" +
size + ">" + text + "</FONT>"
document.write(output)
12
13. makeBar()
}
makeHeader("JavaScript Examples", "red", "+4")
// end hiding contents from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Example-3 (ex-3.htm). A function call in a function block.
Example-3 summarizes many of the terms discussed in this chapter. It includes two function
definitions. In both functions, the output is assigned to a variable (output) and then printed to the
client window using the document.write() method. Assigning strings to variables before printing
them is extremely useful when the string is long (i.e., you want to print a lot of data). You can see
the result of Example-3 in Figure -2.
Figure -2
Control Structures in JavaScript
Dialog Boxes
Before we discuss the control structures in JavaScript, we need some basic user interaction
devices. These will allow us to create both useful and helpful examples for demonstration
purposes.
JavaScript provides the ability to create small windows called dialog boxes. You can create alert
boxes, confirm boxes, and even prompt boxes. These boxes let you generate output and receive
input from the user.
Alert Boxes
An alert box is the most simple dialog box. It enables you to display a short message to the user
in a separate window. Take a look at the following script and its corresponding output:
alert("Click OK to continue...")
13
14. The generic form of this function is alert(message). The function alert() is actually a method of
the window object. It is not necessary to specify that because window is the default object. The
same applies to all dialog boxes.
You can also display messages using data structures. For example:
var message = "Click OK to continue"
alert(message)
As you can see, the alert box is often used to pause the execution of a script until the user
approves its continuation.
Confirm Boxes
Confirm boxes are different from alert boxes in that they evaluate to a value based on a decision
made by the user. Rather than a simple OK button, the confirm box includes both OK and Cancel
buttons.
Like the alert box, confirm is also a method of the window object. This method returns a Boolean
value, because there are two options. You can use confirmation boxes to ask the user a yes-or-no
question, or to confirm an action. Here is an example and its output:
var reply = confirm("OK to continue?")
reply is assigned a true value if the user chooses OK, and false if the user selects Cancel.
The generic form of this function is confirm(message).
Prompt Boxes
The prompt() method displays a prompt dialog box with a message and an input field. You can
use these boxes to receive input from the user. It is similar to the confirm box, except that it
returns the value of the input field, rather than true or false. Here is an example:
var name = prompt("Enter your name:", "anonymous")
The method returns a value of null if the user chooses Cancel. The prompt box looks like the
image shown in Figure below.
14
15. The value of the field is always a string. If the user enters 16 in the form, the string "16" is
returned rather than the number 16. When you want to prompt the user for a number, you must
convert the input into a numeric value. JavaScript features a built-in function that does this—
parseInt(). You can use the following statement to ask the user for a number:
var number = parseInt(prompt("Enter a number:", 0))
or
var number = prompt("Enter a number:", 0)
number = parseInt(number)
The generic form of this function is prompt(message[, inputDefault]). You can see that this
function works by using the type of operator for testing:
var number = prompt("Enter a number:", 0)
alert(number, " is a ", typeof number) // "... is a string"
number = parseInt(number)
alert(number, " is a ", typeof number) // "... is a number"
The input must be of a numeric type, of course (e.g., 99).
Example: This javascript program inputs two integers typed by a user at the keyboard, computes
the sum of the values and displays the result.
<html>
<head>
<title>An Addition Program</title>
<script type = "text/javascript">
<!--
var firstNumber, // first string entered by user
secondNumber, // second string entered by user
number1, // first number to add
number2, // second number to add
sum; // sum of number1 and number2
// read in first number from user as a string
firstNumber = window.prompt( "Enter first integer", "0" );
// read in second number from user as a string
secondNumber = window.prompt( "Enter second integer", "0" );
// convert numbers from strings to integers
number1 = parseInt( firstNumber );
number2 = parseInt( secondNumber );
// add the numbers
15
16. sum = number1 + number2;
// display the results
document.writeln( "<h1>The sum is " + sum + "</h1>" );
// -->
</script>
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
Output
The if statement
The if statement is used to check a condition and if the condition is true, we run a block
of statements (called the if-block), else we process another block of statements (called the
else-block). The else clause is optional.
The condition must evaluate to a Boolean value: true or false. Numeric values are also acceptable
as an alternative to a Boolean condition. 0 is equivalent to false, and all other values are
equivalent to true.
16
17. A statement can be anything from a simple document.write() to a block of statements, using curly
braces ({}). Some if statements require multiple statements, so they use a block in the following
form:
if (condition)
statement1
else
statement2
the pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”
The preceding pseudocode If/Else structure may be written in JavaScript as
if ( studentGrade >= 60 )
document.writeln( "Passed" );
else
document.writeln( "Failed" );
JavaScript provides an operator, called the conditional operator (?:), that is closely related to
the if/else structure. The operator ?: is JavaScript’s only ternary operator— it takes three
operands. The operands together with the ?: form a conditional expression. The first operand is
a boolean expression, the second is the value for the conditional expression if the condition
evaluates to true and the third is the value for the conditional expression if the condition
evaluates to false. For example, the statement
document.writeln(
studentGrade >= 60 ? "Passed" : "Failed" );
contains a conditional expression that evaluates to the string "Passed" if the condition
studentGrade >= 60 is true and evaluates to the string "Failed" if the condition is false. Thus,
this statement with the conditional operator performs essentially the same operation as the
preceding if/else structure.
Nested if/else structures test for multiple cases by placing if/else structures inside if/else
structures. For example, the following pseudocode statement will print A for exam grades greater
than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for
grades in the range 60 to 69 and F for all other grades:
This pseudocode may be written in JavaScript as
if ( studentGrade >= 90 )
document.writeln( "A" );
else if ( studentGrade >= 80 )
document.writeln( "B" );
else if ( studentGrade >= 70 )
document.writeln( "C" );
else if ( studentGrade >= 60 )
document.writeln( "D" );
else
17
18. document.writeln( "F" );
If studentGrade is greater than or equal to 90, the first four conditions will be true, but only
the document.writeln statement after the first test will execute. After that particular
document.writeln executes, the else part of the outer if/else structure is skipped.
The if selection structure expects only one statement in its body. To include several statements
in the body of an if, enclose the statements in braces ({ and }). A set of statements contained
within a pair of braces is called a compound statement or a block.
The following example includes a compound statement in the else part of an if/else
structure:
if ( grade >= 60 )
document.writeln( "Passed" );
else {
document.writeln( "Failed<br />" );
document.writeln( "You must take this course again." );
}
In this case, if grade is less than 60, the program executes both statements in the body of
the else and prints
Failed.
You must take this course again.
Notice the braces surrounding the two statements in the else clause. These braces are
important. Without the braces, the statement
document.writeln( "You must take this course again." );
would be outside the body of the else part of the if and would execute regardless of whether
the grade is less than 60.
The while statement
The while statement allows you to repeatedly execute a block of statements as long as
a condition is true.
As an example of a while structure, consider a program segment designed to find the first
power of 2 larger than 1000. Variable product begins with the value 2. The structure is as
follows:
var product = 2;
while ( product <= 1000 )
product = 2 * product;
When the script enters the while structure, product is 2. The script repeatedly multiplies
variable product by 2, so product takes on the values 4, 8, 16, 32, 64, 128, 256, 512 and
1024 successively. When product becomes 1024, the condition product <= 1000 in the
while structure becomes false. This terminates the repetition, with 1024 as product’s
final value. Execution continues with the next statement after the while structure. [Note: If a
while structure’s condition is initially false, the body statement(s) will never execute.]
18
19. Example: write JavaScript program that calculates and prints the sum of the integers from 1 to
10.
<html>
<head><title>Sum the Integers from 1 to 10</title>
<script type = "text/javascript">
<!--
var sum, x;
x = 1;
sum = 0;
while ( x <= 10 ) {
sum += x;
++x;
}
document.writeln( "The sum is: " + sum );
// -->
</script>
</head><body></body>
</html>
The for loop
The for.. statement is another looping statement which iterates over a sequence of
objects i.e. go through each item in a sequence. The general format of the for structure is
for ( initialization; loopContinuationTest; increment )
statement;
The three expressions in the for structure are optional. If loopContinuationTest is omitted,
JavaScript assumes that the loop-continuation condition is true, thus creating an infinite loop.
One might omit the initialization expression if the control variable is initialized elsewhere in the
program before the loop. One might omit the increment expression if the increment is calculated
by statements in the body of the for structure or if no increment is needed. The increment
expression in the for structure acts like a stand-alone statement at the end of the body of the
for structure. Therefore, the expressions
counter = counter + 1
counter += 1
++counter
counter++
are all equivalent in the incrementing portion of the for structure.
The following examples show methods of varying the control variable in a for structure.
a) Vary the control variable from 1 to 100 in increments of 1.
for ( var i = 1; i <= 100; ++i )
b) Vary the control variable from 100 to 1 in increments of -1 (i.e., decrements of 1).
for ( var i = 100; i >= 1; --i )
c) Vary the control variable from 7 to 77 in steps of 7.
for ( var i = 7; i <= 77; i += 7 )
d) Vary the control variable from 20 to 2 in steps of -2.
for ( var i = 20; i >= 2; i -= 2 )
e) Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17, 20.
for ( var j = 2; j <= 20; j += 3 )
19
20. f) Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55, 44, 33,
22, 11, 0.
for ( var j = 99; j >= 0; j -= 11 )
The next two scripts demonstrate the for repetition structure. It uses the for structure to sum
the even integers from 2 to 100. Notice that the increment expression adds 2 to the control
variable number after the body executes during each iteration of the loop. The loop terminates
when number has the value 102 (which is not added to the sum).
<html>
<head>
<title>Sum the Even Integers from 2 to 100</title>
<script type = "text/javascript">
<!--
var sum = 0;
for ( var number = 2; number <= 100; number += 2 )
sum += number;
document.writeln( "The sum of the even integers " +
"from 2 to 100 is " + sum );
// -->
</script>
</head><body></body>
</html>
break Statement
Normally, a loop executes until the terminating condition is met, but you might want it to
terminate earlier if it meets some other condition. The break statement does just that; it
terminates the loop’s execution. The following script segment demonstrates the break statement:
for (var i = 0; i < 100; i++)
{
document.write(i + " ")
if (i == 50) // additional terminating condition
break // break out of the loop
}
The output of this loop is:
0 1 2 3 4 5 6 7 8 9 . . . 41 42 43 44 45 46 47 48 49 50
As you can see, the loop terminates when i is 50, not when i is equal to 100. That is, it terminates
before the condition i < 100 evaluated to false. When i am equal to 50, the condition i == 50
returns true, and the break statement executes, causing the loop to terminate. The break statement
lets you place additional terminating conditions at various locations in a loop’s command block.
20
21. continue Statement
The continue keyword stops the current iteration of a loop, and continues the execution at the top
of the loop. The loop continues to execute until the terminating condition is achieved. The “top”
of the loop is:
• The update expression in for loops, such as ++i
• The condition expression in while loops
Here is a simple example for the usage of the continue statement:
var sum = 0 // will hold the sum of the odd numbers
for (var i = 1; i <= 10; ++i)
{
if (i % 2 == 0) // 1: if i is even
continue // 2: go to the top of the loop
sum += i // 3: add i to sum (i is always odd!)
}
This example adds up every odd integer from 1 to 10. The easiest way to do that is to increase the
counter variable by 2 after each pass through the loop, but we wanted to feature the continue
statement.
Here is another example using the continue statement:
for (i = 1; i <= 10; ++i)
{
if (i == 5)
continue
document.write(i + " ")
}
The output is:
1 2 3 4 6 7 8 9 10
The 5 is missing because when i is equal to 5 the loop is sent to the beginning, incrementing i to
6. The continue statement is located before the document.write() statement, so the
document.write() method is never invoked when i is 5.
Forms
Input/Output via Text Boxes
A button provides a simple mechanism through which users can interact with a Web page. By
clicking the button, the user initiates some action. Although an alert window is sufficient for
displaying a simple message, most tasks require more elaborate types of user interaction, such as
where the user enters several inputs and then views the results of a computation. Fortunately,
HTML provides another form element, called a text box, that can be used to implement these
more complex interactions. A text box, as its name suggests, is a box that can contain text (words
or phrases). Unlike an alert window or prompt window, however, a text box is displayed within
the page itself. When the user enters characters in a text box, that input is directly accessible via
JavaScript code; similarly, JavaScript statements can assign text to text boxes. Thus, a text box
can be used both to receive user input and to display the results of computations within the page.
21
22. The following represents a generalized text box element:
<input type="text" name="TEXTBOX_NAME" size=NUM_CHARS value="INITIAL_TEXT" />
A text box’s NAME attribute specifies the name used to identify that box. The SIZE attribute
defines the size of the box, which is measured by the number of characters it can contain. The
VALUE attribute (if present) specifies the text that the text box initially contains. Like buttons,
text boxes are form elements and therefore must appear inside form tags.
Text Boxes for Displaying Output
Using JavaScript code, programmers can display a message in a text box by encapsulating the
message as a string and assigning the string to the box’s VALUE attribute. When you assign a
value to a text box, you must specify the absolute name of the box; this is accomplished by
typing the word "document", followed by the name of the form containing the box, then the text
box name (all separated by periods). JavaScript requires the use of full, absolute names as a way
of avoiding confusion, since a page might contain multiple forms with text boxes of the same
name. The following represents a generalized assignment to a text box:
document.FORM_NAME.TEXTBOX_NAME.value = STRING_TO_BE_DISPLAYED;
Text Boxes for Accessing Input
Whereas some text boxes are used to display output, others are employed to handle user input.
When a text box is intended to accept input, users can enter data by clicking the mouse pointer
inside the box and typing. JavaScript code then accesses the text box’s contents using the
absolute name of the text box (where FORM_NAME and TEXTBOX_NAME will vary for each
text box):
document.FORM_NAME.TEXTBOX_NAME.value
For example, the Web page in Figure below is an event-driven version of the temperature
conversion page. The page contains a text box named fahrBox, which accepts user input. The
user enters a Fahrenheit temperature in fahrBox and then clicks the button labeled "Convert to
Celsius". When the button is clicked, the Convert function accesses the value that the user
entered and computes the corresponding Celsius temperature. The result of the computation is
then assigned to a text box named celsiusBox, which displays the converted temperature in the
page.
<html>
<!-- convert1.html -->
<!-- This page converts temperatures from Fahrenheit to Celsius.
-->
<!---------------------------------------------------------------
-->
<head>
<title>Temperature Conversion Page</title>
<script type="text/javascript">
function FahrToCelsius(tempInFahr)
// Assumes: tempInFahr is a temperature in Fahrenheit
// Returns: the equivalent temperature in Celsius
{
return (5/9) * (tempInFahr - 32);
}
function Convert()
22
23. // Assumes: document.TempForm.fahrBox contains degrees
Fahrenheit
// Results: assigns document.TempForm.celsiusBox the equiv.
temperature
{
var tempF, tempC;
tempF = parseFloat(document.TempForm.fahrBox.value);
tempC = FahrToCelsius(tempF);
document.TempForm.celsiusBox.value = tempC;
}
</script>
</head>
<body>
<h2>Temperature Conversion Page</h2>
<hr /><br />
<form name="TempForm">
Enter a temperature in degrees Fahrenheit:
<input type="text" name="fahrBox" size=10 value="" />
<br /><br />
<input type="button" value="Convert to Celsius"
onClick="Convert();" />
<br /><br />
Equivalent temperature in degrees Celsius:
<input type="text" name="celsiusBox" size=10 value="" />
</form>
</body>
</html>
We describe the key parts of this program below:
• The eighth line specifies that you are defining a function named FahrToCelsius that takes
one input. The variable name in parentheses, known as a parameter (because it is part of the
function definition), represents the function’s necessary input. When the function is called,
the input value specified in the function call is assigned to the parameter for use in the
function's computation. For example, in the call FahrToCelsius(212), the parameter
tempInFahr would be assigned the value 212. Thus, the function would evaluate the
expression (5/9) * (212- 32), resulting in the value 100.
• The actual code that carries out the function’s computation is enclosed in curly-braces ({}).
In this example, the function definition contains only one line of JavaScript code, but
functions can encompass any sequence of statements. A return statement, a special JavaScript
statement included within the curly-braces, specifies the value that should be returned by the
function (i.e., its output value). A return statement consists of the word return, followed by
an expression. When a return statement is executed, the expression is evaluated, and the
result is returned as the value of the function call.
23
24. Text Boxes for Handling Both Input and Output
It is not uncommon for a particular sequence of JavaScript statements to employ the same
variable in multiple ways. For example, a program might use a variable initially to store a user
input, then later assign the result of some computation to that same variable. If we extend our
analogy of text boxes as similar to variables, it follows that the same text box can be used both to
obtain user input and to display the result of a computation.
Consider, for example, the JavaScript function in Figure below. Assuming a text box named
number appears in the page (inside a form named NumForm), this function will access the number
in the text box, multiply that number by two, and assign the result back to the box. Thus, every
time the function is called, the current value of the text box will be doubled. A user can enter any
number in the text box, then click the button repeatedly to update the value displayed in the box.
function DoubleIt()
// Assumes: document.NumForm.number contains a number
// Results: the number in the box is doubled
{
var num;
num = parseFloat(document.NumForm.number.value);
document.NumForm.number.value = 2 * num;
}
EXERCISE: Create a Web page named double.html whose HEAD includes the DoubleIt
function. The page should contain a text box with an initial value of 1 and a button labeled
"Double It". When the user clicks the button, the DoubleIt function should be called to
double the contents of the text box.
If you start with a value of 1 in the text box, how many times must you click the button before
the displayed value exceeds 500? How many times to exceed 1000?
Input/Output via Text Areas
Although text boxes provide a convenient method of reading in and displaying values in Web
pages, the fact that text boxes can contain only one line of text often limits their usefulness. An
alternative is a text area, which is similar to a text box but can contain any number of text lines.
The following represents a generalized text area element:
<textarea name="TEXTAREA_NAME" rows=NUM_ROWS cols=NUM_COLS wrap="virtual">
INITIAL_TEXT
24
25. </textarea>
A text area’s NAME attribute specifies the name used to identify that area. The number of rows
(horizontal lines that can contain text) and columns (maximum characters per line) in the text
area are defined by the attributes ROWS and COLS, respectively. The attribute assignment
wrap="virtual" ensures that text will wrap from one line to the next as needed, instead of
running off the edge of the text area. The initial text that appears in the text area (if any) is
enclosed between the <textarea> and </textarea> tags.
The Web page in Figure below contains two text boxes, each 15 characters wide, and a text area
consisting of four rows of 40 characters. The page asks users to enter their first and last names in
the text boxes. Once a user enters the names and clicks the button, the program accesses the
contents of the text boxes and incorporates the names in a greeting, which displays in the text
area. Note that there is no text between the opening and closing TEXTAREA tags, so the text
area initially appears empty.
<html>
<!-- greetbox.html -->
<!-- This page displays a personalized greeting in a text area.
-->
<head>
<title> Long Greeting </title>
<script type="text/javascript">
function Greet()
// Assumes: document.NameForm.firstName and
// document.NameForm.lastName contain names
// Results: writes a message with those names in
document.NameForm.message
{
var firstName, lastName, greeting;
firstName = document.AreaForm.firstName.value;
lastName = document.AreaForm.lastName.value;
greeting = "Hello " + firstName + " " + lastName +
", or may I just call you " + firstName +
"? You wouldn't be related to the " + lastName +
"s of Park Avenue, would you?";
document.AreaForm.message.value = greeting;
}
</script>
</head>
<body>
<form name="AreaForm">
Enter your first name: <input type="text" size=15
name="firstName" />
<br />
Enter your last name: <input type="text" size=15
name="lastName" />
<br /><br />
<input type="button" value="Click for Greeting"
onClick="Greet();" />
<br /><br />
<textarea name="message" rows=4 cols=40
wrap="virtual"></textarea>
25