OUR MUST POPULAR POST

Friday, June 28, 2013

JavaScript Programming

JavaScript Programming

Session -1

What Is JavaScript?

JavaScript is one of a new breed of Web languages called scripting languages. These are simple languages that can be used to add extra features to Web page.
JavaScript was originally developed by Netscape Corporation for use in its browser, Netscape Navigator. It includes a convenient syntax, flexible variable types, and easy access to the browser's features. It can run on the browser without being compiled; the source code can be placed directly into a Web page.
JavaScript Versus Java
JavaScript and Java are alike in more than just name. However, there are significant differences between these two languages. The Table shows a quick overview of the differences.
Comparing JavaScript and Java
JavaScript
Java
Interpreted by client
Compiled by the author, run on client
Code integrated in HTML documents
Applets distinct from HTML document
Loose typing of data types
Strong typing of data types
Dynamic binding
Static binding
Script limited to browser functions
Stand-alone applications
Works with HTML elements
Goes beyond HTML (for example, multimedia)
Access browser objects and functionality
No access to browser functionality objects or

Combining JavaScript with HTML
The <SCRIPT> tag, an extension of HTML supported by Netscape, enables you to include one or more JavaScript functions in the page.
A simple JavaScript Example
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function disp()
{
document.write ("<H1>");
document.write ("A very Simple JavaScript Sample");
document.write ("</H1>");
}
</SCRIPT>
</HEAD>
<BODY onload="disp()">
</BODY>
</HTML>

Simplified Language Structure

The limitations of JavaScript also make it much easier for the programmer. The syntax of the JavaScript language is more relaxed than that of Java, and variables (names used to store values) are easier to use. Here are the specifics:
  • The JavaScript language is interpreted rather than compiled. Changing a script is as simple as changing an HTML page.
  • Rather than creating objects and classes, you can do quite a bit by simply accessing existing objects in JavaScript.
  • Variables are loosely typed: You do not need to declare variables before their use, and most conversions (such as numeric to string) are handled automatically.
  • Event handlers enable a JavaScript function to execute whenever an action is performed on part of the HTML document. For example, a form's input field can be checked for certain values whenever it is modified.
Web Browser Integration
JavaScript is an object-oriented language. This simply means that it can use objects. An object is a more complicated version of a variable. It can store multiple values and can also include actual JavaScript code. You can create your own objects to represent just about anything.
JavaScript also includes objects that enable you to access features of the browser directly. These objects represent actual elements of the browser and the Web page, such as windows, documents, frames, forms, links, and anchors.
Supported on More Platforms
Because JavaScript is supported by Netscape on all the available platforms, it is supported more widely than Java. Until Java becomes more widely supported, using JavaScript for simple applications enables you to reach a wider audience on a wide variety of platforms.
Uses for JavaScript
The most important uses for JavaScript. are
·         Including Dynamic Information
·         Validating Forms
·         Making Pages Interactive
Getting Started with JavaScript
You can program in JavaScript easily; no development tools or compilers are required. You can use the same editor you use to create HTML documents to create JavaScript, and it executes directly on the browser (currently, Netscape or Microsoft Internet Explorer).
JavaScript was originally called LiveScript, and was a proprietary feature of the Netscape browser. JavaScript has now been approved by Sun, the developer of Java, as a scripting language to complement Java. Support has also been announced by several other companies

Testing a Simple JavaScript Program

A JavaScript program can be simple-even as small as a single statement-or much more complicated. Take a look at the simple example.
<HTML>
<HEAD>
<TITLE>Another JavaScript Test </TITLE>
<SCRIPT LANGUAGE="JavaScript">
document.write("Hello!");
window.alert("Hello again!");
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
What happens when you load this Web page in Netscape? Let's take a quick look at the inner workings of JavaScript. Once you understand what happens and in what order, you'll find it easy to learn the specifics-such as the JavaScript language itself.

Receiving the Web Page

Let's start with a review of the basics: What happens when you request a Web page from a server? This is an important process to understand. Here are the steps involved:
  1. You enter a URL into your browser, or select a bookmark.
  2. The browser sends an HTTP request for the URL to the appropriate server (known).
  3. The server sends back the contents of the Web page at the URL.
  4. The browser sends additional requests for each of the graphics page.
  5. After receiving enough information about the graphics to devote the correct amount of space to them, the browser displays the page.
  6. The remaining graphics are displayed as they are received.

Processing the Script

When JavaScript is involved, the process is slightly different. After the full HTML document is received, as in step 3 in the last section, it is examined for the <SCRIPT> tag. If a script is included, it is processed; however, the processing depends on the type of script:
  • If the script is included in the header, it is ignored unless a script later calls it.
  • If the script is included directly in the body, its output will be included in the Web page-thus, it can affect the display of the page.
  • If the script is an event handler for a specific part of the page, it will be processed only when the event happens.
All three of these are useful ways of implementing a JavaScript program; you choose one of these methods depending on your needs. In a complicated JavaScript application, you will probably use all three.
Writing a Simple JavaScript Application
Creating the Script
The following script simply displays the location of the current page and a brief message. This script will be combined with an HTML page and its use demonstrated.
document.write("<B> location: </B>" + document.location + "<br>")
document.write("This is a test of JavaScript." + "<br>")
After you've created the script, you need to do two things:
  1. Embed the script in the HTML page. You can use the <SCRIPT> tag to do this, or use an event handler.
  2. Test the script by viewing the document with Netscape.
Embedding the Script in an HTML Page
Using the <SCRIPT> tag
The simplest method of including a JavaScript script in an HTML page is to use the <SCRIPT> tag. This tag is usually used as a container, and the script is included directly after it.
A simple example of the <SCRIPT> tag.
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write("<B> location: </B>" + document.location + "<br>")
document.write("This is a test of JavaScript." + "<br>")
-->
</SCRIPT>
Notice the strange syntax. The extra brackets and exclamation marks indicate a comment; the entire script is marked as a comment so that older browsers will not attempt to display it. JavaScript-aware browsers will execute it correctly.
If you use this method within the body of a Web page, the script will be executed immediately when the page loads, and the output of the script will be included at that point in the page. You can also use the <SCRIPT> tag within the header of a page to prevent it from executing immediately. This can be useful for subroutines that you will call later.

Session-2
JavaScript Language Structure
JavaScript has a simple, relaxed structure. You can include a single line of JavaScript in an HTML document, and it will act as a JavaScript program in itself. No specific statements are required to begin or end a JavaScript script, except for the <SCRIPT> and </SCRIPT> tags in HTML. For example, this is a simple JavaScript program to print a message:
<SCRIPT LANGUAGE="JavaScript">
document.write("The eagle has landed. The fat man walks alone.");
</SCRIPT>
Note
JavaScript keywords, function and object names, and variable names are case-sensitive. Be sure you use the correct combination of upper- and lowercase when entering JavaScript statements.
Notice the semicolon at the end of the example statement. This is a common feature of many languages, such as C and Java, to indicate the end of a statement.

Statements

Statements are simply commands that perform a certain purpose. Several statements are built into JavaScript; these are used to test variables, control the flow of the program, and perform actions.
The term statement is also used to refer to any line of JavaScript code. For example, the document.write() statement used in the examples is technically an object method.

Functions

A function accepts parameters and returns a value.
This example defines a very simple function that adds two numbers:
Function Add(a,b)
{
   var result = a + b;
   return result;
}
To use a function, you simply include the function's name, followed by the parameters in parentheses. For example, here is a simple script that uses the Add() function to print a result:
var test = Add(2,4);
document.write("Two plus four equals:",test);

Variables

A variable is simply a name given to a value. Variables can be given different values throughout the course of a JavaScript program. In the previous example, a variable called test is used to store the result returned by the Add() function.

Expressions

An expression is something that JavaScript interprets before using it in a statement. For example, this statement assigns a number to the variable total, using an expression:
total = result1 + result2;
The expression result1 + result2 is interpreted; in this case, the values are simply added together. This value is then used as the value to assign to the total variable. Along with mathematical expressions, expressions can include function results and conditional expressions.

Comments

A final element you can include in a JavaScript program is a comment. These are items of text that can be included for your information, or for others who might try to understand the script. Comments are ignored by the JavaScript interpreter.
JavaScript supports two types of comments:
  • A single-line comment begins with two slashes (//) and ends at the end of the line.
  • A multiple-line comment begins with the /* delimiter and ends with the */ delimiter.
Note
Do not confuse JavaScript comments with HTML comments. You can use HTML comments to hide JavaScript commands from non-JavaScript browsers, and they cannot be used within the script. JavaScript comments are part of the script, and they can be used only between the <SCRIPT> tags.
Programs and Applications
  • A JavaScript program consists of all of the functions, event handlers, and variable declarations included in a single HTML file. These might not execute in the order they are defined, but the browser reads and interprets them all at the same time.
  • Consider a JavaScript application to be a set of HTML files and scripts that work together to form a useful purpose. A complete application might involve several JavaScript programs in several different HTML files, and may even include additional functionality through different languages, such as CGI or Java or ASP.

Data Types and Variables

One of the most important features of a programming language is the capability of working with data. JavaScript includes flexible support for most types of data.
You can use data in a JavaScript program in two ways:
  • As a literal or constant value, which is included directly in the JavaScript code. For example, 54, 6.17, and "This" are all literal values.
  • Variables are named containers that can hold a value. You can assign them different values during the course of the program.
JavaScript includes support for relatively few types of data, but you can use these to create other types. In fact, using JavaScript's object-oriented features, you can create a wide variety of custom types.
The four fundamental data types used in JavaScript are the following:
  • Numbers, such as 3, 25, or 1.4142138. JavaScript supports both integers and floating-point numbers.
  • Boolean, or logical values. These can have one of two values: true or false.
  • Strings, such as "This is a string". These consist of one or more characters of text.
  • The null value, represented by the keyword null. This is the value of an undefined variable.
By contrast, JavaScript is a loosely typed language. This means that when you declare a variable, you don't have to define its type. You can store any allowable type of data in a variable. Conversions between different types of data happen automatically.

Integers

An integer is simply a number that does not include a decimal. Integers in JavaScript can be only positive numbers. You can use an integer as a literal in JavaScript simply by including the number. For example, this statement prints the number 47:
document.write(47);

Floating-Point Numbers

You can also use floating-point decimal numbers in your JavaScript programs. These can be used to represent just about any number conveniently. A simple floating-point value consists of an integer followed by a decimal point and a fractional value, such as 2.01.
Unlike integers, floating-point values can be either positive or negative. You can specify negative values for floating-point numbers by adding the negative sign to the beginning of the number, as in -3.1. Any number without a negative sign is assumed to be positive.

Boolean Values

Boolean values are the simplest data type. They can contain one of two values: true or false.
Note
You can use the numbers 0 and 1 as synonyms for false and true in many cases in JavaScript; however, it's best to treat Boolean values as strictly Boolean

Strings

Another important type of value you can work with in a JavaScript program is a string. Strings are simply groups of characters, such as "Hello" or "I am a jelly doughnut.".
You can include strings as literals in JavaScript by enclosing them in double or single quotation marks. Here are some examples of values that JavaScript will treat as strings:
  • "This is a string."
  • 'A'
  • '25 pounds'
  • "200"
You can use the two types of quotes interchangeably. However, you must use the same type of quote to end the string that you used to begin it.
Tip
HTML uses double quotation marks to indicate values for some tags. Because you will be using JavaScript within HTML documents, and especially in event handlers, you may want to get into the habit of using single quotation marks within JavaScript statements. This will avoid conflicts with the HTML codes.

Special Characters

Along with alphanumeric characters, you can use a variety of special characters in JavaScript strings. These include carriage returns, tabs, and other nonprintable characters.
To use one of these special characters, include a backslash (\) followed by the code for that character. The codes are as follows:
  • \a: Alert (bell) character (produces a bell sound)
  • \b: Backspace character (moves the cursor back one character)
  • \f: Form-feed character (indicates a new page on a printer)
  • \n: New line character (indicates a new line of text)
  • \r: Carriage return character (moves the cursor to the beginning of the line)
  • \t: Tab character (advances the cursor to the next tab stop)
You can include special characters directly in a string. For example, the following statement prints out three separate lines of text:
document.write(" this is line 1\n this is line 2\n this is line 3");
Creating an Array
Many languages support arrays-numbered sets of variables. For example, scores for 20 different students might be stored in a scores array. You could then refer to scores[1] for the first student's score, scores[5] for the fifth student, and so on. This makes it easy to define a large number of variables without having to give each one a name. The number in the brackets is called an index into the array.
JavaScript does not support arrays as variables. Instead, they are handled as objects. You can create an array by using the Array object. As an example, this statement creates an array called scores with 20 values:
scores = new Array(20);
Once you define the array, you can access its elements by using brackets to indicate the index. For example, you can assign values for the first and tenth scores with these statements:
scores[0] = 50;
scores[9] = 85;
Tip
In the previous example, notice that the first student's score is referred to as scores[0]. As in many other computer languages, JavaScript array indices begin with 0. A five-element array would have indices from 0 to 4.

Rules for JavaScript Variable Names

As mentioned earlier in this chapter, each variable has a name. In technical terms, JavaScript calls the variable name an identifier. There are specific rules you must follow when choosing a variable name:
  • Variable names can include letters of the alphabet, both upper- and lowercase. They can also include the digits 0-9 and the underscore (_) character.
  • Variable names cannot include spaces or any other punctuation character.
  • The first character of the variable name must be either a letter or the underscore character.
  • Variable names are case-sensitive; Totalnum, Totalnum, and TotalNum are separate variable names.
  • There is no official limit on the length of variable names, but they must fit within one line.
Using these rules, the following are examples of valid variable names:
Total_number_of_students    
LastInvoiceNumber  
Temp1
a
_var39

Variable Declarations and Scope

In some languages, you must declare each variable you will use. JavaScript does not require this; the first time you assign a value to a variable, it is automatically declared. You may also need to use the var keyword to declare a variable, depending on where you will use it.
Any variable in JavaScript has a scope-a section of code in which it is valid. There are generally two types of scope possible in JavaScript:
  • A variable declared within a function with the var keyword is local to that function; other functions cannot access it. Variables used to store the function's parameters are also local to the function.
  • A variable declared outside a function, or without the var keyword in a function, is global; all JavaScript statements in the current HTML or script file can access the value.
Example
<HTML>
<HEAD>
<TITLE>Variable Declarations</TITLE>
<SCRIPT LANGUAGE="JavaScript">
}
var teeth = 30;
var arms = 2;
legs = 2;
function init() {
   teeth = teeth - 4;
   var heads = 1;
   eyes = heads * 2;
}
</SCRIPT>
</HEAD>
<BODY>
Text here.
</BODY>
</HTML>
This example includes quite a few variable declarations.Let's take a look at each one:
  • teeth and arms are declared as global in the header with the var keyword.
  • legs does not use the var keyword, but is still declared as global because the declaration is outside any function.
  • heads is declared as local by using the var keyword within the init function.
  • eyes is declared without var, so it is global, although declared within the init function.

Operators

You can combine variables and literal values to form a complex expression. The tools you use to create an expression are operators. A simple example of an operator is the plus sign in the expression students + 1. JavaScript supports the following types of operators:
  • Assignment operators are used to assign a value to a variable, or change its current value.
  • Arithmetic operators are used to perform addition, subtraction, and other math on numeric literals or variables.
  • String operators are used to manipulate string values.
  • Logical operators deal with Boolean values, and are mainly used for testing conditions.
  • Comparison operators are used to test the relationship between two numeric values.
Assignment Operators
  • =  Assignment operator
  • += adds the number on the right to the variable on the left.
  • -= subtracts the number on the right from the variable on the left.
  • *= multiplies the variable by the number on the right.
  • /= divides the variable by the number on the right.
  • %= uses the modulo operator, described in the next section
Arithmetic Operators
addition (+), subtraction (-), multiplication (*), and division (/).

The Modulo Operator

You may have encountered the modulo (%) operator in a different programming language; it works the same way in JavaScript. In case you haven't seen it before, let's look at the following example:
b = a % 2;
This would be read as "b equals a modulo 2." Technically speaking, modulo is the remainder when two numbers are divided. Thus, the example could be explained as "the remainder when you divide x by 2." Here are a few literal examples:
  • 100 % 2 = 0 (2 divides into 100 evenly; there is no remainder)
  • 100 % 3 = 1 (100 divided by 3 is 33, with a remainder of 1)
  • 20 % 7 = 6 (20 divided by 7 is 2, with a remainder of 6)
Increment and decrement operators:
  • Increment (++) adds 1 to the variable's value.
  • Decrement (--) subtracts 1 from the variable's value.

String Operators

There is only one dedicated string operator in JavaScript: the concatenation operator (+). This takes the string on the right and tacks it onto the string on the left. eg.
text = header + " and so forth.";
if the header contained the text "This is a test", the value assigned to text would be "This is a test and so forth." This makes it easy to combine strings.

Logical Operators

  • && (And) returns true if both of the operands are true.
  • || (Or) returns true if either of the operands is true.
  • ! (Not) returns the opposite of the variable it prefixes.

Comparison Operators

·         Is Equal to (= = )

  • Less than (<)
  • Greater than (>)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)
Shorthand operator
Meaning
Example
x += y
x = x + Y
x +=
x -= y
x = x - y
x -=
x *= y
x = x * y
x *=
x /= y
x = x / y
x /=
x %= y
x = x % y
x %=
Important JavaScript Built-In Functions

The parseInt Function

The parseInt() function looks for an integer number as the first part of the string. It ignores the decimal portion, if found. For example, this statement assigns the variable a to the value 39:
a = parseInt("39 steps");

The parseFloat Function

The parseFloat() function is similar to parseInt(), but works with floating-point values. It attempts to find a decimal floating-point number in the string, and returns it. For example, the following statement assigns the value 2.7178 to the variable a:
a = "2.7178 is the base of a natural logarithm.";


The eval Function
The eval() function has many uses in sophisticated programming techniques. Rather than looking for a number in a string, eval() looks for any valid JavaScript expression. A simple example assigns 25 to the a variable:
a = eval("20 + 1 + 4");
The use of eval() can be much more complicated than this. You can use any JavaScript expression in the string passed to eval()-numeric operations, comparison operations, statements, multiple statements, and even entire JavaScript functions. For example, the following statements define a variable called Fred and set its value to 31. The value of the text variable is used as the variable's name:
var text = "Fred";
var statement = text + "= 31";
eval(statement);
Because eval() can work with any expression, you can use it to perform calculations based on data entered by the user.

Session-3
Control Structures

The if...else Construct

The if statement is the main conditional statement in JavaScript. You can use it to check for certain values and act accordingly.
Here is an example of a basic if statement:
if (a == 1) document.write("Found a 1!");
This statement checks the variable a, and if it has a value of 1, prints a message. Otherwise, it does nothing. You can also use multiple statements by enclosing them in braces:
if (a == 1) 
{
   document.write("Found a 1!");
   a = 0;
}
This block of statements checks the variable a once again. If it finds a value of 1, it prints a message and sets a back to zero.
The if statement has an optional else keyword, which can specify a block of statements to execute if the condition is not true. Eg.
if (a == 1) 
{
   document.write("Found a 1!");
   a = 0;
}
else 
{
   document.write("Incorrect value: " + a);
   a = 0;
}
As you can see, you can follow the block of statements after the if keyword with an else keyword and a second block of statements. Only one of the blocks will be executed, depending on the condition.
Note


One of the most common errors is to use the assignment (=) operator in a conditional instead of the equality (==) operator. This can be especially confusing because the assignment will evaluate as a true condition. Be sure to check your conditions for this.

 

 

Conditional Expressions

In addition to the if statement, JavaScript provides a shorthand type of conditional expression that you can use to make quick decisions. This uses a peculiar syntax, which is also found in other languages, such as C. Here is an example of a conditional expression:
value = (a == 1) ? 1: 0;
This statement may look confusing, but it is equivalent to this if statement:
if (a == 1)
   value = 1;
else
   value = 0;
In other words, the value after the question mark (?) will be used if the condition is true, and the value after the colon (:) will be used if the condition is false. The colon represents the else portion of the statement, and like the else portion of the if statement, is optional.
For Loop
A for loop typically uses a variable (called a counter or index) to keep track of how many times the loop has executed, and it stops when the counter reaches a certain number. A basic for statement looks like this:
for (var = 1; var < 10; var++) {
There are three parameters to the for loop, separated by semicolons:
  • The first parameter (var = 1 in the example) specifies a variable and assigns an initial value to it. This is called the initial expression, because it sets up the initial state for the loop.
  • The second parameter (var < 10 in the example) is a condition that must remain true to keep the loop running. This is called the condition of the loop.
  • The third parameter (var++ in the example) is a statement that executes with each iteration of the loop. This is called the increment expression, because it is usually used to increment the counter.
for (i=1; i<10; i++) {
   document.write("This is line “ + i);
     document.write ("<br>");
}
This example displays a message including the loop's counter during each iteration. The output would look like this:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
Notice that the loop was executed only nine times. This is because i<10 is the conditional. When the counter (i) is incremented to 10, the expression is no longer true. If you need the loop to count to 10, you could change the conditional; either i<=10 or i<11 will work fine.
while Loops
The other keyword for loops in JavaScript is while. Unlike for loops, while loops don't necessarily use a variable to count. Instead, they execute as long as (while) a condition is true. In fact, if the condition starts out as false, the statements might not execute at all.
The while statement includes the condition in parentheses, and it is followed by a block of statements within braces, just like a for loop. As an example, here is a simple while loop:
while (total < 10) 
{
    statement or group of statements ;
}

Infinite Loops

The for and while loops allow you quite a bit of control over the loop. In some cases, this can cause problems if you're not careful. Take this loop, for example:
while (j < 10) 
{
n++;
values[n] = 0;
}
I've made a mistake in the previous example. The condition of the while loop refers to the j variable, but that variable doesn't actually change during the loop. This creates an infinite loop. The loop will continue executing until it is stopped by the user, or until it generates an error of some kind.
##Note : JavaScript won't give you an error that actually tells you there is an infinite loop.

The break Statement

There is one way out of an infinite loop. The break statement can be used during a loop to exit the loop immediately and continue with the first statement after the loop:
while (true) 
{
n++;
if (values[n] == 1) break;
}
Although the while statement is set up as an infinite loop, the if statement checks the corresponding value of an array, and if it finds a 1, it exits the loop.
Events and Event Handlers
In an object-oriented environment, events are often used to trigger portions of a program. In JavaScript, events pertain to the Web page containing the script. When the user clicks on a link, selects or enters text, or even moves the mouse over part of the page, an event occurs.

Types of Events

Event Name
Description
onAbort
Occurs when the user aborts the loading of an image
onBlur
Occurs when an object on the page loses focus
onChange
Occurs when a text field is changed by the user
onClick
Occurs when the user clicks on an item
onError
Occurs when a document or image can't load correctly
onFocus
Occurs when an item gains focus
onLoad
Occurs when the page (or an image) finishes loading
onMouseOver
Occurs when the mouse pointer moves over an item
onMouseOut
Occurs when the mouse pointer moves off an item
onSelect
Occurs when the user selects text in a text area
OnSubmit
Occurs when a submit button is pressed
OnUnload
Occurs when the user leav

Using Prompts, Alerts and Confirmation Dialogs

The window object includes three methods that are useful for displaying messages and interacting with the user:
  • The alert() method displays an alert dialog box. This dialog simply gives the user a message.
  • The confirm() method displays a confirmation dialog. This displays a message and includes OK and Cancel buttons. This method returns true if OK is pressed and false if Cancel is pressed.
  • The prompt() method displays a message and prompts the user for input. It returns the text entered by the user.
Example on Alert, Confirm and Prompt methods :
<HTML>
<HEAD>
<TITLE>Alerts, Confirmations, and Prompts</TITLE>
<SCRIPT Language="JavaScript">
Function ShowAlert()
{
    window.alert('Be Careful to Delete');
}
Function ConfirmShow()
{
var temp = window.confirm('Would you like to confirm?');
if(temp==true)
            window.alert('You Clicked Yes Button');
else
            window.alert('You Clicked No Button');
            window.status=(temp)?'confirm: true':'confirm: false';
}
Function PromptShow()
{
var myprompt=window.prompt('Enter Some Text Here','This ia s default text');
window.status=myprompt;
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Alerts, Confirmations, and Prompts</H1>
<HR>
    Use the buttons below to test dialogs in JavaScript.
<HR>
<FORM NAME="myform">
<INPUT TYPE="button" VALUE="Display an Alert" OnClick="ShowAlert()">
<P><INPUT TYPE="button" VALUE="Display a Confirmation" onClick="ConfirmShow()">
<P><INPUT TYPE="button" VALUE="Display a Prompt" OnClick="PromptShow()">
</FORM>
<BR>Have fun with JavaScript!
<HR>
</BODY>
</HTML>
 



 








  • The alert dialog is displayed when you click on the button.
  • The confirmation dialog displays when you press the button, and displays a message in the status line indicating whether true or false was returned. The returned value is stored in the temp variable.
  • The third button displays the prompt dialog. Notice that the prompt() method accepts a second parameter, which is used to set a default value for the entry. The value you enter is stored in the myprompt variable and displayed on the status line. Notice that if you press the Cancel button in the prompt dialog, the null value is returned.


Session –4
Working with Objects
Working with Objects and Events
JavaScript Objects
JavaScript is an object-oriented language. An object is a custom data type that can combine data with functions to act upon it. The data items in an object are its properties, and the functions are its methods.

Assigning Values to Properties

Let's create an imaginary type of object called Card, which will store business cards. The Card object has the following properties:
  • name
  • address
  • work_phone
  • home_phone
Assuming you had created a Card object called card1, you could define its properties using these statements:
card1.name = "Sherlock Holmes";
card1.address = "221B Baker Street";
card1.work_phone = "555-2345";
card1.home_phone = "555-3456";
Functions and Methods
Declaring a Function
A function is a set of JavaScript statements that accept one or more parameters and return a value.
Let's see an example of a function. One handy use for functions is to avoid repetitive use of complex HTML codes to output information. For example, consider the <TABLE> tag in HTML.
<TABLE>
<TR><TH>Name</TH><TH>Age</TH><TH>Birth Day</TH></TR>
<TR> <TD>Fred</TD> <TD>27</TD> <TD>June 17</TD> </TR>
<TR> <TD>Tom</TD> <TD>24</TD> <TD>March 13</TD> </TR>
<TR> <TD>Rebecca</TD> <TD>25</TD> <TD>November 30</TD> </TR>
</TABLE>
 A JavaScript program to print Same table as above.
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
document.write("<TABLE border=1 bordercolor=red width=80% align=center>\n");
document.write("<TR> <TH>Name</TH> <TH>Age</TH> <TH>Birth Day</TH> </TR>\n");
document.write("<TR> <TD>Fred</TD> <TD>27</TD> <TD>June 17</TD> </TR>\n");
document.write("<TR> <TD>Tom</TD> <TD>24</TD> <TD>March 13</TD> </TR>\n");
document.write("<TR> <TD>Rebecca</TD> <TD>25</TD> <TD>November 30</TD> </TR>\n");
document.write("</TABLE>");
</SCRIPT>
<BODY>
</BODY>
</HTML>
As you can see, this isn't exactly the most readable JavaScript program. A much better method is to use a function to perform the repetitive task-in this case.
The PrintRow function, for printing a table row.
function PrintRow(name, age, birthday) 
{
document.write("<TR> <TD>", name, "</TD> <TD>", age, "</TD> <TD>", birthday,
 "</TD> </TR>\n");
}
The first line of the function definition includes the function keyword, which is required to begin a function definition. The function name, PrintRow, is then given. The parameters the function will expect are in the parentheses; these are also the names of variables, local to the function, which will be defined to store the parameters passed.
The statements that comprise the function begin with the left brace. In the second line, the document.write function is used to output the parameters, with the proper HTML table tags between them. Because this is the final statement in the function, it ends with a right brace.
Tip
Not all functions have parameters. You can define a function that doesn't require any parameters by using an empty parameter list: ().

Calling a Function

In order to use the function,  you need to call the function. A function call is simply the name of the function and the parameters to send it.
document.write("<TABLE>\n");
PrintRow("Fred", 27, "June 17");
PrintRow("Tom", 24, "March 13");
PrintRow("Rebecca", 25, "November 30");
document.write("</TABLE>\n");
As you can see, although it's a simple one-line function, the PrintRow() function can save quite a bit of typing-especially if the table has more than three rows. It also creates more readable, clear JavaScript code.
The final scripting for the Table:
<HTML>
<HEAD>
<TITLE>JavaScript table test</TITLE>
<SCRIPT Llanguage="JavaScript">
Function PrintRow(name, age, birthday)
{
document.write("<TR> <TD>", name, "</TD> <TD>", age, "</TD> <TD>", birthday,
 "</TD> </TR>\n");
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Table Test Using JavaScript</H1>
<TABLE border bordercolor=red width=60% ALIGN=CENTER>
<TR> <TH>Name</TH> <TH>Age</TH> <TH>Birth Day</TH> </TR>
<SCRIPT LANGUAGE="JavaScript">
PrintRow("Fred", 27, "June 17");
PrintRow("Tom", 24, "March 13");
PrintRow("Rebecca", 25, "November 30");
</SCRIPT>
</TABLE>
</HTML>

Methods
Methods are simply functions that have been linked to an object and work on the properties of that object. As an example, the built-in string object includes some methods to work with strings. One of them, toLowerCase(), converts the string to all lowercase.
To call a method, you use a period to divide the string name and the method name, as with properties. However, because a method is a function, you must include parentheses for the parameters. In the case of the toLowerCase() method, there are no parameters. The following JavaScript code demonstrates the use of this method:
var text = "THIS IS UPPERCASE";
var ltext = text.toLowerCase();
Defining Objects and Methods
To define and use this object in a JavaScript program, you need to create a function to create new objects. This function is referred to as the object definition for an object, or the constructor. Here is an object definition for the Card object:
Function Card(name,address,work,home) 
{
   this.name = name;
   this.address = address;
   this.work_phone = work;
   this.home_phone = home;
}
The object definition is a simple function that accepts parameters to initialize a new object and assigns those to the corresponding properties. this keyword;  is required for object definitions and refers to the current object-the one that is being created by the function.
Next, let's create a method to work with the Card object. Let's call this function PrintCard().
Function PrintCard() 
{
   document.write("Name: ", this.name, "\n");
   document.write("Address: ", this.address, "\n");
   document.write("Work Phone: ", this.work_phone, "\n");
   document.write("Home Phone: ", this.home_phone, "\n");
}
This function simply reads the properties from the current object (this), prints each one with a caption, and skips to a new line.
Creating Instances of Objects
In order to use an object definition, you create a new object. This is done with the new keyword. The following statement creates a new Card object called tom:
tom = new Card("Tom Jones", "123 Elm Street", "555-1234", "555-9876");
Putting It All Together
An HTML document that uses the Card object.
<HTML>
<HEAD>
<TITLE>JavaScript Business Cards</TITLE>
<SCRIPT LANGUAGE="JavaScript">
Function PrintCard() 
{
   document.write("<B>Name:</B> ", this.name, "<BR>");
   document.write("<B>Address:</B> ", this.address, "<BR>");
   document.write("<B>Work Phone:</B> ", this.work_phone, "<BR>");
   document.write("<B>Home Phone:</B> ", this.home_phone, "<HR>");
}
Function Card(name,address,work,home) 
{
   this.name = name;
   this.address = address;
   this.work_phone = work;
   this.home_phone = home;
   this.PrintCard = PrintCard;
}
</SCRIPT>
</HEAD>
<BODY>
<H1>JavaScript Business Card Test</H1>
    Script begins here.<HR>
<SCRIPT LANGUAGE="JavaScript">
// Create the objects
sue = new Card("Sue Suthers", "123 Elm Street", "555-1234", "555-9876");
phred = new Card("Phred Madsen", "233 Oak Lane", "555-2222", "555-4444");
henry = new Card("Henry Tillman", "233 Walnut Circle", "555-1299", "555-1344");
// And print them
sue.PrintCard();
phred.PrintCard();
henry.PrintCard();
</SCRIPT>
    End of script.
</BODY>
</HTML>
The web page will be observed as follows:

Simple Calculation  ~Another Example
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
Function a_plus_b(form)
{
a=eval(form.a.value)
b=eval(form.b.value)
c=a+b
form.ans.value = c
}

Function a_minus_b(form)
{
a=eval(form.a.value)
b=eval(form.b.value)
c=a-b
form.ans.value=c
}

Function a_times_b(form)
{
a=eval(form.a.value)
b=eval(form.b.value)
c=a*b
form.ans.value=c
}

Function a_div_b(form)
{
a=eval(form.a.value)
b=eval(form.b.value)
c=a/b
form.ans.value = c
}

Function a_pow_b(form)
{
a=eval(form.a.value)
b=eval(form.b.value)
c=Math.pow(a, b)
form.ans.value = c
}
// End -->
</SCRIPT>
<BODY>
<CENTER>
<FORM name="formx">
<input type=text size=4 value=12 name="a">
<input type="button" value="  +  " onClick="a_plus_b(this.form)"> 
<input type="button" value="  -  " onClick="a_minus_b(this.form)"> 
<input type="button" value="  x  " onClick="a_times_b(this.form)"> 
<input type="button" value="  /  " onClick="a_div_b(this.form)"> 
<input type="button" value="  ^  " onClick="a_pow_b(this.form)"> 
<input type="number" size=4 value=3 name="b"> = <input type "number" value=0 name="ans" size=9>
</FORM>
</CENTER>
<p><center>
<font face="arial, helvetica" size="-2">Program in JavaScript<br>
by<br>
<a href="mailto:cse@unlimit.com">College of Software Engineering</a></font>
</center>
</BODY>
</HTML>
The Page Will Display as Follows:


Session-5

Using Built-In Objects and Functions

JavaScript includes several built-in objects. They are used for programming functions. These include the following:
  • You can use array objects to store numbered variables.
  • You can use String objects to manipulate strings of characters.
  • Date objects enable you to store and work with dates.

Using Array Objects

JavaScript did not include arrays, but they are now a built-in feature. You can create a new Array object to define an array. Use the new keyword to define an array:
students = new Array(30);
This example creates an array with 30 elements, numbered 0 through 29. You can use these values by addressing their array index:
students[29]="Phred Madsen";
This refers to the last element of the array, index 29.
The array object has three methods:
  • join() quickly joins all the array's elements, resulting in a string.
  • reverse() returns a reversed version of the array: the last element becomes the first, and the first element becomes the last.
  • sort() returns a sorted version of the array. Normally, this is an alphabetical sort
Example : Use of the Array object and its methods
<HTML>
<SCRIPT Language="JavaScript">
groceries = new Array(3);
groceries[0]="dental floss";
groceries[1]="baby powder";
groceries[2]="clam chowder";
document.write(groceries[0]);
document.write("<br>");
document.write(groceries[1]);
document.write("<br>");
document.write(groceries[2]);
document.write("<br>");
document.write(groceries.join());
document.write("<br>");
document.write(groceries.reverse().join());
document.write("<br>");
document.write(groceries.sort().join());
</SCRIPT>
<BODY>
</BODY>
</HTML>
Page shown by the above example :
Using String Objects
Any string variable in JavaScript is actually a String object. String objects have a single property, length. They also have a variety of methods that you can use to perform string functions.

String Conversions

Two methods of the String object enable you to convert the contents of the string easily to all uppercase or all lowercase:
  • toUpperCase() converts all characters in the string to uppercase.
  • toLowerCase() converts all characters in the string to lowercase.
For example, the following statement displays the value of the text string variable in lowercase:
document.write(text.toLowerCase());
Note that the statement doesn't change the value of the text variable. These methods return the upper- or lowercase version of the string, but they don't change the string itself. All of the methods of the String object work in this manner.

Working with Substrings

Three important String object methods enable you to work with substrings, or portions of strings. These methods are useful when you need to split a string into components or test portions of the string one at a time.
For example, suppose you defined a string called alpha to hold the alphabet:
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
The following are examples of the substring() method using this string:
  • alpha.substring(0,4) returns "ABC".
  • alpha.substring(10,12) returns "KL".
  • alpha.substring(12,10) also returns "KL". Because it's smaller, 10 is used as the first index.
  • alpha.substring(6,7) returns "G".
  • alpha.substring(24,26) returns "YZ".
  • alpha.substring(0,26) returns the entire alphabet.
  • alpha.substring(6,6) returns the null value, an empty string. This is true whenever the two index values are the same.
The second method for working with substrings is the charAt() method. This method is simpler: it takes a single index, and returns a single character. Here are a few examples using the alpha string defined previously:
  • alpha.charAt(0) returns "A".
  • alpha.charAt(12) returns "M".
  • alpha.charAt(25) returns "Z".
  • alpha.charAt(27) returns an empty string, because there is no character at that index

Searching a String

The indexOf() method searches for a string within another string. Use the string you wish to search for the method call and specify the string to be searched for in the parentheses. This example searches for "text" in the temp String object:
location = temp.indexOf("text");
You can specify an optional second parameter to indicate the index value to begin the search. For example, this statement searches for the word "fish" in the temp string, starting with the 20th character:
location = temp.indexOf("fish",19);
A second method, lastIndexOf(), works the same way, but finds the last occurrence of the string. It searches the string backwards, starting with the last character. For example, this statement finds the last occurrence of "Fred" in the names string:
location = names.lastIndexOf("Fred");

Links and Anchors

The link() and anchor() methods of String objects can be used to produce HTML for links and anchors. The value of the string is used as the actual link or anchor value, and the parameter specifies the link to jump to or the anchor to set. For example, the following statement sets an anchor called "test" using the value "This is a Test":
"This is a Test".anchor("test");
and this statement sets a link on the words "Click Here" to the anchor defined previously:
"Click Here".link("#test");

Using Date Objects

The Date object is a built-in JavaScript object that enables you to conveniently work with dates and times. You can create a Date object any time you need to store a date, and use the Date object's methods to work with the date.

Creating a Date Object

You can create a Date object using the new keyword.
birthday = new Date();
birthday = new Date("June 20, 1996 08:00:00");
birthday = new Date(6, 20, 96);
birthday = new Date(6, 20, 96, 8, 0, 0);
You can choose any of these formats, depending on which values you wish to set.
If you use no parameters, as in the first example, the current date is stored in the object.

Setting Date Values

A variety of set methods enable you to set components of a Date object to values:
  • setDate() sets the day of the month.
  • setMonth() sets the month. JavaScript numbers the months from 0 to 11, starting with January (0).
  • setYear() sets the year.
  • setTime() sets the time (and the date) by specifying the number of milliseconds since January 1st, 1970.
  • setHours(), setMinutes(), and setSeconds() set the time.

Getting Date Values

You can use the get methods to get values from a Date object. This is the only way to obtain these values, because they are not available as properties:
  • getDate() gets the day of the month.
  • getMonth() gets the month.
  • getYear() gets the year.
  • getTime() gets the time (and the date) as the number of milliseconds since January 1st, 1970.
  • getHours(), getMinutes(), and getSeconds() get the time.

Using Timeouts

Two more methods of the window object enable you to set timeouts.
The setTimeout() method  has two parameters. The first is a JavaScript statement, or group of statements, enclosed in quotes. The second parameter is the time to wait in milliseconds (thousandths of seconds). For example, this statement displays an alert dialog after 10 seconds:
ident=window.setTimeout("alert('Time's up!')",10000);
A variable (ident in this example) stores an identifier for the timeout. This enables you to set multiple timeouts, each with its own identifier. Before a timeout has elapsed, you can stop it with the clearTimeout() method, specifying the identifier of the timeout to stop:
window.clearTimeout(ident);
These timeouts execute only once; they do not repeat unless you set another timeout each time.
Example :
<HTML>
<HEAD>
<TITLE>Timeout Example</TITLE>
<SCRIPT Language="JavaScript">
var counter = 0;
// call Update function in 2 seconds after first load
ID=window.setTimeout("Update();",1000);
function Update()
{
   counter ++;
   window.status="The counter is now at " + counter;
   document.form1.input1.value="The counter is now at " + counter;
    // set another timeout for the next count
   ID=window.setTimeout("Update();",1000);
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Timeout Example</H1>
<HR>
The text value below and the status line are being updated every one second.
Press the RESET button to restart the count, or the STOP button to stop it.
<HR>
<FORM NAME="form1">
<INPUT TYPE="text" NAME="input1" SIZE="40"><BR>
<INPUT TYPE="button" VALUE="RESET" onClick="counter = 0;"><BR>
<INPUT TYPE="button" VALUE="STOP" onClick="window.clearTimeout(ID);">
<HR>
</BODY>
</HTML>
This program displays a message in the status line and in a text field every one second, including a counter that increments each time. You can use the RESET button to start the count over and the STOP button to stop the counting.
Example creating digital clock :
<HTML>
<HEAD>
<TITLE>JavaScript Clock</TITLE>
<SCRIPT Language="JavaScript">
Function showtime ()
{
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds()
    var timevalue=""
    if(hours>12)
                timevalue=hours-12;
    else
                timevalue+=hours
    if(minutes<10)
                timevalue+=":0"+minutes
    else
                timevalue+=":"+minutes
    if(seconds<10)
                timevalue+=":0"+seconds
    else
                timevalue+=":"+seconds
    if(hours>=12)
                timevalue+=" P.M. "
    else
                timevalue+=" A.M. "             
    document.myform.myclock.value=timevalue;
    window.status=timevalue;
        setTimeout("showtime()",1000);
}
</SCRIPT>
</HEAD>
<BODY onLoad="showtime()">
<FORM name="myform">
<input type="text" name="myclock" size=12>
</FORM>
</BODY>
</HTML>
Example : Scrolling Text in the Status Bar
<HTML>
<HEAD>
<TITLE>Scrolling Text</TITLE>
<SCRIPT Language="JavaScript">
window.status="This is a simple text scroll"
Function scroll()
{
    text=window.status;
    ftext=text.substring(0,1);
    text=text.substring(1);
    text+=ftext;
    window.status=text;
    setTimeout("scroll()",200)
}
</SCRIPT>
<BODY onload="scroll()">
<H3>Example of Scrolling text on the status bar</H3>
</BODY></HTML>

Session-6

The Navigator Object Hierarchy

Netscape Navigator builds an instance hierarchy that reflects the document being processed. As an instance hierarchy, the instance hierarchy works with the JavaScript approach to objects. The figure below shows the structure of the Navigator object hierarchy.
This hierarchy is important for creating references to objects and their properties. The children of an object are properties of the parent object. Because all objects are descendants of the window object, the window object itself is not referenced when referencing any object or property within the current window. For example, the reference to the instance of myform is document.myform. However, referencing a document in another window requires the addition of the window name to the object reference.

The Importance of HTML Layout

The proper use of JavaScript depends on having a basic understanding of how Netscape Navigator processes an HTML document. When an HTML document is loaded, the browser starts processing at the first line of the document. The browser lays out the screen in the order of the HTML statements in the document. After the screen is drawn, it cannot be redrawn without processing a new document. How this affects frames and windows is the topic of the next section.
The corollary to this is that an instance of an object exists only after encountering the HTML that generates the instance. Thus, JavaScript cannot reference an HTML object, such as a form, or execute a function until the browser processes the statement. For example, JavaScript cannot reference a form object until the browser processes the HTML for the form. Similarly, the changing of a property after the browser used the property in the layout of the window does not affect its value or appearance.
Although the constraints seem onerous, understanding the behavior of processing HTML and JavaScript saves a lot of frustration. The key principle to remember is that an HTML document is sequentially processed and JavaScript is part of that sequential process.

The Window Object

The window object is the parent of all objects. It includes the properties that define all windows and frames within a window. When the browser initially loads the HTML document, it starts with a single instance of a window object. If the HTML document creates frames, the frame information is stored in a frame array object. By the same token, opening a new window creates a child window object. The power of JavaScript lies in its capability to utilize the properties and methods of the window object. The objects that are properties of the window object are :
  • Location object
  • History object
  • Document object
Of the three, the document is the most important object in the hierarchy. The document object itself contains properties that refer to other objects. The most important of these are the following:
  • form object
  • anchor object
  • link object

The location Object

The location object contains information about the current URL. The reference to the object is as follows:
[windowReference.]location[.propertyName]
The properties of the location object refer to the individual parts of the URL:
protocol//hostname:port pathname search hash



The properties of the location object are as follows:
  • protocol. The protocol specifies the access method of the URL and includes everything up to the first colon.
  • hostname. The hostname contains the host and domain name, or IP address, of the destination host.
  • port. The port is the TCP/IP port as discussed in Chapter 1 "An Overview of Internet Programming." If the port property is empty, it defaults to the port specified for the protocol as defined in the services file.
  • pathname. The pathname specifies the path to the specified resource on the destination host.
  • search. The search property is a string that begins with a question mark and is used for CGI scripts.
  • hash. The hash property is a string that begins with a hash mark (#) and specifies an anchor name.
  • href. This property specifies the entire URL. If reference is made to [windowName.]location, the href property is assumed.
  • host. This property is equivalent to hostname:port.
Finding Out Where You Are  
This next example is a page that has no body. It is written entirely by the header script. As the page is written, it dissects the location object and lists all of its properties in a table. To see a non-empty location.search, you have to submit the little form included after the table. To see a non-empty location.search, click the dummy link and then Netscape's Reload button. The host, port, and hostname properties will be non-empty only if you have loaded some page from a server.
<HTML>
<HEAD>
<!-- Created 08 Feb 1996 a2:41 PM 02:41 PM -->
<TITLE>Parts of the Location Object</TITLE>
<SCRIPT>
var aline = '<H3><BR></H3><HR><H3><BR></H3>'
var skip='<H3><BR></H3>'
document.write('<CENTER>')
document.write('<FONT SIZE=5 COLOR="darkred"><B>Example : </B></FONT><FONT SIZE=5 COLOR="darkblue"><B>What is in the Location Object?</B></FONT>')
document.write('<BR>')
document.write('<BLOCKQUOTE><BLOCKQUOTE>If you are viewing this document from your hard disk, host, hostname, and port will be empty.</BLOCKQUOTE></BLOCKQUOTE>')
document.write('<CENTER><TABLE ALIGN= CENTER BORDER CELLPADDING=3>')
document.write('<TR><TD><B>Property</B></TD><TD ALIGN=CENTER>     <B>Value</B></TD></TR>')
document.write('<TR><TD>href</TD><TD>' + location.href + '</TD></TR>')
document.write('<TR><TD>protocol</TD><TD>' + location.protocol + '</TD></TR>')
document.write('<TR><TD>hostname</TD><TD>' + location.hostname + '</TD></TR>')
document.write('<TR><TD>host</TD><TD>' + location.host + '</TD></TR>')
document.write('<TR><TD>port</TD><TD>' + location.port + '</TD></TR>')
document.write('<TR><TD>pathname</TD><TD>' + location.pathname + '</TD></TR>')
document.write('<TR><TD>search</TD><TD>' + location.search + '</TD></TR>')
document.write('<TR><TD>hash</TD><TD>' + location.hash + '</TD></TR>')
document.write('</TABLE></CENTER>')
document.write('<CENTER>')
document.write('<FORM NAME="nameForm" >')
document.write('Your name\: <INPUT TYPE=text NAME="yourName" VALUE="John Smith" WIDTH=30 MAXLENGTH=30>')
document.write('<INPUT TYPE=submit VALUE="Click Me to Add a Search Parameter!" >')
document.write('</FORM>')
document.write('<A HREF=' + location.href + '#myAnchor >Click on me and then RELOAD to enter a hash parameter!</A>')
</SCRIPT>
</HEAD>
</HTML>
The Page will display like :

The History Object

The history object is a list that contains the locations of all the URLs that you have visited. You can move backward and forward through the history list with history.back and history.forward. You can also move around in the list in a relative fashion with history.go(). This function takes a positive or negative integer argument and moves you that many URLs forward or backward in the history list. The only property of a history list you can access is its length, which is the number of items in the list. You can neither set nor retrieve history list items.

Example :
<HTML>
<HEAD>
<TITLE>Running through the History List</TITLE>
<SCRIPT>
var aNoteWin
var myDummyVar = 'Apples, peaches, pumpkin pie...'
Function openNote(topic)
{
     aPopUp= window.open('','Note','toolbar=no,location=no,
     directories=no,status=no,scrollbars=yes,resizable=yes,  copyhistory=no,width=110,height=150')
     ndoc= aPopUp.document
     ndoc.close()
     ndoc.open()
     astr ='<HTML><HEAD><BR><TITLE>' + topic + '</TITLE>'
     astr +='<SCRIPT>'
     astr +='function closeNote(aName){'
     astr +='self.close()'
     astr +='}\n'
     astr +='function saveNote(aName){'
     astr +='}\n'
     astr +='function goNext(){'
     astr +='creator.history.forward()\n'
     astr +='}\n'
     astr +='function goBack(){'
     astr +='creator.history.back()\n'
     astr +='}\n'
     astr +='function goStart(){'
     astr += 'creator.history.go(-5)\n'
     astr +='}\n'
     astr +='function goEnd(){'
     astr +='creator.history.go(5)\n'
     astr +='}\n'
     astr +='<\/SCRIPT>'
     astr +='</HEAD>'
     ndoc.write(astr)
     astr ='<BODY>'
     astr +='<FORM NAME="popForm">'
     astr +='<TABLE ALIGN=LEFT BORDER>'
     astr +='</TR><TR ALIGN=CENTER><TD>'
     astr +='\<INPUT TYPE=button NAME=closeBtn VALUE="Close"         ONCLICK="closeNote()" \>'
     astr +='</TD>'
     astr +='</TR>'
     astr +='<TR><TD>'
     astr +='<INPUT TYPE="button" NAME="startBtn" VALUE=&lt;&lt;           onclick="goStart()">'
     astr +='<INPUT TYPE="button" NAME="backBtn" VALUE=&lt;            onclick="goBack()">'
     astr +='<INPUT TYPE="button" NAME="nextBtn" VALUE=&gt;            onclick="goNext()">'
     astr +='<INPUT TYPE="button" NAME="endBtn" VALUE=&gt;&gt;            onclick="goEnd()">'
     astr +='</TD></TR>'
     astr +='<TR><TD>'
     astr +='<INPUT TYPE="hidden" NAME="IAm" VALUE="0">'
     astr +='</TD></TR>'
     astr +='</TABLE>'
     astr +='</FORM>'
     astr +='<BR CLEAR=ALL><H3><BR></H3>'
     astr +='</BODY></HTML>'
     ndoc.write(astr)
     ndoc.close()
     self.aNoteWin = aPopUp
     self.aNoteWin.creator = self
     aNoteWin.document.popForm.startBtn.focus()
}
Function closeNote(which)
{
     self.aNoteWin.close()
}
</SCRIPT>
</HEAD>
<BODY >
<CENTER>
<FONT SIZE=5 COLOR='darkred'><B>Example 6</B></FONT>:
<FONT SIZE=5 COLOR='darkblue'><B>Running through the History List</B></FONT>
</CENTER>
<H3><BR><HR><BR></H3>
<BODY>
<H3><BR><HR><BR></H3>
<CENTER>
<FORM NAME='noteForm'>
<INPUT TYPE='button' NAME='makeBtn' VALUE='Make Popup' onclick='openNote("JoAnn Murphy at 7:00; bring salad.")'>
<INPUT TYPE='button' NAME='closeBtn' VALUE='Close Popup' onclick='closeNote()'>
</FORM>
</CENTER>
<H3><BR><HR><BR></H3>
<H3><BR><HR><BR></H3>
<H3><BR><HR SIZE=5 WIDTH=80%><BR></H3>
</BODY>
</HTML>
The Page will display as :

The document Object

The document object holds the properties, objects, and methods that define the presentation of the document. It refers to that part of the HTML document defined by the <BODY></BODY> tags.

The document Object Properties

The HTML options to the <BODY> tag define the document object properties. JavaScript references all of these properties, except for the background image.
The color document object properties are as follows:
  • bgColor. This property defines the background color of the document. The bgColor property immediately updates the display.
  • fgColor. This property defines the text color of the document. After the browser completes the layout of the HTML document, the browser ignores changes to this property. Instead, the <FONT> tag or the fontcolor method provide an alternative mechanism for changing the text color.
  • linkColor. The linkColor represents the color of a link defined by HREF, without prior visits. As with all color involving the links, the colors change after the user selects the link.
  • alinkColor. This property controls the color of an active link. In other words, it is the color of the link after it is selected and before the destination host replies.
  • vlinkColor. After the user visits a site, the browser displays this color for the link.

The document Object Methods

The document object contains five methods:
  • document.write()
  • document.writeln()
  • document.open()
  • document.close()
  • document.clear()


Session – 7
Windows and Frames
Windows and frames create more confusion for Web page developers than any other aspect of the browser. When Netscape Navigator starts, it opens a window and, depending on how the options are set, loads a document into the window. If you select the menu option File | New Web Browser, a new window is opened. In this case, closing the original window does not close the new window.
On the other hand, frames are created according to the <FRAMESET></FRAMESET> tags in the HTML document. It subdivides the screen's real estate into a number of frames. When the document that defined the frames is closed, the frames go away because their existence depends on the document.
The Window Object Properties
One of the major features of JavaScript is its capability to create and manipulate windows. These windows are not limited to just displaying messages; depending on the parameters set, they can be another instance of the browser. The following properties of the window object reflect the flexibility of the browser window:
  • defaultStatus. The defaultStatus is the message that appears in the status bar when no other message is being displayed. If it is set from a onMouseOver event handler, the event handler must return true for the status to change.
  • frames. This property is an array that contains the frame objects. The frame inherits all of the properties and methods of the window object.
  • length. The value of this property is the number of frames in the frame array.
  • parent. From a frame reference, this is the window that the frameset resides in. A frame within the frameset can reference another frame in the frameset by using parent.frames[index] without having to reference the window by name.
  • self. This is a synonym for the current window or frame.
  • status. This is a transient message that is set by the onMouseOver event handler.
  • top. This property is used to reference the topmost window. It can be used by child windows or embedded filesets to reference the originating window.
  • window. This property is a synonym for the current window.
The forms for referencing window properties are

window.propertyName

self.propertyName

top.propertyName

parent.propertyName

windowVar.propertyName

propertyName
The Window Object Methods
The following are the window or frame object methods:
  • alert("message"). This method creates an alert dialog box with a single OK button. It is used to display a message that does not require a user decision.
  • close(). This method closes the referenced window. It must contain a window reference such as window.close as close() with no reference is the equivalent of document.close.
  • confirm("message"). The confirm method displays a confirm dialog box with OK and Cancel buttons. OK returns a value of true, and Cancel returns a value of false.
  • [windowVar = ][window.]open("URL", "windowName" ["windowFeatures"]. This method opens a new Web browser window. The object name windowVar is the name of the new window and is used to reference its properties and methods. The URL specifies the URL to open in the new window. If the option is null, a blank window is opened. The variable windowName is the name used in the TARGET attribute of the <FORM> and <A> tags. The variable windowFeatures is a comma-separated list of the following options:

toolbar=yes|no

location=yes|no

directories=yes|no

status=yes|no

menubar=yes|no

scrollbars=yes|no

resizable=yes|no

width=pixels

height=pixels

  • If no features are set, all features default to true. If any feature is explicitly set, all features default to false. If a feature is set without specifying the value, the value is true. These features refer to the components of the Navigator window. Thus, location refers to the location entry field and directories refers to the standard Navigator buttons.
NOTE
After it is created, the window is independent of the parent window; if the parent window closes, the window created remains open. The onUnLoad event handler closes the windows created
  • prompt("message" [, inputDefault]). The prompt method displays a prompt dialog box with a message, an input field, an OK button, and a Cancel button. The inputDefault is a string, integer, or property of an object that represents the default value for the input field. If the inputDefault is not specified, the input field displays the value <undefined>.
  • timeoutID=setTimeout(expression, msec). With this method, the evaluation of the expression is delayed for the number of milliseconds specified. The timeoutID is only used by the clearTimeout method.
  • clearTimeout(timeoutID). This method cancels the time-out set by the setTimeout method.
The preceding methods are referenced as follows:

window.methodName(parameters)

self.methodName(parameters)

top.methodName(parameters)

parent.methodName(parameters)

windowVar.methodName(parameters)

methodName(parameters)

Dividing the Window into Frames
Frames divide a window into multiple, independently scrollable frames on a single screen. Frames are created via the <FRAMESET></FRAMESET> tags in an HTML document. Each document creates a frame array for that document. If a document opened in one of the frames contains a <FRAMESET> tag, that frame is divided into frames by that document. This hierarchy of framesets is important in referencing the properties and methods of frames.
A Windows Example
<HTML>
<HEAD>
<TITLE>JavaScript Windows Example</TITLE>
<SCRIPT LANGUAGE="JAVASRIPT">
<!--
var win4Open=false
Function winTest4()
{
   winTst4=window.open("", "winS", "resizable,width=200,height=100")
   winTst4.document.open()
   winTst4.document.write("<H1>Test 4</H1>")
   winTst4.document.close()
   win4Open=true
}
Function endIt()
{
   if (win4Open) winTst4.close()
}
// -->
</SCRIPT>
</HEAD>
<BODY onUnLoad='endIt()'>
<H1 ALIGN="CENTER">A JavaScript Windows Example</H1>
<P>HTML lacks the means to create windows. Frames, yes -- windows ,no. The best way to learn about the behavior of windows is to play with this script.</P>
<HR>
<FORM>
<P>This window test generates a new instance of the browser, with this document as the opening document. Close the first instance
of the browser to see what happens.<BR><BR>
<INPUT TYPE="button" NAME="test1" VALUE="Open Test 1"    onClick='window.open("window.htm")'></P>
<HR>
<P>By declaring a named windowed object, it is still possible to create multiple instance of the browser.<BR><BR>
<INPUT TYPE="button" NAME="test2" VALUE="Open Test 2” onClick='winTST2 = indow.open("window.htm")'></P>
<HR>
<P>When the name argument to window.open is provided, it cannot another copy with a duplicate name. Instead, it reopens the same document.<BR><BR>
<INPUT TYPE="button" NAME="test3" VALUE="Open Test 3"  onClick='winTST3 = indow.open("window.htm", "winTest")'></P>
<HR>
<P>This final test shows away to use the onUnLoad option to close any windows created. You can run test 1 or 2 and run this test from another instance of the browser.<BR><BR>
<INPUT TYPE="button" NAME="test4" VALUE="Open Test 4"    onClick='winTest4()'></P>
</FORM>
</BODY>
</HTML>
The web page will display as follows:


Session – 8
Using form Objects in JavaScript
Before you continue working with the order form, let's look at the way JavaScript handles form data. Each form in your HTML page is represented in JavaScript by a form object. The form object has the same name as the NAME attribute in the <FORM> tag you used to define it.
Alternately, you can use the forms array to refer to forms. This array includes an item for each form element, indexed starting with zero. For example, if the first form in a document has the name form1, you can refer to it in one of two ways:
document.form1
document.forms[0]
Form Object Properties
The most important property of the form object is the elements array, which contains an object for each of the form elements. You can refer to an element by its own name or by its index in the array. For example, these expressions both refer to the first element in the order form, the name1 text field:
document.order.elements[0]
document.order.name1
The JavaScript form Object Hierarchy
Text Fields and Password Fields
Text fields are the simplest field to work with in JavaScript. Password fields are nearly identical; the main difference is that the text is not displayed. The text and password objects have the following properties:
  • name is the name given to the field. This is also used as the object name.
  • defaultValue is the default value; this corresponds to the VALUE attribute. This is a read-only property.
  • value is the current value. This starts out the same as the default value, but can be changed-either by the user or by JavaScript functions.
Most of the time when you work with text fields, you will use the value attribute to read the value the user has entered, or to change the value. For example, this statement changes the value of a text field called organisation  in the order form to "College of Software Engineering":
document.order.username.value = "College of Software Engineering"
Text Field Methods
The text and password objects also have a few methods you can use:
  • focus() sets the focus to the field. This positions the cursor in the field and makes it the "current" field.
  • blur() is the opposite; it removes the focus from the field.
  • select() selects the text in the field, just as a user can do with the mouse. You cannot currently select only part of a field.
Text Field Events
The text and password objects support the following event handlers:
  • The onFocus event happens when the text field gains focus.
  • The onBlur event happens when the text field loses focus.
  • The onChange event happens when the user changes the text in the field, then moves out of it.
  • The onSelect event happens when the user selects some or all of the text in the field. Unfortunately, there's no way to tell exactly which part of the text was selected.
If used, these event handlers should be included in the <INPUT> tag declaration. For example, the following is a text field including an onChange event that displays an alert:
<INPUT TYPE="TEXT" NAME="text1" onChange="window.alert('Changed.');">
Text Areas
Text areas are defined with their own tag, <TEXTAREA>, and are represented by the textarea object. This object includes the same properties, methods, and event handlers as the text and password objects. For example, this <TEXTAREA> tag includes an onFocus event handler to change the status line:
<TEXTAREA NAME="text2" onFocus = "window.status = 'got focus.';">Default Value</TEXTAREA>
There is one difference about a text area's value: it can include more than one line.
Checkboxes
A checkbox is simple: it has only two states. Nevertheless, the checkbox object has four different properties:
  • name is the name of the checkbox, and also the object name.
  • value is the "true" value for the checkbox-usually on. This value is used by the server to indicate that the checkbox was checked. In JavaScript, you should use the checked property instead.
  • defaultChecked is the default status of the checkbox, assigned by the chECKED attribute.
  • checked is the current value (true for checked, and false for unchecked).
To manipulate the checkbox or use its value, you use the checked attribute. For example, this statement turns on a checkbox called same in the order form:
document.order.same.checked = true;
The checkbox has a single method, click(). This method simulates a click on the box. It also has a single event, onClick, which occurs whenever the checkbox is clicked. This happens whether the box was turned on or off, so you'll need to check the checked property.
Radio Buttons
Radio buttons are similar to checkboxes, but an entire group of them shares a single name and a single object. You can refer to the following properties of the radio object:
  • name is the name common to the radio buttons.
  • length is the number of radio buttons in the group.
To access individual buttons, you treat the radio object as an array. The buttons are indexed, starting with 0. Each individual button has the following properties:
  • value is the value assigned to the button. (This is used by the server.)
  • defaultChecked indicates the value of the chECKED attribute and the default state of the button.
  • checked is the current state.
For example, you can check the first radio button in the radio1 group on the form1 form with this statement:
document.form1.radio1[0].checked = true;
However, if you do this, be sure you set the other values to false as needed. This is not done automatically. You can use the click method to do both of these in one step.
Like a checkbox, radio buttons have a click() method and an onClick event handler. Each radio button can have a separate statement for this event.
Selection Lists
A selection list is similar to radio buttons, because the entire group of options shares a name. In this case, the data for each element is stored in the options array, which indexes the different options starting with 0.
The object for selection lists is the select object. The object itself has the following properties:
  • name is the name of the selection list.
  • length is the number of options in the list.
  • options is the array of options (explained later).
  • selectedIndex returns the index value of the currently selected item. You can use this to check the value easily. In a multiple-selection list, this indicates the first selected item.
The options array has a single property of its own, length, which indicates the number of selections. In addition, each item in the options array has the following properties:
  • index is the index into the array.
  • defaultSelected indicates the state of the SELECTED attribute.
  • selected is the current state of the option. Setting this property to true selects the option. You can select multiple options if the MULTIPLE attribute is included in the <SELECT> tag.
  • name is the value of the NAME attribute. This is used by the server.
  • text is the text that is displayed in the option. In Netscape 3.0 or later, you can change this value.
The select object has two methods, blur() and focus(). These perform the same purpose as the corresponding methods for text objects. The event handlers are onBlur, onFocus, and onChange, also similar to other objects.
Hidden Fields
Hidden fields are stored in hidden objects. This object has two properties, name and value. These function similarly to a text field. There are no methods or event handlers for the hidden object-it can't be changed, so the user can't really mess with a hidden field.
Buttons
Buttons can be defined as SUBMIT buttons, RESET buttons, or generic BUTTON buttons. All of these types have the same properties, methods, and events.
Buttons support the name property, used to identify the button, and the value property, which defines the button's text. You cannot change either of these values. Buttons support a single method, click(), and an event handler, onClick.
The onClick action is performed with any button. In the case of a generic button, nothing else happens. In a SUBMIT or RESET button, you can prevent the submission or resetting by returning a false value.
File Upload Fields
A relatively new feature of Netscape enables you to define a file upload field on a form. This enables the user to upload a file to the server. You can define a file upload field with an <INPUT> tag:
<INPUT TYPE="file" NAME="fname">
Because this field is mainly for interacting with the server, JavaScript has little control over it. A FileUpload object represents the field, and you can access two properties:
  • name is the name of the field, as defined in the <INPUT> tag.
  • value is the name of the file (if any) the user is uploading.

Session – 9
Automations and Validations
Validating the Form Data with Event Handlers
The final feature you can add to a form with JavaScript is perhaps the most important: validation. This means checking each field to ensure that it contains a proper value and advising the user if it is incorrect.
Which Fields to Validate?
When choosing how to handle validation for a form, the first step is to decide which fields you need to validate and what to check for. For some items, such as a name, the most you can do is see whether anything is entered.
For other items you can be more specific; for example, if your form asked for the user's age, you can check for numbers over 100
For the Order Form, let's use the following validation criteria:
  • The name must be at least 6 characters, and the billing address and shipping address must be at least 30 characters. The phone number must be at least 10 characters. (You want them to include the area code.)
  • The e-mail address must be at least 5 characters and include the @ symbol.
  • Because the cost fields are calculated automatically, you won't bother validating them. However, you'll check the total cost; if it's 0 or blank, they haven't ordered anything.
  • If the payment method is anything but cash, the credit card number/check number field must be at least 2 characters.
Lets see the Order form :

The HTML tags behind the form is like :
<HTML>
<HEAD>
<TITLE>Order Form</TITLE>
</HEAD>
<BODY>
<H1>CSE Book Order Form</H1>
<FORM NAME="order">
<B>Name:</B> <INPUT TYPE="text" NAME="name1" SIZE=20>
<B>Phone: </B><INPUT TYPE="text" NAME="phone" SIZE=15>
<B>E-mail address:</B><INPUT TYPE="text" NAME="email" SIZE=20><BR>
<B>Billing and Shipping Addresses:</B>
<INPUT TYPE="CHEKBOX" NAME="same" onClick="CopyAddress();">
Ship to Billing Address
<BR>
<TEXTAREA NAME="billto" COLS=40 ROWS=4>
Enter your billing address here.
</TEXTAREA>
<TEXTAREA NAME="shipto" COLS=40 ROWS=4>
Enter your shipping address here.
</TEXTAREA>
<br>
<B>Products to Order:</B><BR>
Qty: <INPUT TYPE="TEXT" NAME="qty1" VALUE="0" SIZE=4>
Cost: <INPUT TYPE="TEXT" NAME="cost1" SIZE=6>
(Rs.400.00)Mastering Acces XP 
<BR>
Qty: <INPUT TYPE="TEXT" NAME="qty2" VALUE="0" SIZE=4>
Cost: <INPUT TYPE="TEXT" NAME="cost2" SIZE=6>
(Rs.800.00) Mastering Visual  basic 6.0
<BR>
Qty: <INPUT TYPE="TEXT" NAME="qty3" VALUE="0" SIZE=4>
Cost: <INPUT TYPE="TEXT" NAME="cost3" SIZE=6>
(Rs. 1400.00) SQL Server 2000
<BR>
Qty: <INPUT TYPE="TEXT" NAME="qty4" VALUE="0" SIZE=4>
Cost: <INPUT TYPE="TEXT" NAME="cost4" SIZE=6>
(Rs.2400.00)Oracle 8i and D2K <HR>
<B>Total Cost:</B>
<INPUT TYPE="TEXT" NAME="totalcost" SIZE=8><HR>
<B>Method of Payment</B>:
<SELECT NAME="payby">
<OPTION VALUE="check" SELECTED>Check or Money Order
<OPTION VALUE="cash">Cash or Cashier's Check
<OPTION VALUE="credit">Credit Card (specify number)
</SELECT><BR>
<B>Credit Card or Check Number:</B>:
<INPUT TYPE="TEXT" NAME="creditno" SIZE="20"><BR>
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Send Your Order">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>
Creating Functions for Validation
Based on the decisions made previously, you now need to create a function to handle each of the fields. In some cases, you can use the same function for multiple fields. Let's start with the simplest function: checking for the proper length. This function will work with the name, billing address, and phone number fields.
Function ValidLength(item, len)
{
   return (item.length >= len);
}
This function expects the name of an item and the required length. It simply checks whether the item is greater than or equal to that length, and it returns true or false appropriately.
Next, let's create a function for the e-mail address. This will simply call the ValidLength function to check the length, then use the indexOf string method to check for the @ sign:
//function to validate an email address
Function ValidEmail(item)
{
   if (!ValidLength(item, 5)) return false;
   if (item.indexOf ('@', 0) == -1) return false;
   return true;
}
Finally, let's create a main validation routine. This routine validates all the fields one at a time, then returns true or false:
Function Validate()
{
   errfound = false;
   if (!ValidLength(document.order.name1.value,6))
      error(document.order.name1,"Invalid Name");
   if (!ValidLength(document.order.phone.value,10))
      error(document.order.phone,"Invalid Phone");
   if (!ValidLength(document.order.billto.value,30))
      error(document.order.billto,"Invalid Billing Address");
   if (!ValidLength(document.order.shipto.value,30))
      error(document.order.shipto,"Invalid Shipping Address");
   if (!ValidEmail(document.order.email.value))
      error(document.order.email, "Invalid Email Address");
   if (document.order.totalcost.value == "")
      error(document.order.qty1, "Please Order at least one item.");
   if (document.order.payby.selectedIndex != 1)
     {
      if (!ValidLength(document.order.creditno.value,2))
         error(document.order.creditno,"Invalid Credit/Check number");
      }
   return !errfound; /* true if there are no errors */
}
As you can see, this function includes tests for the length-related functions and the e-mail address; in addition, I have added checks for the credit card number and the total cost. If any of these checks fails, an error routine is called:
function error(elem, text)
{
// abort if we already found an error
   if (errfound) return;
   window.alert(text);
   elem.select();
   elem.focus();
   errfound = true;
}
Automating the Form with JavaScript
Adding Automatic Totals
Function to update cost when quantity is changed
Function UpdateCost(number, unitcost)
{
   costname = "cost" + number;
   qtyname = "qty" + number;
   var q = document.order[qtyname].value;
   document.order[costname].value = q * unitcost;
   Total();
}

Function to calculate the total cost field
Function Total()
{
   var tot = 0;
   tot += (400.00 * document.order.qty1.value);
   tot += (800.00 * document.order.qty2.value);
   tot += (1400.00 * document.order.qty3.value);
   tot += (2400.00 * document.order.qty4.value);
   document.order.totalcost.value = tot;
}
Automating the Shipping Address
Because the order form includes spaces for separate billing and shipping addresses, it's a good idea to give the user an option to use the same address for both. Using JavaScript, you can add such an option easily-and it makes for a neat bit of automation.
Function to copy billing address to shipping address
Function CopyAddress()
{
   if (document.order.same.checked)
   {
      document.order.shipto.value = document.order.billto.value;
   }
}
Adding an Event Handler for Automation and Validation
Finally we use event handlers for the automations and validations as :
<INPUT TYPE="chECKBOX" NAME="same" onClick="CopyAddress();">
Qty: <INPUT TYPE="TEXT" NAME="qty1" VALUE="0" SIZE=4 onChange = "UpdateCost(1, 400.00);">
<INPUT TYPE="BUTTON" NAME="submit" VALUE="Send Your Order" onClick="Validate()">
The Final Complete Validated  Order form look like :
<HTML>
<HEAD>
<TITLE>Order Form</TITLE>
 <SCRIPT>
//Function to Autamate Total cost
Function UpdateCost(number, unitcost)
{
   costname = "cost" + number;
   qtyname = "qty" + number;
   var q = document.order[qtyname].value;
   document.order[costname].value = q * unitcost;
   Total();
}

// Function to calculate the total cost field
function Total()
{
   var tot = 0;
   tot += (400.00 * document.order.qty1.value);
   tot += (800.00 * document.order.qty2.value);
   tot += (1400.00 * document.order.qty3.value);
   tot += (2400.00 * document.order.qty4.value);
   document.order.totalcost.value = tot;
}

// Function to copy billing address to shipping address
Function CopyAddress()
{
   if (document.order.same.checked) {
      document.order.shipto.value = document.order.billto.value;
   }
}

//global variable for error flag
var errfound = false;

//Function to Validate by length
Function ValidLength(item, len)
{
   return (item.length >= len);
}
//function to validate an email address
Function ValidEmail(item)
{
   if (!ValidLength(item, 5)) return false;
   if (item.indexOf ('@', 0) == -1) return false;
   return true;
}
//display the error message
Function error(elem, text)
{
// abort if we already found an error
   if (errfound) return;
   window.alert(text);
   elem.select();
   elem.focus();
   errfound = true;
}

//main validation function
Function Validate()
{
   errfound = false;
   if (!ValidLength(document.order.name1.value,6))
      error(document.order.name1,"Invalid Name");
   if (!ValidLength(document.order.phone.value,10))
      error(document.order.phone,"Invalid Phone");
   if (!ValidLength(document.order.billto.value,30))
      error(document.order.billto,"Invalid Billing Address");
   if (!ValidLength(document.order.shipto.value,30))
      error(document.order.shipto,"Invalid Shipping Address");
   if (!ValidEmail(document.order.email.value))
      error(document.order.email, "Invalid Email Address");
   if (document.order.totalcost.value == "")
      error(document.order.qty1, "Please Order at least one item.");
   if (document.order.payby.selectedIndex != 1)
     {
      if (!ValidLength(document.order.creditno.value,2))
         error(document.order.creditno,"Invalid Credit/Check number");
     }
   return !errfound; /* true if there are no errors */
}
</SCRIPT>
<BODY>
<H1>CSE Book Order Form</H1>
<FORM NAME="order">
<B>Name:</B> <INPUT TYPE="text" NAME="name1" SIZE=20>
<B>Phone: </B><INPUT TYPE="text" NAME="phone" SIZE=15>
<B>E-mail address:</B><INPUT TYPE="text" NAME="email" SIZE=20><BR>
<B>Billing and Shipping Addresses:</B>
<INPUT TYPE="chECKBOX" NAME="same" onClick="CopyAddress();" onClick="CopyAddress()">
Ship to Billing Address
<BR>
<TEXTAREA NAME="billto" COLS=40 ROWS=4 onChange="CopyAddress()">
Enter your billing address here.
</TEXTAREA>
<TEXTAREA NAME="shipto" COLS=40 ROWS=4 onChange="CopyAddress();">
Enter your shipping address here.
</TEXTAREA>
<br>
<B>Products to Order:</B><BR>
Qty: <INPUT TYPE="TEXT" NAME="qty1" VALUE="0" SIZE=4 
onChange="UpdateCost(1,400.00)">
Cost: <INPUT TYPE="TEXT" NAME="cost1" SIZE=6>
(Rs.400.00)Mastering Acces XP 
<BR>
Qty: <INPUT TYPE="TEXT" NAME="qty2" VALUE="0" SIZE=4 onChange="UpdateCost(2,800.00)">
Cost: <INPUT TYPE="TEXT" NAME="cost2" SIZE=6>
(Rs.800.00) Mastering Visual  basic 6.0
<BR>
Qty: <INPUT TYPE="TEXT" NAME="qty3" VALUE="0" SIZE=4 onChange="UpdateCost(3,1400.00)">
Cost: <INPUT TYPE="TEXT" NAME="cost3" SIZE=6>
(Rs. 1400.00) SQL Server 2000
<BR>
Qty: <INPUT TYPE="TEXT" NAME="qty4" VALUE="0" SIZE=4 onChange="UpdateCost(4,2400.00)">
Cost: <INPUT TYPE="TEXT" NAME="cost4" SIZE=6>
(Rs.2400.00)Oracle 8i and D2K <HR>
<B>Total Cost:</B>
<INPUT TYPE="TEXT" NAME="totalcost" SIZE=8><HR>
<B>Method of Payment</B>:
<SELECT NAME="payby">
<OPTION VALUE="check" SELECTED>Check or Money Order
<OPTION VALUE="cash">Cash or Cashier's Check
<OPTION VALUE="credit">Credit Card (specify number)
</SELECT><BR>
<B>Credit Card or Check Number:</B>:
<INPUT TYPE="TEXT" NAME="creditno" SIZE="20"><BR>
<INPUT TYPE="BUTTON" NAME="submit" VALUE="Send Your Order" onClick="Validate()">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>

No comments:

Post a Comment

Thanks for comment me