0% found this document useful (0 votes)
43 views53 pages

Chap-5 Javascript

Chapter 5 of the Internet Programming Lecture Note covers JavaScript programming, highlighting its use in web design, form validation, and browser detection. It explains the differences between interpreted and compiled languages, the syntax for including JavaScript in HTML, and various input-output methods such as alert and prompt boxes. Additionally, it discusses variable declaration, data types, operators, and comments in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views53 pages

Chap-5 Javascript

Chapter 5 of the Internet Programming Lecture Note covers JavaScript programming, highlighting its use in web design, form validation, and browser detection. It explains the differences between interpreted and compiled languages, the syntax for including JavaScript in HTML, and various input-output methods such as alert and prompt boxes. Additionally, it discusses variable declaration, data types, operators, and comments in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 53

Internet Programming Lecture Note

Chapter 5
JavaScript Programming
5.1 Introduction
JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, create cookies, and much more. JavaScript is the most popular scripting language on
the internet, and works in all major browsers, such as Internet Explorer, Firefox, and Opera.

Scripting languages are usually interpreted rather than compiled. That means that a software
routine called an interpreter translate a program’s statements into machine code, code
understandable by a particular type of computer, before executing them every time the program
is run. Compiled languages, on the other hand, are translated into machine code and stored for
later execution. When the compiled program is run, it executes immediately without further need
of inFaterpretation; it was interpreted into machine code when it was compiled. Because
programs written in interpreted languages must be translated into machine code every time they
are run, they are typically slower than compiled programs. However, this does not usually
present a problem for the small applications for which scripting languages are generally used.
Being interpreted does have its advantages. One is platform independence. Because an
interpreter performs the translation, we can write the program once and run it on a variety of
platforms. In the case of JavaScript, the interpreter is built into Web browsers. Browsers are
available for a variety of platforms and operating systems. Another advantage is that scripting
languages are often loosely typed and more forgiving than compiled languages.
5.2 Purposes of Java script :-
 JavaScript gives HTML designers a programming tool - JavaScript is a scripting
language with a very simple syntax!
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: [Link]("<h1>" + name + "</h1>") can write a variable text into an HTML
page
 JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
 JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
 JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer
5.3 Running the JavaScript
Any time including JavaScript in an HTML document, we must enclose those lines inside a
<SCRIPT>...</SCRIPT> tag pair. These tags alert the browser program to begin interpreting all
the text between these tags as a script. Because other scripting languages (such as Microsoft’s
VBScript) can take advantage of these script tags, we must specify the precise name of the

Page 1 of 53
Internet Programming Lecture Note
language in which the enclosed code is written. Therefore, when the browser receives this signal
that our script uses the JavaScript language, it employs its built-in JavaScript interpreter to
handle the code.

JavaScript is case-sensitive. Hence, we must enter any item in our script that uses a JavaScript
word with the correct uppercase and lowercase letters. HTML tags (including the <SCRIPT>
tag) can be in the case of our choice, but everything in JavaScript is case-sensitive. JavaScript
should be pt between the following :-
<SCRIPT LANGUAGE=”text/JavaScript”>
//your script here
</SCRIPT>
Or
<SCRIPT type=”text/JavaScript”>
//your script here
</SCRIPT>
As shown above, the attribute name called LANGUAGE & TYPE can be used interchangeably.
But, commonly we use type attribute.
Here are some tips to remember when writing JavaScript commands:
 JavaScript code is case sensitive (e.g. age and Age are different variables)
 White space between words and tabs are ignored
 Line breaks are ignored except within a statement
 JavaScript statements end with a semi colon (;) but not always

Javascript can come at different places. There is a flexibility given to include JavaScript code
anywhere in an HTML document. But there are following most preferred ways to include
JavaScript in an HTML file.

 Script in <head>...</head> section.


 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in and external file and then include in <head>...</head> section.

 Wherever we use/ define a JavaScript block in our web page, simply use the following block
of HTML.
<script type='text/JavaScript'>
// Your script goes here.
</script>
 We can place these script blocks anywhere on the page that we wish, there are some rules
and conventions however.
 But, for external external File, Use the SRC attribute of the <SCRIPT> tag to call JavaScript
code from an external text file.
 This is useful if we have a lot of code or we want to run it from several pages, because any
number of pages can call the same external JavaScript file. The text file itself contains no
HTML tags. It is called by the following tag:
<SCRIPT type = "JavaScript" SRC = " url of javascript file">

Page 2 of 53
Internet Programming Lecture Note
</SCRIPT>
 If we want to run the same JavaScript on several pages, without having to write the same
script on every page, we can write a JavaScript in an external file. Save the external
JavaScript file with a .js file extension. The external script cannot contain the <script>
</script> tags. To use the external script, point to the .js file in the "src" attribute of the
<script> tag.
 JavaScripts is put in a page where it will be executed immediately while the page loads into
the browser. Sometimes we want to execute a script when a page loads, or at a later event,
such as when a user clicks a button.

Script between <head>…..</head>


Scripts to be executed when they are called, or when an event is triggered, are placed in
functions. Put functions in the head section, this way they are all in one place, and they do not
interfere with page content.
<html>
<head>
<script language="javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>

Scripts in <body>…..</head> tags


If we don't want our script to be placed inside a function, or if our script should write page
content, it should be placed in the body section.
<html>
<head> </head>
<body>
<script language="javascript">
[Link]("This message is written by JavaScript");
</script>
</body>
</html>
Scripts in both <head>…..</head> and <body>…..</body> tags
We can place an unlimited number of scripts in our document, so we can have scripts in both the
body and the head section.
5.4 Input-Output in Java/ Message Boxes
In JavaScript, input-output can be done in different ways:
 [Link] method writes a string to the web page. Anything between double quotes
will be displayed as it is in the web page. However, if there is something out of quotes, it is
evaluated as expression and the result will be sent to the web page.

Page 3 of 53
Internet Programming Lecture Note
 The alert method is produces a browser alert box. These are incredibly useful for debugging
and learning the language. However, they are not good way to communicate with the users.
An alert box is often used if we want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed. The Syntax is
[Link]("sometext"); or simply write as alert(“some text”)
Example belows:-
<html>
<head>
<script language="javascript">
[Link]("This message is written by JavaScript");
function message()
{
alert("message to display");
}
</script>
</head>
<body onload="message()">
<br><br><br><br><br><br>
<h1>I THANK YOU FOR EVERY THING YOU MADE!!!</H1>
</body>
</html>
 Prompt box:- is used to allow a user to enter something according to the promotion. It is
written as [Link]("please enter your name") or simply write as prompt(“some
text”)
Example:-
<script>
var y=[Link]("please enter your name")
[Link](y)
</script>
 Confirm Box:- A confirm box is often used if we want the user to verify or accept
something. When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false. It has the following Syntax [Link]("sometext"); or simply write
confirm(“some text”)
Example1:
<script type=”text/javascript”>
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!"; }
else
{ x="You pressed Cancel!"; }
[Link] (x);
</script>
Example 2:-
<script>

Page 4 of 53
Internet Programming Lecture Note
var x=[Link]("Are you sure you want to quit")
if (x)
[Link]("Thank you.")
else
[Link]("Good choice.")
</script>
 The Page Printing:- JavaScript helps us to implement this functionality using print function
of window object. The JavaScript print function [Link]() will print the current web
page when executed. We can call this function directly using onclick event as follows:
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="[Link]()" />
</form>
</body>
5.5 Working with Variables and Data
Data in java script may be text information displayed on the screen by a JavaScript statement or
the on/off setting of a radio button in a form. Each single piece of information in programming is
also called a value. Outside of programming, the term value usually connotes a number of some
kind; in the programming world, however, the term is not as restrictive. A string of letters is a
value. A number is a value. The setting of a check box (whether it is checked or not) is a value.
In JavaScript, a value can be one of several types as shown bellow:-

Type Example Description


String “John” a series of characters inside quotation marks
Number 4.5 any number not inside quotes
Boolean True a logical true or false
Null Null completely devoid of any value
Object a software thing that is defined by its properties and
methods
Table JavaScript data types
i. Declaring Variables
To declare variable, we use the var keyword, followed by the name we want to give to
the variable. JavaScript variables can be declared with the var keyword as var
variablename;
To declare a new variable called myAge, the JavaScript statement is var myAge;
Variable names obey number of restrictions (rules).
 Don’t use any reserved keyword as a variable name.
 A variable name cannot contain space characters. Therefore, one-word variable
names are fine. For example, the followings are invalid:- var my_age; var
myAge;

Page 5 of 53
Internet Programming Lecture Note
 Variable names should avoid all punctuation symbols except for the underscore
character. Also, the first character of a variable name cannot be a numeral.
 To put together, a variable name can contain letters of the alphabet, both capital
and small, number and _(underscore). Still, the name should start with letters of
the alphabet, or _, not digits
Example: see the following correct variable declaration,
var firstName;
var weight;
var he89;
var TH_;
Example: Wrong variable names:
Var first name; //space not allowed
Var 89he; //can’t start with digit
Var TH.; //punctuation mark not allowed
ii. Assigning Values to Variables
After the declaration shown above, the variables are empty which means they have no
data values yet. After declaring a variable, it is possible to assign a value to it by using
equal sign (=) as follows:
var myAge;
myAge = 25;
However, we can also assign values to the variables as:
var age=5;
[Link] Values to Undeclared Variables
To assign values to variables that have not yet been declared, the variables will
automatically be declared. These statements:
age=5;
The above statements have the same effect as:
var age=5;
iv. Redeclaring JavaScript Variables
If we redeclare a JavaScript variable, it will not lose its original value.
var age=5;
var age;
After the execution of the statements above, the variable x will still have the value of 5.
The value of x is not reset (or cleared) when we redeclare it.

5.6 JavaScript Comments


Comments are ignored by the interpreter. The purpose of including comments is to remind us
how our script works after long period has passed when we see our code. JavaScript supports
two types of comments:
Comments on a single line are preceded by a double-slash (//).
Comments that span multiple lines are preceded by /* and followed by */
5.7 Operators and Expressions
An operator performs some kind of calculation (operation) or comparison with two values to
reach a third value. Generally, operators can be broadly categorized into two: mathematical
operators, and comparison and logical operators.

Page 6 of 53
Internet Programming Lecture Note
i. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between variables or values. +, -,
*, /, %, ++, --
ii. JavaScript Assignment Operators
Assignment operators are used to perform arithmetic operation and then assign the result to
variables. Includes:- =, +=, -=, *=, /= and %=
iii. Comparison Operators
Comparison operators help to compare two or more values — whether two values are equal, for
example. These kinds of comparisons return a value of the Boolean type — true or false.
Includes:- >, >=, <, <=, ==, and !=
iv. Logical Operators
Logical operators are used to determine the logic between variables or values:- &&, ||
V. The Bitwise Operators:

There are following bitwise operators supported by JavaScript language Assume variable A
holds 2 and variable B holds 3 then:

Operato
Description Example
r

& Called Bitwise AND operator. It performs a (A & B) is 2 .


Boolean AND operation on each bit of its integer
arguments.

| Called Bitwise OR Operator. It performs a (A | B) is 3.


Boolean OR operation on each bit of its integer
arguments.

^ Called Bitwise XOR Operator. It performs a (A ^ B) is 1.


Boolean exclusive OR operation on each bit of its
integer arguments. Exclusive OR means that either
operand one is true or operand two is true, but not
both.

~ Called Bitwise NOT Operator. It is a is a unary (~B) is -4 .


operator and operates by reversing all bits in the
operand.

<< Called Bitwise Shift Left Operator. It moves all (A << 1) is 4.


bits in its first operand to the left by the number of
places specified in the second operand. New bits
are filled with zeros. Shifting a value left by one
position is equivalent to multiplying by 2, shifting

Page 7 of 53
Internet Programming Lecture Note
two positions is equivalent to multiplying by 4,
etc.

>> Called Bitwise Shift Right with Sign Operator. It (A >> 1) is 1.


moves all bits in its first operand to the right by the
number of places specified in the second operand.
The bits filled in on the left depend on the sign bit
of the original operand, in order to preserve the
sign of the result. If the first operand is positive,
the result has zeros placed in the high bits; if the
first operand is negative, the result has ones placed
in the high bits. Shifting a value right one place is
equivalent to dividing by 2 (discarding the
remainder), shifting right two places is equivalent
to integer division by 4, and so on.

>>> Called Bitwise Shift Right with Zero Operator. (A >>> 1) is 1.


This operator is just like the >> operator, except
that the bits shifted in on the left are always zero,

Operator Precedence
Individual operators Operator type
[] member
() new call / create instance
! ~ - + ++ -- typeof negation/increment
void delete
* / % multiply/divide
+- addition/subtraction
<< >> >>> bitwise shift
< <= > >= in instanceof relational
== != === !== equality
& bitwise-and
^ bitwise-xor
| bitwise-or
&& logical-and
|| logical-or
?: Conditional
= += -= *= /= %= <<= assignment

Page 8 of 53
Internet Programming Lecture Note
>>= >>>= &= ^= |=
, comma
Table operator precedence Java Script

5.8 Java Scrpit Statements

A. Working with Conditional Statements


Conditional statements are used to perform different actions based on different conditions.
Broadly, there are two ways to execute code conditionally:
 If statement
 switch statement
i. If condition/if -----else condition:- The simplest program decision is to follow a special
branch or path of the program if a certain condition is true. Formal syntax for this
construction follows:
if (condition) {
statement[s] if true
}
The keyword if is a must. In the parentheses goes an expression that evaluates to a Boolean
value. This is the condition being tested as the program runs past this point. If the condition
evaluates to true, then one or more statements inside the curly braces execute before continuing
on with the next statement after the closing brace. If the condition evaluates to false, then the
statements inside the curly brace are ignored and processing continues with the next statement
after the closing brace. Items in italics are replaced with expressions and statements that fit the
situation.
The formal syntax definition for an if...else construction is as follows:
if (condition) {
statement(s) if true
}
[else if(condition){
statement(s) if true
}]
[else {
statement(s) if false
}]
Where [] indicates optional parts of the JavaScript code.
Example1:-
<script type="text/javascript">
var d = new Date()
var time = [Link]()
if (time<10)
{ [Link]("<b>Good morning</b>"); }
else if (time>10 && time<16)

Page 9 of 53
Internet Programming Lecture Note
{ [Link]("<b>Good day</b>"); }
else
{ [Link]("<b>Hello World!</b>"); }
</script>
Example:-
<script type="text/javascript">
var book = "maths";
if( book == "history" ){
[Link]("<b>History Book</b>");
}else if( book == "maths" ){
[Link]("<b>Maths Book</b>");
}else if( book == "economics" ){
[Link]("<b>Economics Book</b>");
}else{
[Link]("<b>Unknown Book</b>");
}
</script>
ii. Switch Statement:- A switch statement allows a program to evaluate an expression and
attempt to match the expression's value to a case label. If a match is found, the program
executes the associated statement. A switch statement looks as follows:
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
[break;]
}
Example 1:-
<script type="text/javascript">
var d=new Date();
theDay=[Link]();
switch (theDay)
{ case 5: [Link]("Finally Friday");
break;
case 6: [Link]("Super Saturday");
break;
case 0: [Link]("Sleepy Sunday");
break;
default:
[Link]("I'm looking forward to this weekend!"); }
</script>
The program first looks for a case clause with a label matching the value of expression. If found,
it then transfers control to that clause, executing the associated statements. If no matching label

Page 10 of 53
Internet Programming Lecture Note
is found, the program looks for the optional default clause. If no default clause is found, the
program continues execution at the statement following the end of switch. By convention, the
default clause is the last clause.

If break is omitted, the program continues execution at the next statement in the switch statement
when there is a matched statement.
Example 2:
switch (fruittype) {
case "Apples":
[Link]("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
[Link]("Bananas are $0.48 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
[Link]("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
[Link]("Sorry, we are out of " + fruittype + ".<br>");
}

Example 3:-
<script type="text/javascript">
var grade='A',’B’;
[Link]("Entering switch block<br />");
switch (grade)
{
case 'A': [Link]("Good job<br />");
case 'B': [Link]("Pretty good<br />");
case 'C': [Link]("Passed<br />");
case 'D': [Link]("Not so good<br />");
case 'F': [Link]("Failed<br />");
default: [Link]("Unknown grade<br />")
}
[Link]("Exiting switch block");
</script>
B. Working with Loops
A loop is a set of commands that executes repeatedly until a specified condition is met, and
JavaScript supports loop like for, do while, and while loop statements. In addition, we can use
the break and continue statements within loop statements.
i. for Loop
A for loop repeats until a specified condition evaluates to false. A syntax of for statement is:-
for ([initialization]; [condition]; [increment]){ Statement(s)}
Example 1: a program that adds numbers from 0 to 10
var counter = 100;
var sum = 0;

Page 11 of 53
Internet Programming Lecture Note
for (var i = 0; i <= counter; i++) {
sum = sum + i;
}
[Link](“the sum is ” + sum);

Example 2:-
<html> <body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
[Link]("The number is " + i); [Link]("<br />");
}
</script>
</body>
</html>
ii. do...while Statement
The do...while statement repeats until a specified condition evaluates to false. A do...while
statement written as follows:
do{
statement
}while (condition);
statement executes once before the condition is checked. If condition is true, the statement
executes again. At the end of every execution, the condition is checked. When the condition is
false, execution stops and control passes to the statement following do...while.
Example: the do loop iterates at least once and reiterates until i is no longer less than 5.
i=1;
do
{
i += 1;
[Link](i);
} while (i < 5);
iii. while Statement
A while statement executes its statements as long as a specified condition evaluates to true. A
while statement looks as follows:
while (condition){
statement
}
The condition test occurs before statement in the loop are executed. If the condition returns true,
statement is executed and the condition is tested again. If the condition returns false, execution
stops and control is passed to the statement following while.
<html>
<body>

Page 12 of 53
Internet Programming Lecture Note
<script type="text/javascript">
var i=0;
while (i<=10)
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
</script>
<I>THANK YOU BEING UNDERSTAND ME</I>
</body>
</html>

iv. for...in loop


 This loop is used to loop through an object's properties.

 Syntax:

for (variablename in object){


statement or block to execute
}
 In each iteration one property from object is assigned to variablename and this loop
continues till all the properties of the object are exhausted.

Example: The following example that prints out the properties of a Web browser's Navigator
object:
<script type="text/javascript">
var aProperty;
[Link]("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
[Link](aProperty);
[Link]("<br />");
}
[Link]("Exiting from the loop!");
</script>
Test the output?

v. Break, continue and lablel statements:-

These are used to come out of a loop without reaching at its bottom or to skip a part of the code
block and want to start next iteration of the look when needed by users or programmers.

To handle all such situations, JavaScript provides break, label and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any loop.

Example1: the following example loops until the value of loop counter is 5:
for (i = 0; i < 100; i++) {
if (i== 5)
break;
}

Page 13 of 53
Internet Programming Lecture Note
The continue statement can be used to restart a while, do-while, for, or label statement. When we
use continue, it terminates the current iteration and continues execution of the loop with the next
iteration. In contrast to the break statement, continue does not terminate the execution of the loop
entirely. In a while loop, it jumps back to the condition check, and in a for loop, it jumps to the
increment-expression. But, break statement is used to terminate loop.
Example 2: a program that adds numbers between 0 and 100 with the exception of 60, 70, and
80

<script type=”text/javascript”>
var counter = 100;
var sum = 0;
for (var i = 0; i <= counter; i++)
{
if(i==60 || i==70 || i==80)
continue;
sum = sum + i;
}
[Link](“the sum is ” + sum);
</script>

Using Labels to Control the Flow:


A label can be used with break and continue to control the flow more precisely. A label is
simply an identifier followed by a colon that is applied to a statement or block of code.

Note: Line breaks are not allowed between the continue or break statement and its label name.
Also, there should not be any other statement in between a label name and associated loop.

Example 1:
<script type="text/javascript">
<!--
[Link]("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++)
{
[Link]("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++)
{
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
[Link]("Innerloop: " + j + " <br />");
}
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>

Page 14 of 53
Internet Programming Lecture Note

This will produce following result:

Entering the loop!


Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!

To understand it in better way you can Try it yourself.

Example 2:
<script type="text/javascript">
<!--
[Link]("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
[Link]("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
[Link]("Innerloop: " + j + "<br />");
}
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>

This will produce following result:

Entering the loop!


Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2

Page 15 of 53
Internet Programming Lecture Note
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!

C. Using Arrays
An array is an ordered collection of data. In JavaScript, arrays are limited to a table holding one
column of data, with as many rows as needed to hold data.
A JavaScript-enabled browser creates a number of internal arrays for the objects in HTML
documents and browser properties. For example, if our document contains five links, the browser
maintains a table of those links. To access them by number (with 0 being the first link) in the
array syntax as in [Link][0], which represents the first link in the document.

 To initialize an array for script, use the new keyword to construct the object for
assigning the array object to a variable of our choice like:
var myArray = new makeArray(n) where n is the number of entries anticipated for the
array. This initialization does not make any array entries or create any placeholders.
Example: an array that stores the names of planets
planet = new Array(9); //an array with 9 entries
planet[0] = “Mercury”
planet[1] = “Venus”
planet[2] = “Earth”
planet[3] = “Mars”
planet[4] = “Jupiter”
planet[5] = “Saturn”
planet[6] = “Uranus”
planet[7] = “Neptune”
planet[8] = “Pluto”
The index number starts at 0 and end at n-1 for array of n entries to access them. For
example, to access the fifth planet in the planets array, we use:
planet[4]; //Jupiter
 To deleting array entries, we can always set the value of an array entry to null or an
empty string to wipe out any data that used to occupy that space. But with the delete
operator, we could not completely remove the element. Deleting an array element eliminates
the index from the list of accessible index values but does not reduce the array’s length.
[Link]; // result: 9
delete planet[2];
[Link]; //result: 9
planet[2]; //result: undefined

Page 16 of 53
Internet Programming Lecture Note
 Array Object Methods
o [Link](array2):- The [Link]() method allows to join two array objects into a
new array object. The action of concatenating the arrays does not alter the contents or
behavior of the two original arrays.
For example:
var array1 = new Array(1,2,3)
var array2 = new Array(“a”,”b”,”c”)
var array3 = [Link](array2) // result: array with values 1,2,3,”a”,”b”,”c”
If an array element is a string or number value (not a string or number object), the values are
copied from the original arrays into the new one. All connection with the original arrays ceases
for those items.
o [Link]([compareFunction]):- This methods returns array of entries in the order as
determined by the compareFunction algorithm.
For simple alphabetical sorting of string values in arrays, the plain [Link]() method does the
trick. A comparison function is passed two values from the array. The comparison function lets
the sort() method know which of the two items comes before the other, based on the value the
function returns. Assuming that the function compares two values, a and b, the returned value
reveals information to the sort() method:

Example: a function that sorts numbers


<html>
<head>
<title>JavaScript Array sort Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array('12', '5', '100', '1', '200', '80');
var sorted = [Link]();
[Link]("Returned string is : " + sorted );
</script>
</body>
</html>
Other array object methods
Description
Method

every() Returns true if every element in this array satisfies the provided
testing function.
filter() Creates a new array with all of the elements of this array for which
the provided filtering function returns true.
forEach() Calls a function for each element in the array.

indexOf(value) Returns the first (least) index of an element within the array equal to
the specified value, or -1 if none is found.
join(separator) Joins all elements of an array into a string using separator

Page 17 of 53
Internet Programming Lecture Note
lastIndexOf(value) Returns the last (greatest) index of an element within the array equal
to the specified value, or -1 if none is found.
pop() Removes the last element from an array and returns that element.

push(value) Adds one or more elements to the end of an array and returns the new
length of the array.
reverse() Reverses the order of the elements of an array − the first becomes the
last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.

slice(start [,end]) Extracts a section of an array and returns a new array.

splice(start, count) Adds and/or removes elements from an array.

toString() Returns a string representing the array and its elements.

unshift(value) Adds one or more elements to the front of an array and returns the
new length of the array.
Table array object methods

Example 1: On some array functions


<html>
<head>
<title>javascript test</title>
<script language="JavaScript">
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");
[Link]("<br> Popped: " + [Link]());
[Link]("<br> After poping:");
for(var i=0;i<[Link]; i++)
[Link](" " + grade[i]);

[Link]();
[Link]("<br>Reversed: ");
for(var i=0;i<[Link]; i++)
[Link](" " + grade[i]);
[Link]("<br>Search 80: " + [Link]("80"));
[Link]("<br>Converted to string: " + [Link]());
[Link]("<br>Sliced: " + [Link](2));
[Link]("<br>Spliced: " + [Link](1));
}
</script>
</head>
<body onLoad="arrayFunction();">
</body>
</html>
Example2:- Filter example
<html>
<head>

Page 18 of 53
Internet Programming Lecture Note
<title>JavaScript Array filter Method</title>
</head>
<body>
<script type="text/javascript">
if (![Link])
{
[Link] = function(fun /*, thisp*/)
{
var len = [Link];
if (typeof fun != "function")
throw new TypeError();

var res = new Array();


var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if ([Link](thisp, val, i, this))
[Link](val);
}
}

return res;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
[Link]("Filtered Value : " + filtered );

</script>
</body>
</html>

This will produce following result: Filtered Value: 12, 130, 44

Example 3:- sort example


<html>
<head>
<title>JavaScript Array sort Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");

var sorted = [Link]();


[Link]("Returned string is : " + sorted );

</script>
</body>
</html>
Returned array is : banana,mango,orange,sugar
Example 4:- on push
<html>
<head>
<title>JavaScript Array push Method</title>
</head>

Page 19 of 53
Internet Programming Lecture Note
<body>
<script type="text/javascript">
var numbers = new Array(1, 4, 9);

var length = [Link](10);


[Link]("new numbers is : " + numbers );

length = [Link](20);
[Link]("<br />new numbers is : " + numbers );
</script>
</body>
</html>

This will produce following result:

new numbers is : 1,4,9,10


new numbers is : 1,4,9,10,20

5.9 JavaScript Functions


Functions are one of the fundamental building blocks in JavaScript. A function is a set of
statements that performs a specific task. To use a function, we must first define it; then the script
can be called it.
In function definition, it consists of the function keyword, followed by:
 The name of the function.
 A list of arguments to the function, enclosed in parentheses and separated by commas.
The JavaScript statements that define the function, enclosed in curly braces, { }. The statements
in a function can include calls to other functions defined in the current application. The syntax to
define function:
function functionName ( [parameter1]...[,parameterN] ) {
statement[s]
}
Function names have the same restrictions as variable names. It is possible to use multiword
names with the interCap (internally capitalized) format that start with a verb because functions
are action items.
Example: the following code defines a simple function named square:
function square(number) {
return number * number;
}
The function square takes one argument, called number. The function consists of one statement
that indicates to return the argument of the function multiplied by itself. The return statement
specifies the value returned by the function.
Example:-
<html>
<head>
<script type="text/javascript">
// If alert("Hello world!!") below had not been written within a
// function, it would have been executed as soon as the page gets loaded.
function displaymessage() {

Page 20 of 53
Internet Programming Lecture Note
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

 Function Parameters:- Functions receive parameter values from the calling statement.
Parameters (also known as arguments) provide a mechanism for “handing off” a value
from one statement to another by way of a function call. If no parameters occur in the
function definition, both the function definition and call to the function have only empty
sets of parentheses. When a function receives parameters, it assigns the incoming values
to the variable names specified in the function definition’s parentheses. Consider the
following script segment:
function sayHiToFirst(first, second, third) {
alert(“Say hello, “ + first)
}
sayHiToFirst(“Gracie”, “George”, “Harry”)
sayHiToFirst(“Larry”, “Moe”, “Curly”)

After the function is defined in the script, the next statement calls function, passing three strings
as parameters. The function definition automatically assigns the strings to variables first, second,
and third. Therefore, before the alert() statement inside the function ever runs, first evaluates to
“Gracie,” second evaluates to “George,” and third evaluates to “Harry.” In the alert() statement,
only the first value is used and the alert reads
Say hello, Gracie

When the user closes the first alert, the next call to the function occurs. This time through,
different values are passed to the function and assigned to first, second, and third. The alert
dialog box reads
Say hello, Larry
Unlike other variables that defined in script, function parameters do not use the var keyword to
initialize them. They are automatically initialized whenever the function is called. Example :-
function getCookie(c_name)
{
if ([Link]>0)
{
c_start=[Link](c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=[Link](";",c_start);
if (c_end==-1) c_end=[Link]; return
Page 21 of 53
Internet Programming Lecture Note
unescape([Link](c_start,c_end));
}
} return "";
}

The function above first checks if a cookie is stored at all in the [Link] object. If the
[Link] object holds some cookies, then check to see if our specific cookie is stored. If
our cookie is found, then return the value, if not - return an empty string. Last, we create the
function that displays a welcome message if the cookie is set, and if the cookie is not set it will
display a prompt box, asking for the name of the user:
function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{ alert('Welcome again '+username+'!'); }
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}} }
The above two codes can come together as follow:
<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if ([Link]>0)
{
c_start=[Link](c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=[Link](";",c_start);
if (c_end==-1) c_end=[Link];
return unescape([Link](c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
[Link]([Link]()+expiredays);
[Link]=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+[Link]());
}
function checkCookie()
{ username=getCookie('username');

Page 22 of 53
Internet Programming Lecture Note
if (username!=null && username!="")
{ alert('Welcome again '+username+'!'); }
else {
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{ setCookie('username',username,365);
}}}
</script>
</head>
<body onLoad="checkCookie()">
</body> </html>
The example above runs the checkCookie() function when the page loads. As indicated above,
the return statement is used to specify the value that is returned from the function. So, functions
that are going to return a value must use the return statement. The example below returns the
product of two numbers (a and b):
<html>
<head>
<script type="text/javascript">
function product(op1, op2){
return op1*op2;
}
</script>
</head>
<body>
<script type="text/javascript">
[Link](product(4,3));
</script>
</body>
</html>
Example:- to exponensial
<html>
<head>
<title>Javascript Method toExponential()</title>
</head>
<body>
<script type="text/javascript">
var num=77.1234;
var val = [Link]();
[Link]("[Link]() is : " + val );
[Link]("<br />");

val = [Link](4);
[Link]("[Link](4) is : " + val );
[Link]("<br />");

val = [Link](2);
[Link]("[Link](2) is : " + val);
[Link]("<br />");

val = [Link]();
[Link]("[Link]()is : " + val );
[Link]("<br />");

Page 23 of 53
Internet Programming Lecture Note
val = [Link]();
[Link]("77 .toExponential() is : " + val);
</script>
</body>
</html>
Example:- concatenate
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = [Link]( str2 );

[Link]("Concatenated String :" + str3);


</script>
</body>

<!-- Mirrored from [Link]/cgi-bin/[Link]?file=javascript_76 by HTTrack


Website Copier/3.x [XR&CO'2013], Wed, 25 Dec 2013 [Link] GMT -->
</html>

Example:- replace
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">

var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = [Link](re, "$2, $1");
[Link](newstr);

</script>
</body>

<!-- Mirrored from [Link]/cgi-bin/[Link]?file=javascript_82 by HTTrack


Website Copier/3.x [XR&CO'2013], Wed, 25 Dec 2013 [Link] GMT -->
</html>
Example:- To lower case
<html>
<head>
<title>JavaScript String toLowerCase() Method</title>
</head>
<body>
<script type="text/javascript">

Page 24 of 53
Internet Programming Lecture Note
var str = "Apples are round, and Apples are Juicy.";

[Link]([Link]( ));
</script>
</body>

<!-- Mirrored from [Link]/cgi-bin/[Link]?file=javascript_90 by HTTrack


Website Copier/3.x [XR&CO'2013], Wed, 25 Dec 2013 [Link] GMT -->
</html>
5.10 Working with JavaScript Objects
JavaScript is an Object Oriented Programming (OOP) language. A JavaScript object has
properties and methods
Example: String JavaScript object has length property and toUpperCase() method
<script type="text/javascript">
var txt="Hello World!"
[Link]([Link])
[Link]([Link]())
</script>
As shown above, [Link] and [Link] can be used in JavaScript to
built-in objects that we can use to perform different activities. JavaScript Built-in Objects such
as String, Date, Array, Boolean and Math. The common and important objects in JavaScript are
discussed bellow:-

i. Math Object:-
The predefined Math object has properties and methods for mathematical constants and
functions. For example, the Math object’s PI property has the value of pi (3.141...), which we
would use in an application as [Link]. Similarly, standard mathematical functions are methods
of Math. These include trigonometric, logarithmic, exponential, and other functions. For
example, if we want to use the trigonometric function sine, we would write: [Link](1.56).
Note that all trigonometric methods of Math take arguments in radians.

Math Object Properties

Property Value Description


Math.E 2.718281828459045091 Euler’s constant
Math.LN2 0.6931471805599452862 Natural log of 2
Math.LN10 2.302585092994045901 Natural log of 10
Math.LOG2E 1.442695040888963387 Log base-2 of E
Math.LOG10E 0.4342944819032518167 Log base-10 of E
[Link] 3.141592653589793116 Π
Math.SQRT1_2 0.7071067811865475727 Square root of ½
Math.SQRT2 1.414213562373095145 Square root of 2
Table Math object properties

Page 25 of 53
Internet Programming Lecture Note
Functions of the Math Object
 abs (x): returns the absolute value of x; the result has the same magnitude as x but has
positive sign.
 acos (x): returns the arc cosine of x. The result is expressed in radians and ranges from +0 to
+π.
 asin (x): returns the arc sine of x. The result is expressed in radians and ranges from −π/2 to
+π/2.
 atan (x): returns the arc tangent of x. The result is expressed in radians and ranges from −π/2
to +π/2. atan2 (y, x)
 cos (x): returns the cosine of x. The argument is expressed in radians.
Example: [Link](0);
 exp (x): returns the exponential function of x (e raised to the power of x, where e is the base
of the natural logarithms). Example: [Link](3);
 floor (x): returns the greatest number that is not greater than x and is equal to a mathematical
integer. If x is already an integer, the result is x. The value of [Link](x) is the same as the
value of -[Link](-x).
 ceil (x): returns the smallest (closest to −∞) number value that is not less than x and is equal
to a mathematical integer. If x is already an integer, the result is x. The value of [Link](x)
is the same as the value of -[Link](-x).
Example:
[Link](1.6); //result: 1
[Link](1.6); //result: 2
log (x): returns the natural logarithm of x.
Example:
[Link](20);
 max ( [ value1 [ , value2 [ , ... ] ] ] ):- used to return the largest of the resulting values from
the given arguments.
 min ( [ value1 [ , value2 [ , ... ] ] ] ):- uses to return the smallest of the resulting values i.e
arguments.
 pow (x, y): returns result of raising x to the power y. Example: [Link](5,2); //output: 25

 random ( ):- Returns a number value with positive sign, greater than or equal to 0 but less
than 1, chosen randomly or pseudo randomly with approximately uniform distribution over
that range. This function takes no arguments.
 round (x):- Returns the number value that is closest to x and is equal to a mathematical
integer. If two integer number values are equally close to x, then the result is the number
value that is closer to +∞. If x is already an integer, the result is x.
Example:
[Link](3.5); // output: 4
[Link](–3.5); //output: –3.
Example:- this example uses to show how we use math objects.
<html><body><script type="text/javascript">
[Link]([Link](0.60) + "<br />");
[Link]([Link]());
[Link]([Link](5,7) + "<br />");

Page 26 of 53
Internet Programming Lecture Note
[Link]([Link](5,7) + "<br />");
[Link]([Link](7.25,7.30));
</script> </body> </html>
The value of [Link](x) is the same as the value of [Link](x+0.5), except when x
is −0 or is less than 0 but greater than or equal to -0.5; for these cases [Link](x)
returns −0, but [Link](x+0.5) returns +0.
 sin (x): returns the sine of x. The argument is expressed in radians.
Example: [Link](90);
 sqrt (x): returns the square root of x.
 tan (x): returns the tangent of x. The argument is expressed in radians.

ii. Date Object


Most of date and time work is done with the Date object. The basic syntax for generating a new
date object is as follows:
var dateObjectName = new Date([parameters])
The parameter can be:
new Date(“Month dd, yyyy hh:mm:ss”)
new Date(“Month dd, yyyy”)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)

Method Value Range Description


[Link]() 0-... returns Milliseconds since 1/1/70 [Link] GMT
[Link]() 70-... returns Specified year minus 1900
returns four-digit year for 2000+
[Link]() 1970-... returns four-digit year (Y2K-compliant)
[Link]() 0-11 returns Month within the year (January = 0)
[Link]() 1-31 returns Date within the month
[Link]() 0-6 returns Day of week (Sunday = 0)
[Link]() 0-23 returns Hour of the day in 24-hour time
[Link]() 0-59 returns Minute of the specified hour
[Link]() 0-59 returns Second within the specified minute
[Link](val) 0-... sets Milliseconds since 1/1/70 [Link] GMT
[Link](val) 70-... sets Specified year minus 1900
sets four-digit year for 2000+
[Link](val) 0-11 sets Month within the year (January = 0)
[Link](val) 1-31 sets Date within the month
[Link](val) 0-6 sets Day of week (Sunday = 0)
[Link](val) 0-23 sets Hour of the day in 24-hour time

Page 27 of 53
Internet Programming Lecture Note
[Link](val) 0-59 sets Minute of the specified hour
[Link](val) 0-59 sets Second within the specified minute
Table Date object methods
Example: display current date and time
today = new Date();
var date = [Link]();
var month = [Link]();
var year = [Link]();
[Link](“Today’s date: ”+date+”/”+month+”/”+year);
output:
Date today: 4/11/2010
Example: to set date to some past time like birth date
myBirthday = new Date(“September 11, 2001”)
result = [Link]() // result = 2, a Tuesday
[Link](2002) // bump up to next year
result = [Link]() // result = 3, a Wednesday

example:- square root


<html>
<head>
<title>JavaScript Math sqrt() Method</title>
</head>
<body>
<script type="text/javascript">

var value = [Link]( 0.5 );


[Link]("First Test Value : " + value );

var value = [Link]( 81 );


[Link]("<br />Second Test Value : " + value );

var value = [Link]( 13 );


[Link]("<br />Third Test Value : " + value );

var value = [Link]( -4 );


[Link]("<br />Fourth Test Value : " + value );
</script>
</body>
</html>

iii. String Object


The syntax to define string object is:
var stringVar = new String(“characters”)

Method Description
charAt(index) Returns the character at the specified index.

charCodeAt(index) Returns a number indicating the Unicode value of the character at


the given index.

Page 28 of 53
Internet Programming Lecture Note
concat(string) Combines the text of two strings and returns a new string.
indexOf(string, [start]) Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.
lastIndexOf(string,[start]) Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.
localeCompare(string2) Returns a number indicating whether a reference string comes
before or after or is the same as the given string in sort order.
length() Returns the length of the string.

match(regExpression) Used to match a regular expression against a string.

replace(regExpression,replacer) Used to find a match between a regular expression and a string,


and to replace the matched substring with a new substring.
search(regExpression) Executes the search for a match between a regular expression and
a specified string.
slice(startIndex [,end]) Extracts a section of a string and returns a new string.

split(delimiter [,limit]) Splits a String object into an array of strings by separating the
string into substrings.
substr(start [, length]) Returns the characters in a string beginning at the specified
location through the specified number of characters.
substring(start, end) Returns the characters in a string between the two indexes into a
string.
toLocaleLowerCase() The characters within a string are converted to lower case while
respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while
respecting the current locale.
toLowerCase() Returns the calling string value converted to lower case.

toString() Returns a string representing the specified object.

toUpperCase() Returns the calling string value converted to uppercase.

Table string object methods


Example:
var name = new String(“Konrad Zuse”);
[Link](“ - created the first computer”);
[Link](0,10);
[Link](“Zuse”);
[Link](“a”,”#”);
[Link]();
Output:
Konrad Zuse - created the first computer
Konrad Zuse
7
Konr#d Zuse

Page 29 of 53
Internet Programming Lecture Note
KONRAD ZUSE
iv. Document Object
Document object contains properties and methods that can be used to access the page elements
of the current document.
Properties:
 title - Current document title. If no title is defined, title contains “Untitled.”
 location - Full URL of the document.
 lastModified - A Date object-compatible string containing the date the document was
last modified.
 bgColor - Background color, expressed as a hexadecimal RGB value compatible with
HTML syntax (for example, #FFFFF" for white). Equivalent to the BGCOLOR attribute
of the <BODY> tag.
 fgColor - Foreground (text) color, expressed as a hexadecimal RGB value compatible
with HTM syntax. Equivalent to the TEXT attribute of the <BODY> tag.
 linkColor - Hyperlink color, expressed as a hexadecimal RGB value compatible with
HTML syntax. Equivalent to the vlinkColor Visited hyperlink color, expressed as a
hexadecimal RGB value compatible with HTML syntax. Equivalent to the VLINK
attribute of the <BODY> tag.
 alinkColor - Activated (after button press, before button release) hyperlink color,
expressed as a hexadecimal RGB value compatible with HTML syntax. Equivalent to the
ALINK attribute of the <BODY> tag.
 forms[ ] - Array of form objects in the document, in the order specified in the source.
Each form has its own form object.
 [Link] - The number of form objects within the document.
 links[ ] - Array objects corresponding to all HREF links in the document, in the order
specified in the source.
 [Link] - The number of HREF links in the document.
 anchors[ ] - Array of all "named" anchors (between the <A NAME=""> and </A> tags)
within the document, in the order specified in the source.
 [Link] - The number of named anchors in the document.
 images[] - Image objects that correspond to each image on the page.
 applets[] - Java applet objects that correspond to each applet on the page.
 embeds[] - Plugins object that represent each plug-in on the page.

Methods:
write("string")-Writes string to the current window. string may include HTML tags.
writeln("string") - Performs the same as write(), but adds a carriage return. This affects
only preformatted text (inside a <PRE> or <XMP> tag).
clear( ) - Clears the window.
close( ) - Closes the window.
[Link]() – goes back to last visited page
[Link]() – goes forward just like clicking forward button on toolbar
[Link](location) – goes to the specified history location

Page 30 of 53
Internet Programming Lecture Note
Managing Events
Events are occurrences generated by the browser, such as loading a document, or by the user,
such as moving the mouse. They are the user and browser activities to which we may respond
dynamically with a scripting language like JavaScript.
There are several more events that we can capture with JavaScript. Here is a short list of events
that Web developers like to capture:

Event Event Description


Handler
Load onLoad Browser finishes loading a Web document
Unload onUnload Visitor requests a new document in the browser window
Mouseover onMouseOver Visitor moves the mouse over some object in the document
window
Mouseout onMouseOut Visitor moves the mouse off of some object in the document
window
MouseDown onMouseDown A mouse button was pressed
MouseMove onMouseMove The mouse moved
MouseUp onMouseUp The mouse button was released
Select onSelect Text has been selected.
Click onClick Visitor clicks the mouse button
Focus onFocus Visitor gives focus to or makes active a particular window
or form element by clicking on it with a mouse or other
pointing device or tabbing to it
Blur onBlur A form field lost the focus (user moved to another field)

Change onChange Visitor changes the data selected or contained in a form


element
Submit onSubmit Visitor submits a form
Reset onReset Visitor resets a form
Abort onAbort An image failed to load
Change onChange The contents of a field has changed

DblClick onDblClick User double-clicked on this item


Error onError An error occurred while loading an image
Keydown onKeyDown A key was pressed
KeyPress onKeyPress A key was pressed OR released
KeyUP onKeyUp A key was released

Table most commonly used events


The event that we used can be summarized as :-
> A mouse click

Page 31 of 53
Internet Programming Lecture Note
> A web page or an image loading
> Mousing over a hot spot on the web page
> Selecting an input box in an HTML form
> Submitting an HTML form
> A keystroke
Events are :-
 onabort - Loading of an image is interrupted
o onblur - An element loses focus
o onchange - The content of a field changes
o onclick - Mouse clicks an object
o ondblclick - Mouse double-clicks an object
o onerror - An error occurs when loading a document or an image
o onfocus - An element gets focus
o onkeydown - A keyboard key is pressed
o onkeypress - A keyboard key is pressed or held down
o onkeyup - A keyboard key is released
o onload - A page or an image is finished loading
o onmousedown - A mouse button is pressed
o onmousemove - The mouse is moved
o onmouseout - The mouse is moved off an element
o onmouseover - The mouse is moved over an element
o onmouseup - A mouse button is released
o onreset - The reset button is clicked
o onresize - A window or frame is resized
o onselect - Text is selected
o onsubmit - The submit button is clicked
o onunload - The user exits the page

Example 1 :- onblur and onSubmit


<html>
<head>
<script type="text/javascript">
function upperCase() {
var x=[Link]("fname").value
[Link]("fname").value=[Link]()
}
function validate() {
// return true or false based on validation logic
}
</script>
</head>
<body>
Enter your name:

Page 32 of 53
Internet Programming Lecture Note
<input type="text" id="fname" onblur="upperCase()"><br>
<form action="tryjs_submitpage.htm" onsubmit="return validate()">
Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />
Age (from 1 to 100): <input type="text" id="age" size="20"><br />
E-mail: <input type="text" id="email" size="20"><br />
<br />
<input type="submit" value="Submit">
</form>
</body>
</html>
Example 2: a program that adds or subtracts two numbers when respective button is clicked
<html>
<head>
<script language="JavaScript">
function adder(num1, num2)
{
var sum = 0;
sum = num1 + num2;
[Link]("The sum is " + sum);
}
function subtractor(num1, num2)
{
var difference = 0;
difference = num1 - num2;
[Link]("The difference is " + difference);
}
</script>
</head>
<body>
<form name="event_example">
<input type="button" value="add" name="add" onClick="adder(10,30)">
<input type="button" value="subtract" name="subtract" onClick="subtractor(20,50)">
</form>
</body>
</html>
5.11 Form Processing and Validation

Forms are widely used on the Internet. The form input is often sent back to the server or mailed
to a certain e-mail account. With the help of JavaScript the form input can easily be checked
before sending it over the Internet. It is sent only if the input is valid.

Form data that typically are checked by a JavaScript could be:


 has the user left required fields empty?
 has the user entered a valid e-mail address?
 has the user entered a valid date?
 has the user entered text in a numeric field?

Page 33 of 53
Internet Programming Lecture Note
In the name field, we will receive an error message when nothing is entered. Age is number and
we expect a positive number only. If user enters characters which are not number, or negative
value, it is not valid age. So the script should check this and determine its validity.

The email field is a little bit more sophisticated. It shouldn’t work if there is no @ symbol in the
email because valid email addresses contain that symbol. The criteria for accepting the input as a
valid e-mail address is the @. The person may enter wrong emails which could pass as valid but
this is the least check we could do.

Figure form validation

Example: a script that creates and validates the above form:


<html>
<head>
<script language="JavaScript">
function check(form)
{
if ([Link] == "")
alert("Please enter a string as your name!")
else
alert("Hi " + [Link] + "! Name ok!");
if([Link] < 0 || [Link]=="")
alert("Age should be number and greater than 0");
else
alert("Age ok");
if ([Link] == "" || [Link]('@', 0) == -1)
alert("No valid e-mail address!");
else
alert("Email oK!");
if([Link]=="")

Page 34 of 53
Internet Programming Lecture Note
alert("No message written");
else
alert("Message ok");
}
</script>
</head>
<body>
<h2> <u> Form validation </u> </h2>
<form name="first">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
Enter your e-mail address: <input type="text" name="email"> <br>
write message: <textarea name="urmessage" cols=40 rows=10></textarea><br><br>
<input type="button" name="validate" value="Check Input"
onClick="check([Link])">
</body>
</html>

E-mail Validation The function below checks if the content has the general syntax of an email.
This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not
be the first character of the email address, and the last dot must at least be one character after the
@ sign:
function validate_email(field,alerttxt)
{
with (field)
{ apos=[Link]("@");
dotpos=[Link](".");
if (apos<1||dotpos-apos<2)
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
The entire script, with the HTML form could look something like this:
<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=[Link]("@");
dotpos=[Link](".");
if (apos<1||dotpos-apos<2)

Page 35 of 53
Internet Programming Lecture Note
{alert(alerttxt);return false;}
else
{ return true;
}}}
function validate_form(thisform)
{
with (thisform)
{
If
(validate_email(email,"Not a valid e-mail address!")==false)
{[Link]();return false;}
}}
</script>
</head>
<body>
<form action="[Link]"
onsubmit="return validate_form(this);"
method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>
</html>

Example:- The following code used to develop form webpage for different operations
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!--
function plus(){
var n1;
var n2;
n1=[Link];
n2=[Link];

n1=parseFloat(n1);
n2=parseFloat(n2);

[Link]=n1+n2;
}
function times(){
var n1;
var n2;
n1=[Link];
n2=[Link];

n1=parseFloat(n1);
n2=parseFloat(n2);

[Link]=n1*n2;
}
//--></SCRIPT>

Page 36 of 53
Internet Programming Lecture Note
</HEAD>
<BODY BGCOLOR="#FFFFCC">
<P><FORM name=addmult>
<P>Enter a number in each field:
<INPUT TYPE=text NAME=num1 VALUE="" SIZE=5>
<INPUT TYPE=text NAME=num2 VALUE="" SIZE=5><BR>
<INPUT TYPE=button VALUE="+" onclick="plus()">
<INPUT TYPE=button VALUE="*" onclick="times()"><BR>
<INPUT TYPE=reset VALUE="Reset Form"><BR>
<TEXTAREA NAME=result ROWS=3 COLS=27
WRAP=virtual></TEXTAREA>
</FORM>
</BODY>
</HTML>

5.12 The try...catch...finally Statement:

The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions. We can
catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax
errors. Here is the try...catch...finally block syntax:

<script type="text/javascript">
<!--
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and the catch
block is executed. The optional finally block executes unconditionally after try/catch.

Examples:Here is one example where we are trying to call a non existing function this is
causing an exception raise

and display a user friendly message. You can also


Now let us try to catch this exception using try...catch
suppress this message, if you want to hide this error from a user.

Page 37 of 53
Internet Programming Lecture Note
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;

try {
alert("Value of variable a is : " + a );
} catch ( e ) {
alert("Error: " + [Link] );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

You can use finally block which will always execute unconditionally after try/catch. Here is an
example:

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;

try {
alert("Value of variable a is : " + a );
}catch ( e ) {
alert("Error: " + [Link] );
}finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

Page 38 of 53
Internet Programming Lecture Note
The throw Statement:
You can use throw statement to raise to built-in exceptions or we customized exceptions. Later these exceptions can be captured and we
can take an appropriate action. Following is the example showing usage of throw statement.

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
var b = 0;

try{
if ( b == 0 ){
throw( "Divide by zero error." );
}else{
var c = a / b;
}
}catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

You can raise an exception in one function using a string, integer, Boolean or an object and then you can capture that exception either in
the same function as we did above, or in other function using try...catch block.

Example 2 :- The example below determines the value of a variable called x. If the value of x is
higher than 10 or lower than 0 we are going to throw an error. The error is then caught by the
catch argument and the proper error message is displayed:
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{ if(x>10)
throw "Err1";
else if(x<0)
throw "Err2"; }
catch(er)
if
(er=="Err1")
alert("Error! The value is too high");
if(er == "Err2") alert("Error! The value is too low"); }

Page 39 of 53
Internet Programming Lecture Note
</script>
</body>
</html>

The onerror() Method

The onerror event handler was the first feature to facilitate error handling for JavaScript. The
error event is fired on the window object whenever an exception occurs on the page. Example:

<html>
<head>
<script type="text/javascript">
<!--
[Link] = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

The onerror event handler provides three pieces of information to identify the exact nature of
the error:

 Error message . The same message that the browser would display for the given error
 URL . The file in which the error occurred

 Line number . The line number in the given URL that caused the error

Here is the example to show how to extract this information

<html>
<head>
<script type="text/javascript">
<!--
[Link] = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>
</head>

Page 40 of 53
Internet Programming Lecture Note
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

You can use onerror method to show an error message in case there is any problem in loading
an image as follows:

<img src="[Link]"
onerror="alert('An error occurred loading the image.')" />

You can use onerror with many HTML tags to display appropriate messages in case of errors.

Java Validate:-
Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button. If some of
the data that had been entered by the client had been in the wrong form or was simply missing, the server would have to send all the data
back to the client and request that the form be resubmitted with correct information. This was really a lengthy process and over
burdening server.

JavaScript, provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally
performs two functions.

 Basic Validation - First of all, the form must be checked to make sure data was entered into each form field that required it.
This would need just loop through each field in the form and check for data.
 Data Format Validation - Secondly, the data that is entered must be checked for correct form and value. This would need to
put more logic to test correctness of data.

We will take an example to understand the process of validation. Here is the simple form to proceed:

<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/[Link]" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>

Page 41 of 53
Internet Programming Lecture Note
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>

</html>

Basic Form Validation:


First we will show how to do a basic form validation. In the above form we are calling validate() function to validate data when
onsubmit event is occurring. Following is the implementation of this validate() function:

<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{

if( [Link] == "" )


{
alert( "Please provide your name!" );
[Link]() ;
return false;
}
if( [Link] == "" )
{
alert( "Please provide your Email!" );
[Link]() ;
return false;
}
if( [Link] == "" ||
isNaN( [Link] ) ||
[Link] != 5 )
{
alert( "Please provide a zip in the format #####." );
[Link]() ;
return false;
}
if( [Link] == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );

Page 42 of 53
Internet Programming Lecture Note
}
//-->
</script>

Data Format Validation:


Now we will see how we can validate our entered form data before submitting it to the web server.

This example shows how to validate an entered email address which means email address must
contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email
address, and the last dot must at least be one character after the @ sign:

<script type="text/javascript">
<!--
function validateEmail()
{

var emailID = [Link];


atpos = [Link]("@");
dotpos = [Link](".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
[Link]() ;
return false;
}
return( true );
}
//-->
</script>

5.13 JavaScript Animation

It is possible to use JavaScript to create animated images. The trick is to let a JavaScript change
between different images on different events. In the following example we will add an image that
should act as a link button on a web page. We will then add an onMouseOver event and an
onMouseOut event that will run two JavaScript functions that will change between the images.

Examples:- Button animation


<html> <head>
<script type="text/javascript">
function mouseOver() { [Link] ="b_blue.gif"; }
function mouseOut() { [Link] ="b_pink.gif"; } </script> </head>
<body>
<a href="[Link] target="_blank">
<img border="0" src="b_pink.gif" name="b1" width="26" height="26"
onmouseover="mouseOver()" onmouseout="mouseOut()" />
</a> </body> </html>

Page 43 of 53
Internet Programming Lecture Note
The HTML Code
The HTML code looks like this:
<a href="[Link] target="_blank">
<img border="0" src="b_pink.gif" name="b1"
onmouseOver="mouseOver()"
onmouseOut="mouseOut()" />
</a>
Note that we have given the image a name to make it possible for JavaScript to address it later.
The onMouseOver event tells the browser that once a mouse is rolled over the image, the
browser should execute a function that will replace the image with another image.

The onMouseOut event tells the browser that once a mouse is rolled away from the image,
another JavaScript function should be executed. This function will insert the original image
again.
The JavaScript Code
The changing between the images is done with the following JavaScript:
<script type="text/javascript">
function mouseOver()
{
[Link] ="b_blue.gif";
}
function mouseOut()
{
[Link] ="b_pink.gif";
}
</script>
The function mouseOver() causes the image to shift to "b_blue.gif". The function mouseOut()
causes the image to shift to "b_pink.gif".
Example:-
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript><!--
function verify(){
with([Link]){
if(([Link]=="")||([Link]=="")||([Link]=="")){
alert("You have left one or more fields blank. Please supply the necessary
information, and re-submit the form.");
}
else {
[Link]="The following information has been added to our
guestbook:\r"+[Link]+"\r"+ [Link] +"\r" +[Link];
}
}
}
//--></SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFCC">
<P><FORM name=”infoform”>

Page 44 of 53
Internet Programming Lecture Note
<P><TABLE BORDER=0>
<TR>
<TD WIDTH=83>
<P>Name:
</TD>
<TD>
<P><INPUT TYPE=text NAME=fullname VALUE="" SIZE=32>
</TD>
</TR>
<TR>
<TD WIDTH=83>
<P>Address:
</TD>
<TD>
<P><INPUT TYPE=text NAME=address VALUE="" SIZE=32>
</TD>
</TR>
<TR>
<TD WIDTH=83>
<P>E-mail:
</TD>
<TD>
<P><INPUT TYPE=text NAME=email VALUE="" SIZE=32>
</TD>
</TR>
<TR>
<TD WIDTH=83>
<P><INPUT TYPE=button VALUE="Submit" onclick="verify()">
</TD>
<TD>
<P><INPUT TYPE=reset VALUE="Clear Your Information">
</TD>
</TR>
<TR>
<TD COLSPAN=2>
<P><TEXTAREA NAME=display ROWS=5 COLS=41
WRAP=virtual></TEXTAREA>
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>

We can use JavaScript to create a complex animation which includes but not limited to:

Page 45 of 53
Internet Programming Lecture Note
 Fireworks
 Fade Effect

 Roll-in or Roll-out
 Page-in or Page-out
 Object movements

We might be interested in existing JavaScript based animation library. JavaScript can be used to move a
number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined
by a logical equation or function. JavaScript provides following two functions to be frequently used in animation programs.

 setTimeout( function, duration) - This function calls function after duration milliseconds from now.
 setInterval(function, duration) - This function calls function after every duration milliseconds.

 clearTimeout(setTimeout_variable) - This function calls clears any timer set by the setTimeout() functions.

JavaScript can also set a number of attributes of a DOM object including its position on the
screen. You can set top and left attribute of an object to position it anywhere on the screen. Here
is the simple syntax:

// Set distance from left edge of the screen.


[Link] = distance in pixels or points;

or // Set distance from top edge of the screen.


[Link] = distance in pixels or points;

Manual Animation:
So let's implement one simple animation using DOM object properties and JavaScript functions
as follows:

<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
function init(){
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight(){
[Link] = parseInt([Link]) + 10 + 'px';
}
[Link] =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/[Link]" />
<p>Click button below to move the image to right</p>

Page 46 of 53
Internet Programming Lecture Note
<input type="button" value="Click Me" onclick="moveRight();" />
</form>
</body>
</html>

Here is the explanation of the above example:

 We are using JavaScript function getElementById() to get a DOM object and then
assigning it to a global variable imgObj.
 We have defined an initialization function init() to initialize imgObj where we have set its
position and left attributes.

 We are calling initialization function at the time of window load.

 Finally, we are calling moveRight() function to increase left distance by 10 pixels. You
could also set it to a negative value to move it to the left side

Automated Animation:
In the above example we have seen , how an image moves to right with every click. We can automate this process by using JavaScript
function setTimeout() as follows:

<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight(){
[Link] = parseInt([Link]) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
[Link] = '0px';
}
[Link] =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/[Link]" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>

Page 47 of 53
Internet Programming Lecture Note
</body>
</html>

Here we have add more spice. So let's see what is new here:

 The moveRight() function is calling setTimeout() function to set the position of imgObj.
 We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.

Rollover with a Mouse Event:

Here is a simple example showing image rollover with a mouse events:

<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type="text/javascript">
<!--
if([Link]){
var image1 = new Image(); // Preload an image
[Link] = "/images/[Link]";
var image2 = new Image(); // Preload second image
[Link] = "/images/[Link]";
}
//-->
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href="#" onMouseOver="[Link]=[Link];"
onMouseOut="[Link]=[Link];">
<img name="myImage" src="/images/[Link]" />
</a>
</body>
</html>

Let's see what is different here:

 At the time of loading this page, the if statement checks for the existence of the image object. If the image object is
unavailable, this block will not be executed.
 The Image() constructor creates and preloads a new image object called image1.

 The src property is assigned the name of the external image file called /images/[Link].

 Similar way we have created image2 object and assigned /images/[Link] in this object.

 The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.

 The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is
triggered when the user's mouse moves away from the link (image).

 When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is
moved away from the image, the original image is displayed.

 When the mouse is moved away from the link, the initial image [Link] will reappear on the screen.

Page 48 of 53
Internet Programming Lecture Note
What are Cookies ?
Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is
required to maintain session information among different pages. For example one user registration ends after completing many pages.
But how to maintain user's session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and
other information required for better visitor experience or site statistics.

How It Works ?
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as
a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same
cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

Cookies are a plain text data record of 5 variable-length fields:

 Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
 Domain : The domain name of your site.

 Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any
directory or page.

 Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is
blank, no such restriction exists.

 Name=Value : Cookies are set and retrieved in the form of key and value pairs.

Cookies were originally designed for CGI programming and cookies' data is automatically transmitted between the web browser and web
server, so CGI scripts on the server can read and write cookie values that are stored on the client.

JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete
the cookie or cookies that apply to the current web page.

Storing Cookies:
The simplest way to create a cookie is to assign a string value to the [Link] object, which looks like this:

Syntax:
[Link] = "key1=value1;key2=value2;expires=date";

Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and
after that cookies' value will not be accessible.

Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape()
function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape()
function when you read the cookie value.

Example:

Following is the example to set a customer name in input cookie.

<html>

Page 49 of 53
Internet Programming Lecture Note
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( [Link] == "" ){
alert("Enter some value!");
return;
}

cookievalue= escape([Link]) + ";";


[Link]="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>

This will produce following result. Now enter something in the text box and press the button "Set
Cookie" to set the cookies.

Enter name:

Now your machine has a cookie called name. You can set multiple cookies using multiple key=value pairs separated by comma.

You will learn how to read this cookie in next section.

Reading Cookies:
Reading a cookie is just as simple as writing one, because the value of the [Link] object is the cookie. So you can use this
string whenever you want to access the cookie.

The [Link] string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value
is its string value.

You can use strings' split() function to break the string into key and values as follows:

Example:

Following is the example to get the cookies set in previous section.

<html>
<head>
<script type="text/javascript">
<!--

Page 50 of 53
Internet Programming Lecture Note
function ReadCookie()
{
var allcookies = [Link];
alert("All Cookies : " + allcookies );

// Get all the cookies pairs in an array


cookiearray = [Link](';');

// Now take key value pair out of this array


for(var i=0; i<[Link]; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>

Note: Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that
time please try to digest it.

This will produce following result. Now press the button "Get Cookie" to see the cookies which
you have set in previous section.

Note: There may be some other cookies already set on your machine. So above code will show you all the cookies set at your machine.

Setting the Cookies Expiration Date:


You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiration date within
the cookie. This can be done by setting the expires attribute to a date and time.

Example:

The following example illustrates how to set cookie expiration date after 1 Month :

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
[Link]( [Link]() + 1 );
cookievalue = escape([Link]) + ";"
[Link]="name=" + cookievalue;
[Link] = "expires=" + [Link]() + ";"

Page 51 of 53
Internet Programming Lecture Note
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

Deleting a Cookie:
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set
the expiration date to a time in the past.

Example:

The following example illustrates how to delete cookie by setting expiration date one Month in
past :

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
[Link]( [Link]() - 1 );
cookievalue = escape([Link]) + ";"
[Link]="name=" + cookievalue;
[Link] = "expires=" + [Link]() + ";"
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

Note that:-

 The script tag takes two important attributes:

Page 52 of 53
Internet Programming Lecture Note
 language: This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although
recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.

 type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to
"text/javascript".

 JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

 Semicolons are Optional


 JavaScript is a case-sensitive language

Page 53 of 53

You might also like