File

advertisement
Chapter 4: JavaScript
4.1
Introduction of JavaScript
JavaScript is an interpreted programming language that can be embedded into an HTML web
page. Interpreted means that the entire web page is downloaded to the browser and the JavaScript
code is executed when an event is triggered. When the code is executed it is interpreted one line
at time. There are a number of events that will trigger the execution of a JavaScript, like a click
on a form button, or the completion of a web page loading. It is platform specific.
JavaScript is a scripting language used in many websites. A scripting language is a language,
which is easy and fast to learn. A scripting language is interpreted in run-time. It is not compiled
like other languages as C++, C#, VB.NET etc. JavaScript is a client side language and it runs on
the client browser. JavaScript can be used on all most known browsers. However JavaScript can
be also used on the server-side. On the server side you can use JavaScript for example to manage
your database entry. It can be easily used to interact with HTML elements. In other words,
JavaScript is a language that lets you make your pages interact with your readers and respond to
what they do. It is a programming language that can make your pages feel more dynamic and
give feedback to your user. You can validate text fields, disable buttons, validate forms, or
change the background color of your page. All this is possible with JavaScript. Like each
programming language, it contains variables, arrays, functions, operators, objects and much more
which can be help you to create better scripts for your pages. JavaScript is an object-oriented
scripting language that lets you build interactions between page content, the state of the browser,
and the actions of the reader. JavaScript code can be inserted directly in the HTML or you can
place it in a separate file with the .js extension and link the web page with the .js file.
The JavaScript language was developed by the Netscape Communications Corporation and is a
trademarked name. It is a cross-platform, object-based scripting language that was originally
designed for use in Netscape Navigator. Indeed, versions 2.0, and later, of Navigator can
interpret JavaScript statements that are embedded within HTML code. When a request is made to
see a page, the HTML code that defines the requested page along with the embedded JavaScript
statements, are sent by the server to the client. Navigator interprets the HTML document and
executes the JavaScript code. The resultant page is displayed for the client. It is important to
understand that this interpretation occurs on the client-side rather than the server-side.
After the success of JavaScript in Navigator 2.0, the Microsoft Corporation was quick to create a
clone of JavaScript, called JScript, which is a trademarked name that is designed to run inside the
Microsoft Internet Explorer. In truth, except for a few minor differences, JScript is essentially a
carbon copy of JavaScript.
JavaScript is a simple to comprehend, easy to use, general purpose scripting language. When
used in conjunction with a Web browser's Document Object Model (DOM), it can produce
powerful dynamic HTML browser-based applications which also can feature animation and
sound.
JavaScript code is placed within the <SCRIPT> and </SCRIPT> tags. Script tags can be put into
inside the Header or inside the Body tags. This tells the browser that the flowing bunch of code
bounded within <SCRIPT> and </SCRIPT> tags is not HTML to be displayed but rather the
code to be processed. One important attribute that is used with <SCRIPT> tag is type and
language. This tells the browser which scripting language is used.
Basic format:
<HTML>
<HEAD>
<SCRIPT language=”JavaScript” type=”text/javascript”>
----------------</SCRIPT>
</HEAD>
<BODY>
<SCRIPT language=”JavaScript” type=”text/javascript”>
------------------</SCRIPT>
</BODY>
</HTML>
Example:
<HTML>
<HEAD>
<SCRIPT language=”JavaScript”>
document.write(“Hello to JavaScript”);
</SCRIPT>
</HEAD>
</HTML>
The result of code is shown in figure 4.1
Figure 4.1 first JavaScript program
The above example displays the text “Hello to JavaScript” in the browser.
Interpretation of JavaScript Code or Execution of JavaScript code can be done both Client as
well as Server Side, By default it will execute JavaScript code at Client side that why it called
Client side Scripting and interpretation done at server is called Server Side Scripting language.
So we can run on Server as well as Client Side both.
4.1.1 Client-Side JavaScript
When the browser (or client) requests a page, the server sends the full content of the document,
including HTML and JavaScript statements, over the network. The client reads the page from top
to bottom, displaying the results of the HTML and executing JavaScript statements as it goes.
Client-side JavaScript statements embedded in an HTML page can respond to user events such
as mouse clicks. For example, you can write a JavaScript function to verify that users enter valid
information into a form requesting a telephone number or zip code. Without any network
transmission, the embedded JavaScript on the HTML page can check the entered data and
display a dialog box to the user who enters invalid data.
Client side JavaScript accommodates the wide range of document object models that are spread
among numerous browser brands, operating systems, and versions. Document Object Model
(DOM) discuss later
4.1.2 Server-Side JavaScript
JavaScript is also embedded in HTML pages on server-side. The server-side statements can
connect to relational databases, share information across users of an application, access the file
system on the server, or communicate with other applications. JavaScript applications that use
server-side JavaScript are compiled into bytecode executable files. These application executables
are run in concert with a web server that contains the JavaScript runtime engine. When a page in
the application is requested by a client browser, the runtime engine uses the application
executable to look up the source page and dynamically generate the HTML page to return. It
runs any server-side JavaScript statements found on the page. The result of those statements
might add new HTML or client-side JavaScript statements to the HTML page. It then sends the
resulting page over the network to the client, which displays the results
4.1.3 Document Object Model
To help scripts control various objects/elements, the browser makers define a Document Object
Model (DOM). A model is like a prototype or plan for the organization of objects on a page.
Below fig. shows a map of the lowest common denominator object model, which is safe to use
on all browsers.
Figure 4.2 relationships of all objects
The relationship of all objects with each other is explained below:
Window object: At the top of the hierarchy is the window. This object represents the content
area of the browser window where HTML documents appear. In a multiple-frame environment,
each frame is also a window (but don’t concern yourself with this just yet). Because all
document action takes place inside the window, it is the outermost element of the object
hierarchy. Its physical borders contain the document.
Document object: Each HTML document that gets loaded into a window becomes a document
object. Its position in the object hierarchy is an important one, as you can see in Figure 4-6. The
document object contains most of the other kinds of objects in the model. This makes perfect
sense when you think about it: The document contains the content that you are likely to script.
The biggest improvement is that every HTML element becomes an object that scripts can
manipulate.
Form object: Users don’t see the beginning and ending of forms on a page, only their elements.
But a form is a distinct grouping of content inside an HTML document. Everything that is inside
the <FORM>...</FORM> tag set is part of the form object. A document might have more than
one pair of <FORM> tags if dictated by the page design.
Form control elements: Just as your HTML defines form elements within the confines of the
<FORM>...</FORM> tag pair, so does a form object contain all the elements defined for that
object. Each one of those form elements—text fields, buttons, radio buttons, checkboxes, and the
like—is a separate object.
4.1.4 Comments
Text which is commented is ignored by the interpreter from that point to the end of the line.
There are two types of comments: those that run to the end of the current line and those that span
multiple lines. Single-line comments begin with a double forward slash (//). For example:
var count = 10; // holds number of items the user wishes to purchase
Comments spanning multiple lines are enclosed between a slash-asterisk (/*) and asterisk-slash
(*/) pair. For example:
/*var count = 10;
var y = square(10);*/
4.1.5 Conventions

JavaScript is case-sensitive.

At the end of every JavaScript statement, semicolon is required which indicates the end of
statement. For eg:
var x = 0;

The double quotation mark can be found within strings that start, and end with (are delimited
by) single quotes (‘He said, “JavaScript is an interesting language.” ‘)

The single quotation mark can be used within a string delimited by double quotation marks.

JavaScript ignores spaces, tabs, and newlines that appear in statements. However it
recognizes spaces, tabs, and tabs that are part of string. For eg:
var x=0; is same as var x = 0;

The backslash (\) is followed by another character that represents something in a string
that cannot be typed on keyboard. The \ tells the interpreter that in this case it should print the
character and not interpret as a delimiter. For eg:
‘You\nPressed\nEnter key’
‘\n’ represents carriage return and a line feed. The result of above eg. is :
You
Pressed
Enter key
These backslashes and letter combination is known as Escape Sequences. Some common of
them are listed below:
\b
backspace
\f
form feed
\n
new line
\t
\’
\”
tab
single quote
double quotes
4.1.6 Data Types
Various data types in JavaScript are as follows:
1. Numerical Data: This consists of numbers both integer and floating. For example 17, 21.5 etc
2. Text: Also called String. This consists of text specified within single or double quotes. For
example “Hello”, ‘World’ etc
3. Boolean: This consists of Boolean value i.e. true or false.
4.1.7 Declaring and Initializing Variables
A variable can be declared by using var keyword. For example
var sum;
A variable can be assigned value as:
var name = “Hello”;
Every JavaScript variable has a data type, but the type is inferred from the variable’s content. For
example, a variable that is assigned a string value assumes the string data type. A consequence of
JavaScript’s automatic type inference is that a variable’s type can change during script execution.
For example, a variable can hold a string at one point and then later be assigned a Boolean. Its
type changes according to the data it holds. There is no need to indicate type in variable
declarations.
To check the type of variable, typeof operator is used. For eg:
var x = “5”;
alert (typeof x);
The output is string. alert () function is used to display text in message box. It will be explained
later.
4.1.8 Data Type Conversion
JavaScript tries its best to perform internal conversions to solve data type conversion, but
JavaScript cannot read your mind. If your intentions differ from the way JavaScript treats the
values, you won’t get the results you expect.
A case in point is adding numbers that may be in the form of text strings. In a simple arithmetic
statement that adds two numbers together, you get the expected result:
3 + 3 // result = 6
But if one of those numbers is a string, JavaScript leans toward converting the other value to a
string—thus turning the plus sign’s action from arithmetic addition to joining strings. Therefore,
in the statement
3 + “3” // result = “33”
the “string-ness” of the second value prevails over the entire operation. The first value is
automatically converted to a string, and the result joins the two strings. Look what happens
when another number is added to the statement:
3 + 3 + “3” // result = “63”
This might seem totally illogical, but there is logic behind this result. The expression is evaluated
from left to right. The first plus operation works on two numbers, yielding a value of 6. But as
the 6 is about to be added to the “3,” JavaScript lets the “string-ness” of the “3” rule. The 6 is
converted to a string, and two string values are joined to yield “63.”
4.2
Operators
Lots of operators are used in various expressions. Various categories are described below:
4.2.1 Assignment Operator:
The most basic operator is the assignment operator (=), which is used to assign a value to a
variable. Often this operator is used to set a variable to a value. For eg:
var str = “Hello”;
Generally, the assignment operator is used to assign a value to a single variable, but it is possible
to perform multiple assignments at once by stringing them together with the = operator. For eg:
var x = y = z = 7;
Assignments can also be used to set a variable to hold the value of an expression. For eg:
var x = 12 + 5;
Below Table illustrates different Assignment Operators
Operator
+=
-=
*=
/=
%=
Example
a+=b
a-=b
a*=b
a/=b
a%=b
Meaning
a=a+b
a=a-b
a=a*b
a=a/b
a = a %b
Arithmetic Operators: JavaScript supports all the basic arithmetic operators like addition (+),
subtraction (–), multiplication (*), division (/), and modulus (%, also known as the remainder
operator). For eg:
var a = 3 – 2;
var x = 10 + 5;
var b = 3 * 2;
//result is 1
//result is 15
// result is 6
var c = 5 / 2;
var d = 5 % 2;
//result is 2.5
//result is 1
4.2.2 Comparison Operators:
These operators compare values in scripts—whether two values are the same. These kinds of
comparisons return a value of the Boolean type—true or false. The operator that tests whether
two items are equal consists of a pair of equal signs to distinguish it from the single equal sign
assignment operator. Other comparison operators are listed below:
==
!
!=
>
>=
<
<=
Equals
Not
Does not equal
Is greater than
Is greater than or equal to
Is less than
Is less than or equal to
For eg:
4<8
4.2.3 Logical Operators:
Logical Operators typically operate on Boolean values, which are either true or false. The
following logical operators are available:
&&
||
!
Logical AND
Logical OR
Logical NOT
a
True
True
False
False
b
True
False
True
False
a && b
True
False
False
False
a || b
True
True
True
False
a!b
False
False
True
True
4.2.4 Bitwise Operators:
Computers work with bits and bytes. These operators work with bits i.e. zeros and ones. These
operators are rarely used. These operators are listed below:
Operator Meaning
&
bitwise AND
Usage
a&b
|
bitwise OR
a|b
^
bitwise XOR
a^b
Description
Returns 1 in each bit position if corresponding bits of an b are
1; returns 0 otherwise
Returns 0 in each bit position if corresponding bits of an b
are 0; returns 1 otherwise
Returns 0 in each bit position if corresponding bits of an b
are identical; returns 1 otherwise
Inverts the bits of its operand
~
bitwise NOT
~a
<<
bitwise Shift
Left
Unsigned
Shift Right
Zero-fill right
sift
a << b
Left-shifts a, b times (<32) filling zeros from the right
a >> b
Right-shifts a, b times (<32) discarding bits shifted off
a>>>b
Right-shifts a, b times (<32) discarding bits shifted off, and
shifting in zeros from the left
>>
>>>
4.2.5 Ternary Operator:
The ?: operator is used to create a quick conditional branch. The basic syntax for this operator is
(expression) ? if-true-statement : if-false-statement;
where expression is any expression that will evaluate eventually to true or false. If expression
evaluates true, if-true-statement is evaluated. Otherwise, if-false-statement is executed. In this
example,
(x >> 5) ? alert("x is greater than 5") : alert("x is less than 5");
4.2.6 typeof Operator:
typeof operator defines the kind of value to which a variable or expression evaluates. Typically,
this operator is used to identify whether a variable value is one of the following types: number,
string, boolean, object, function, or undefined.
Example
<html>
<head><title>typeof Operator</title>
<script>
var a=10;
document.write(typeof(a));
</script>
</head>
</html>
The result of code is shown in figure 4.3
Figure 4.3 typeof operator
4.2.7 Increment & Decrement Operator:
The ++ operator is used to increment—or, simply put, to add 1—to its operand. For example,
with
var x=3;
x++;
the value of x is set to 4.
Similar to the ++ operator is the -- operator, used to decrement (subtract one from) its operand.
So,
var x=3;
x--;
leaves a value of 2 in the variable x. Of course, this statement could also have been written the
“long” way:
x=x-1;
4.3 String Concatenation Using +:
The addition operator (+) has a different behavior when operating on strings as opposed to
numbers. In this other role, the + operator performs string concatenation. For eg:
document.write("JavaScript is " + "great.");
outputs the string "JavaScript is great" to the document.
You can join any number of strings or literals together using this operator.
4.4
Control Structures
The kinds of statements that make decisions and loop around to repeat themselves are called
control structures. A control structure directs the execution flow through a sequence of script
statements based on simple decisions and other factors. An important part of a control structure
is the condition. A program sometimes have to branch to an execution route if a certain condition
exists. Each condition is an expression that evaluates to true or false. JavaScript provides several
kinds of control structures for different programming situations. Three of the most common
control structures you’ll use are if constructions, if...else constructions, and for loops.
4.4.1 If Structure
if statement is JavaScript’s basic decision-making control statement. It allows your program to
perform a test and act based on the results of the test. The syntax is:
if (condition)
{
statement[s] if true
}
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
var x = 5;
if (x > 1)
{
document.write("x is greater than 1");
}
document.write("moving on ...");
</script>
</body>
</html>
The result of code is shown in figure 4.4
Figure 4.4 example of if statement
The expression evaluates to true, displays the message “x is greater than 1,” and then displays the
second moving on afterward. However, if the value of variable x were something like zero, the
expression would evaluate false, resulting in skipping the first alert and immediately displaying
the second one.
if . . . else structure
In the plain if construction, no special processing is performed when the condition evaluates to
false. But if processing must follow one of two special paths, you need the if...else structure. The
syntax is as follows:
if (condition)
{
statement[s] if true
}
else
{
statement [s] if false
}
Example
<html>
<body>
<script type="text/JavaScript">
x=10;
y=5;
sum=2;
if (sum ==0)
{
sum = x +y;
}
else
{
sum=x-y ;
}
document.write(sum)
</script>
</body>
</html>
The result of code is shown in figure 4.5
Figure 4.5 example of if..else statement
If sum equals to 0 then sum equals x plus y, or else sum equals x minus y. value of sum equals to
2 it will go in else part and x minus y output will we 5
if…else if structure
More advance than if..else is if…else if construct. You can evaluate your more than more one
conditions and can process it. The syntax is as follows:
if (expression1)
statement or block
else if (expression2)
statement or block
else if (expression3)
statement or block
...
else
statement or block
Example
<html>
<body>
<script type="text/JavaScript">
x=1;
If (x>5)
{
document.write (“x is greater than 5”);
}
else if (x<10)
{
document.write (“x is less than 10”);
}
else
{
document.write (“unknown”);
}
</script>
</body>
</html>
The above code checks for the value of x. if it is greater than 5, 1st block is executed. If it is less
than 10, 2nd block is executed. If both the conditions are false, last block is executed.
4.4.2 switch
The switch statement is used when a variable may take a number of values and you want to test
for some of those values. The basic syntax of the switch statement is to give an expression to
evaluate and several different statements to execute based on the value of the expression. The
interpreter checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used. The syntax is as follows:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statement indicates the end of that particular case. If they were omitted, the interpreter
would continue executing each statement:
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
var yourGrade='B';
switch (yourGrade)
{
case 'A': alert("Good job.");
break;
case 'B': alert("Pretty good.");
break;
case 'C': alert("You passed!");
break;
case 'D': alert("Not so good.");
break;
case 'F': alert("Back to the books.");
break;
default: alert("Grade Error!");
}
</script>
</body>
</html>
The result of code is shown in figure 4.6
Figure 4.6 example of switch case
4.4.3 continue
The continue statement tells the interpreter to immediately start the next iteration of the loop.
When it’s encountered, program flow will move to the loop check expression. The below
example shows how the continue statement is used to skip printing when the index held in
variable x reaches 8
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
var x = 0;
while (x < 10)
{
x = x + 1;
if (x == 8)
continue; // continues loop at 8 without printing
document.write(x+" ");
}
</script>
</body>
</html>
The result of code is shown in figure 4.7
Figure 4.7 example of continue
4.4.4 break
The break statement, is used to exit a loop early, breaking out of the enclosing curly braces. The
example below breaks out early once x reaches 8:
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
var x = 0;
while (x < 10)
{
x = x + 1;
if (x == 8)
break;
document.write(x+" ");
}
</script>
</body>
</html>
The result of code is shown in figure 4.8
Figure 4.8 example of break
4.5 Looping Structure
A loop is a structure that forces the statements contained within its delimiters to execute over and
again until a condition is met and at that point loop ends.
4.5.1 While loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false or a break statement is encountered, the loop
will be exited. While loops are useful when you don’t know how many times you have to loop,
but you know you should stop when you meet the condition. The syntax is as follows:
while (expression)
{
statement or block of statements to execute
}
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
var count = 0;
while (count < 10)
{
document.write(count+" ");
count++;
}
document.write("Loop done!");
</script>
</body>
</html>
The result of code is shown in figure 4.9
Figure 4.9 example of while loop
4.5.2 For loop
For loops are useful when you know exactly how many times you want the loop to execute. The
initialization statement is executed before the loop begins, the loop continues executing until test
condition becomes false, and at each iteration the iteration statement is executed. The syntax is
as follows:
for (initialization; test condition; iteration statement)
{
loop statement or block
}
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
for (var i = 0; i < 10; i++)
document.write ("Loop " + i + " ");
</script>
</body>
</html>
The result of code is shown in figure 4.10
Figure 4.10 example of for loop
4.6 Dialog Boxes
JavaScript has three kind of dialog boxes: Alert box, Confirm box, and Prompt box.
4.6.1 Alert Box
An alert box is often used if you 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.
Syntax
alert("sometext");
Example
<html>
<head>
</head>
<body>
<script>
alert(“Hello this is alert box”);
</script>
</body>
</html>
The result of code is shown in figure 4.11
Figure 4.11 example of alert dialog box
4.6.2 Confirm Box
A confirm box is often used if you 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.
Syntax
confirm("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm box" />
</body>
</html>
The result of code is shown in figure 4.12
Figure 4.12 example of confirm dialog box
In above example if user clicks on confirm button message box will appear with OK and Cancel
button, if user pressed OK “You Pressed OK” message will appear. , if user pressed Cancel “You
Pressed Cancel” message will appear
4.6.3 Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns
null.
Syntax
prompt("sometext","defaultvalue");
Example
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","XYZ");
if (name!=null && name!="")
//check the condition for name is not null
{
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>
The result of code is shown in figure 4.13
Figure 4.13 example of prompt dialog box
In above example when user click on Show Prompt box, Input box will appear with default
name as XYZ when user click on OK it will display Hello XYZ how r u today. If user click on
cancel button , Show Ptrompt box botton will display as it is.
4.7
Arrays
In JavaScript arrays are considered as an Object. An array is stored in a variable, so when you
create an array you assign the new array object to the variable. A special keyword new preceding
a call to the JavaScript function that generates arrays creates space in memory for the array. An
optional parameter to the Array() function enables you to specify at the time of creation how
many elements (rows) of data eventually will occupy the array. You can change the size of an
array at any time. Therefore, you can omit a parameter when generating a new array. For
example
var arr1 = new Array();
var arr2 = new Array(10);
var arr3=[1,3,5,7,9];
Statement 1 in the above example will declare arr1 as an array with no data limits. While in
statement 2 arr2 is declared as array with 10 data elements and arr3 using square brackets with
array elements separated by commas.
Vales in an array can be assigned as given below:
arr1[0] = “1”;
arr1[1] = “2”;
……..
……..
arr1[9] = “10”;
The array index is the key to accessing an array element. The name of the array and an index in
square brackets evaluates to the content of that array location. For example:
arr1[0];
arr1[1];
………
………
arr1[9];
Example:
<html>
<head>
<title>Single Dimension Array Example</title>
</head>
<body>
<script language=”JavaScript”>
var myArray = new Array();
myArray[0] = “Maya”;
myArray[1] = “Kavita”;
myArray[2] = “Komal”;
document.write (“myArray[0] = “ + myArray[0] + “ <br>”);
document.write (“myArray[1] = “ + myArray[1] + “ <br>”);
document.write (“myArray[2] = “ + myArray[2] + “ <br>”);
myArray[1] = “Changed”;
document.write (“myArray[1] changed to = “ + myArray[1] + “
<br>”);
</script>
</body>
</html>
The result of code is shown in figure 4.14
Figure 4.13 example of single dimension array
4.7.1 Multidimensional Array
Multidimensional arrays created exactly same way as one-dimensional array. Although not
explicitly included in the language, most JavaScript implementations support a form of
multidimensional arrays. A multidimensional array is an array that has arrays as its elements.
Example:
<html>
<head>
<title>Multi Dimension Array</title>
</head>
<body>
<script>
var personnel = new Array();
personnel[0] = new Array();
personnel[0][0] = ‘Name0’;
personnel[0][1] = ‘Age0’;
personnel[0][2] = ‘Address0’;
personnel[1] = new Array();
personnel[1][0] = ‘Name1’;
personnel[1][1] = ‘Age1’;
personnel[1][2] = ‘Address1’;
personnel[2] = new Array();
personnel[2][0] = ‘Name2’;
personnel[2][1] = ‘Age2’;
personnel[2][2] = ‘Address2’;
document.write(“Name:” + personnel[1][0] + “<br>”);
document.write(“Age:” + personnel[1][1] + “<br>”);
document.write(“Address:” + personnel[1][2] + “<br>”);
</script>
</body>
</html>
The length property retrieves the index of the next available (unfilled) position at the end of the
array. Even if some lower indices are unused, length gives the index of the first available slot
after the last element. Consider the following:
var myArray = new Array();
myArray[1000] = "This is the only element in the array";
alert(myArray.length);
Even though myArray only has one element at index 1000, as we see by the alert dialog
myArray.length, the next available slot is at the end of the array, 1001. The length property is
automatically updated as new elements are added to the array.
Setting length to a value greater than the index of the last valid element has no effect on the array
contents, though it will increase the number of undefined slots in the array. Consider, for
example, the result of the following script,
var myArray = ["red", "green", "blue"];
myArray.length = 20;
alert("myArray="+myArray);
the output is:
Figure 4.14 example of array length property
Array has various methods. They are described as follows:
4.7.2 Array Methods
Javascript has several built in methods for manipulation of arrays.
4.7.2.1 join():
The join() method converts the array to a string and allows the programmer to specify how the
elements are separated in the resulting string. When you print an array, the output is a commaseparated list of the array elements. You can use join() to format the list separators as you like.
Fro eg:
Example
var myArray = ["red", "green", "blue"];
var stringVersion = myArray.join(" / ");
alert(stringVersion);
Figure 4.15 example of array join method
4.7.2.2 reverse()
The reverse() method reverses the order of the elements in an array (makes the last element first,
and the first element last).
Example
var myArray = ["red", "green", "blue"];
var stringVersion = myArray.reverse();
alert(stringVersion);
The result of code is shown in figure 4.16
Figure 4.16 example of array reverse() method
4.7.2.3 push()
The push() method adds new elements to the end of an array, and returns the new length
Syntax
array.push(element1, element2, ..., elementX)
Example
<html>
<head>
<script type="text/javascript">
var stack = [ ];
stack.push("first");
stack.push(10, 20);
stack.push(2);
document.write(stack);
</script>
</html>
The result of code is shown in figure 4.17
Figure 4.17 example of array push() method
4.7.2.4 pop()
The pop() method removes the last element of an array, and returns that element.
Syntax
array.pop()
Example
<html>
<head>
<script type="text/javascript">
var stack = [ ];
stack.push("first");
stack.push(10, 20);
document.write(stack.pop() );
document.write("<BR>");
stack.push(2);
document.write(stack.pop());
document.write("<BR>");
document.write(stack.pop());
document.write("<BR>");
document.write(stack.pop());
</script>
</html>
The result of code is shown in figure 4.18
Figure 4.18 example of array pop() method
4.7.2.5 unshift()
The unshift() method adds new elements to the beginning of an array, and returns the new length.
Note: The unshift() method returns undefined in Internet Explorer!
Syntax
array.unshift(element1,element2, ..., elementX)
Example
<html>
<head>
<script type="text/javascript">
var stack = [4,10];
stack.unshift("first");
stack.unshift(10, 20);
document.write(stack.unshift(2) +”<br>”);
document.write(stack);
</script>
</html>
The result of code is shown in figure 4.19
Figure 4.19 example of array unshift() method
4.7.2.6 shift()
The shift() method removes the first element of an array, and returns that element.
Syntax
array.shift()
Example
<html>
<head>
<script type="text/javascript">
var stack = [4,10];
document.write(stack.shift() +"<br>");
stack.unshift(20, 30);
document.write(stack +"<br>");
document.write(stack.shift() +"<br>");
document.write(stack);
</script>
</html>
The result of code is shown in figure 4.20
Figure 4.20 example of array shift() method
4.7.2.7 Sort()
The sort() method sorts the elements of an array.
Syntax
array.sort()
Example
<html>
<head>
<script type="text/javascript">
var s1= ["f", "a", "e", "g"];
document.write(s1.sort());
</script>
</html>
The result of code is shown in figure 4.21
Figure 4.21 example of array sort() method
4.8
User Define Functions
Functions allow you to create bunch of code that perform specific task. JavaScript has a number
of built-in functions that are part of the language. It also allows the user to create its own
functions. A function is capable of returning a value to the statement that invoked it, but this is
not a mandatory. The function can return the value using return keyword. When a function
returns a value, the calling statement treats the function call like any expression—plugging in the
returned value right where the function call is made. Function can return only one value. The
syntax is as follows:
4.8.1 How to define Function
Syntax
function functionName ( [parameter1]...[,parameterN] )
{
statement[s]
}
A simple function that takes no parameters called sayHello is defined below:
function sayHello()
{
alert("Hello there");
}
To invoke the function somewhere later in the script, you have to write the statement something
like this:
sayHello();
You also can define functions so they receive parameter values from the calling statement.
Below eg. shows a simple document that has a button whose onClick event calls a function while
passing text data to the function.
Example
<html>
<head>
<script language=”JavaScript”>
function showMsg(msg)
{
alert(“The button sent: “ + msg)
}
</script>
</head>
<body>
<form>
<input type=”button” value=”Click Me” onClick=”showMsg (‘The
button has been clicked!’)”>
</form>
</body>
</html>
Output
Msgbox will come The Button sent: The button has been clicked!
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:
Example
<script language=”JavaScript”>
function sayHiToFirst(p, q, r)
{
alert(“Say hello, “ + p)
}
sayHiToFirst(“A”, “B”, “C”)
sayHiToFirst(“X”, “Y”, “Z”)
</script>
4.8.2 Function and invoke is done in body tag only
<html>
<head>
</head>
<body>
<script language="JavaScript">
function sayHiToFirst(p,q,r)
{
alert("Say hello, " + p);
}
sayHiToFirst("A", "B", "C");
sayHiToFirst("X", "Y", "Z");
</script>
</body>
</html>
4.8.3 Function in Head and invoke is done in body
<html>
<head>
<script language="JavaScript">
function sayHiToFirst(p,q,r)
{
alert("Say hello, " + p);
}
</script>
</head>
<body>
<script language="JavaScript">
sayHiToFirst("A", "B", "C");
sayHiToFirst("X", "Y", "Z");
</script>
</body>
</html>
After the function is defined in the script, the next statement calls that function, passing three
strings as parameters. The function definition automatically assigns the strings to variables p, q,
and r. Therefore, before the alert() statement inside the function ever runs, p evaluates to “A,” q
evaluates to “B,” and r evaluates to “C.” In the alert() statement, only the p value is used and the
alert reads
Say hello, A
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 p, q, and r. The alert dialog box reads
Say hello, X
4.8.4 Returning values from function is demonstrated as below:
<html>
<head>
<script language="JavaScript">
function addThree(arg1, arg2, arg3)
{
return (arg1+arg2+arg3);
}
</script>
</head>
<body>
<script language="JavaScript">
var x = 5, y = 7, result;
result = addThree(x,y,11);
alert(result);
</script>
</body>
</html>
4.8.5 Variable Scope
There are only two basic scopes: global and local. Variables defined outside of functions are
called global variables. They are known (“visible”) throughout a document. Variables defined
inside functions are called local variables. It is limited to the particular block of code it is defined
within. The body of a function has its own local scope. Local scope allows for the reuse of
variable names within a document.
Example
<html>
<head>
<script language=”JavaScript”>
var aBoy = “John
// global
var hisDog = “Snoopy”
// global
function demo()
{
// using improper design to demonstrate a point
var hisDog = “Tommy
// local version of hisDog
var output = hisDog + “ does not belong to “ + aBoy +
“.<BR>”
document.write(output)
}
</script>
</head>
<body>
<script language=”JavaScript”>
demo()
// runs as document loads
document.write(hisDog + “ belongs to “ + aBoy + “.”)
</script>
</body>
</html>
When the page loads, the script in the Head portion initializes the two global variables (aBoy and
hisDog) and defines the demo() function in memory. In the Body, another script begins by
invoking the function. Inside the function, a local variable is initialized with the same name as
one of the global variables—hisDog. In JavaScript, such a local initialization overrides the global
variable for all statements inside the function. (But note that if the var keyword is left off of the
local initialization, the statement reassigns the value of the global version to “Tommy.”) Another
local variable, output, is used to store text which is to be written on the screen. The accumulation
begins by evaluating the local version of the hisDog variable. Then it concatenates some hard
text. Next comes the evaluated value of the aBoy global variable—any global not overridden by
a local is available for use inside the function. The expression is accumulating HTML to be
written to the page, so it ends with a period and a <BR> tag. The final statement of the function
writes the content to the page. After the function completes its task, the next statement in the
Body script writes another string to the page. Because this script statement is executing in global
space, it accesses only global variables— including those defined in another <SCRIPT> tag set
in the document. By the time the complete page finishes loading, it contains the following text
lines:
Tommy does not belong to John.
Snoopy belongs to John.
4.9 Built-in functions
JavaScript provides many built in functions that ease the development of JavaScript programs.
Here are the lists of the built-in JavaScript functions.
4.9.1 Built in function of String Object
The String object is used to store a sequence of character (letter, numbers, spaces, and so on).
String objects are created with new String().
Syntax
Var txt = new String(“string”);
Or
Var txt = “String”
4.9.1.1 CharAt()
The charAt() method returns the character at the specified index in a string.
The index of the first character is 0, and the index of the last character in a string called "txt", is
txt.length-1.
Syntax
string.charAt(index)
Example
<HTML>
<BODY>
<SCRIPT language="JavaScript">
var the_name="abc";
first_char=the_name.charAt(0);
//first_char=a
if (first_char=="S")
//a==S condition False
{
document.write(“First Character is S”);
} else {
document.write(“First Character is “ + first_char);
}
</SCRIPT>
</BODY>
</HTML>
Output
First Character is a
In above example a==S condition will be false so else part will execute so output will be First
character is a
4.9.1.2 Concat()
The concat() method is used to join two or more strings.This method does not change the
existing strings, it only returns a copy of the joined strings.
Syntax
string.concat(string2, string3, ..., stringX)
Example
<html>
<script language="JavaScript">
var myString1 = new String("Hello, ");
var myString2 = new String("World!");
var myConcatString = myString1.concat(myString2);
alert(myConcatString);
</script>
</html>
Output
Hello World!
4.9.1.3 indexOf()
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
Syntax
string.indexOf(searchstring, start)
The start position in the string to start the search. If omitted, the search starts from position 0
The indexOf() method is case sensitive!
Example
<html>
<script language="JavaScript">
var myString = new String("Hello, World!");
document.write(myString.indexOf("z") + '<br>');
document.write(myString.indexOf(" ") + '<br>');
document.write(myString.indexOf("l", 4));
</script>
</html>
//(char,startfrom number)
The result of code is shown in figure 4.22
Figure 4.21 example of indexOf()
In above example indexOf(z) not found in string so it return -1, position of space in string is 6 so
it return 6 and indexOf(l,4) position of “l” but start searching from 4 position. So it return 10
4.9.1.4 lastindexOf()
The lastIndexOf() method returns the position of the last found occurrence of a specified value in
a string.
Note: The string is searched backward, but the index returned is the character position from left
to right (starting at 0).
This method return -1 if the value to search for never occurs.
Syntax
string.lastIndexOf(searchstring, start)
The lastIndexOf() method is case sensitive!
Example
<html>
<script language="JavaScript">
var myString = new String("Hello World, here I am!");
document.write(myString.lastIndexOf("e") + '<br>');
document.write(myString.lastIndexOf("l", 3));
</script>
</html>
In above example output will be 16 and 3, lastIndexof(e) is 16 and lastIndexof(l) will be 9 but
start from 3 so output will be 3.
4.9.1.5 replace()
The replace () method searches for a match between a substring and a string, and replaces the
matched substring with a new substring
Syntax
string.replace (substr, newstring)
Following regular expression modifier may be used
 g get all matches
 m serve all multiple lines of text
 i case insensitive search
Example
<html>
<head>
<title>Using the replace() method of the String object</title>
<script type="text/javascript" language="javascript">
var originalString = "A ab abc abcd";
var replacedString = /a/g;
//"a" get all matches
var replacementString = "z";
var newString = originalString.replace(replacedString, replacementString);
document.write("<h3>" + newString + "</h3");
</script>
</head>
<body>
Output
A zb zbc zbcd
In above program all a will be replaced by z.
4.9.1.6 Search()
The search() method searches for a match between a regular expression and a string. Its same as
indexOf() method
This method returns the position of the match, or -1 if no match is found.
Syntax
string.search(regexp)
Example
<html>
<script language="JavaScript">
//return index of searched string
var myString = new String("This is a test");
var myRegExp = "s";
var answerIdx = myString.search(myRegExp);
if(answerIdx == -1){
document.write('No matches were found');
}else{
document.write('Your search string was found starting at: ' + answerIdx);
}
</script>
</html>
Output
Your search string was found starting at: 3
In above program string This is a test string it will search for s and return the index of searched
character that is 3.
4.9.1.7 substr()
This method returns the characters in a string beginning at the specified location through the
specified number of characters.
Syntax
string.substr(start[, length]);
Here is the detail of parameters:

start : Location at which to begin extracting characters (an integer between 0 and one less
than the length of the string).
 length : The number of characters to extract.
Note: If start is negative, substr uses it as a character index from the end of the string.
Return Value:

The substr method returns the new sub string based on given parameters.
<html>
<script language="JavaScript">
var myString = new String("This is a test");
var a = myString.substr(1,3);
//last character of the string
var b = myString.substr(5,-3);
//length is not in negative
document.write('The first characters of our string, ' + a + "<BR>");
</script>
</html>
The first characters of our string, Thi
Output
The first characters of our string, his
In above example substr(1,3) where 1 represents the starting position of the string that is h and 3
represents the number of characters you want from string, if length is not specified then it will
return till end of string.
4.9.1.8 substring()
The substring() method extracts the characters from a string, between two specified indices, and
returns the new sub string.
This method extracts the characters in a string between "from" and "to", not including "to" itself
Syntax
string.substring(from, to)
from
to
Required. The index where to start the extraction. First character is at index 0
Optional. The index where to stop the extraction. If omitted, it extracts the rest of the
string
Example
<html>
<head>
<title>JavaScript String substring() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
document.write("(1,2): " + str.substring(1,2));
document.write("<br />(0,10): " + str.substring(0, 10));
document.write("<br />(5): " + str.substring(5));
</script>
</body>
</html>
Output
(1,2): p
(0,10): Apples are
(5): s are round, and apples are juicy.
//from 1st position to 2nd position
// from 0 to 10 position
//from 5th position to end of string
4.9.1.9 toLowerCase()
The toLowerCase() method converts a string to lowercase letters.
Syntax
string.toLowerCase()
Example
<script type="text/javascript">
var str="Hello World!";
document.write(str.toLowerCase());
</script>
Output
hello world!
4.9.1.10 toUpperCase()
The toUpperCase() method converts a string to uppercase letters.
Syntax
string.toUpperCase()
Example
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
Output
HELLO WORLD!
4.9.2 Built in function of Math Object
The Math object allows you to perform mathematical tasks.
4.9.2.1 abs()
The abs() method returns the absolute value of a number.
Syntax
Math.abs(n)
n
Required number
Example
<html>
<head><title>Example of abs() Function</title>
</head>
<body>
<script type="text/javascript">
document.write(Math.abs(5.15) + "<br />");
document.write(Math.abs(-5.15) + "<br />");
document.write(Math.abs("Hello") + "<br />");
</script>
</body>
</html>
Output
5.15
5.15
NaN
In above example -5.15 will be converted into absolute number and hello is not a number so it
will return NaN.
4.9.2.2 ceil()
The ceil() method rounds a number UPWARDS to the nearest integer, and returns the result.
Syntax
Math.ceil(n)
n
Required number
Example
<html>
<head><title>Example of ceil() Function</title>
</head>
<body>
<script type="text/javascript">
document.write(Math.ceil(0.60) + "<br />");
document.write(Math.ceil(0.40) + "<br />");
document.write(Math.ceil(5.1) + "<br />");
document.write(Math.ceil(-5.1) + "<br />");
document.write(Math.ceil(-5.9));
</script>
</body>
</html>
Output
1
1
6
-5
-5
In above example ceil() will round up number upward integer number.0.60 to 1, 0.40 to 1,
5.1 to 6 and negative number also round up in upward number -5.1 to -5 and -5.9 to -5.
4.9.2.3 floor()
The floor() method rounds a number DOWNWARDS to the nearest integer, and returns the
result.
Syntax
Math.floor(n)
n
Required number
Example
<html>
<head><title>Example of floor() Function</title>
</head>
<body>
<script type="text/javascript">
document.write(Math.floor(0.60) + "<br />");
document.write(Math.floor(0.40) + "<br />");
document.write(Math.floor(5.1) + "<br />");
document.write(Math.floor(-5.1) + "<br />");
document.write(Math.floor(-5.9));
</script>
</body>
</html>
Output
0
0
5
-6
-6
In above example ceil() will round up number downward integer number.0.60 to 0, 0.40 to 0,
5.1 to 5 and negative number also round up in upward number -5.1 to -6 and -5.9 to -6.
4.9.2.4 pow()
The pow() method returns the value of x to the power of y (xy).
Syntax
Math.pow(x,y)
x
Required .The base
y
Required. The exponent
Example
<html>
<head><title>Example of pow() Function</title>
</head>
<body>
<script type="text/javascript">
document.write(Math.pow(2,4) + "<br />");
document.write(Math.pow(1,2) + "<br />");
document.write(Math.pow(5,2) + "<br />");
</script>
</body>
</html>
Output
16
1
25
In above example (24) is equal to 16, (12) is equals to 1, and (52) equals to 25.
4.9.2.5 random()
The random() method returns a random number between 0 and 1.
Syntax
Math.random()
Example
<html>
<head><title>Example of random() Function</title>
</head>
<body>
<script type="text/javascript">
//return a random number between 0 and 1
document.write(Math.random() + "<br />");
</script>
</body>
</html>
Output
0.1251147060701645
In above example it will generate random number between 0 and 1 everytime you run the
program it will generate different number
4.9.2.6 round()
The round() method rounds a number to the nearest integer.
Syntax
Math.round(n)
n
Required Number
Example
<html>
<head><title>Example of round() Function</title>
</head>
<body>
<script type="text/javascript">
document.write(Math.round(0.60) + "<br />");
document.write(Math.round(0.50) + "<br />");
document.write(Math.round(0.49) + "<br />");
document.write(Math.round(-4.60) + "<br />");
</script>
</body>
</html>
Output
1
1
0
-5
In above example will round up the number to nearest interger, 0.60 to 1, 0.50 to 1, 0.49 to 0
because value is less than 0.50 so it will not round up to nearest integer, and negative value -4.60
will round up to -5.
4.9.2.7 min()
The min() method returns the number with the lowest value.
Syntax
Math.min(x,y,z,...,n)
One or more numbers.If no arguments are given, the result is Infinity
Example
<html>
<head><title>Example of min() Function</title>
</head>
<body>
<script type="text/javascript">
document.write(Math.min(5,10) + "<br />");
document.write(Math.min(0,150,30,20,38) + "<br />");
document.write(Math.min(-5,10) + "<br />");
document.write(Math.min(-5,-10) + "<br />");
document.write(Math.min(1.5,2.5));
</script>
</body>
</html>
Output
5
0
-5
-10
1.5
In above example it will return minimum number from the given list example.-5 and -10
minimum is -10, same way 1.5 and 2.5 minimum value is 1.5
4.9.2.8 max()
The max() method returns the number with the highest value.
Syntax
Math.max(x,y,z,...,n)
One or more numbers can be pass as argument. If no arguments are given, the result is Infinity
Example
<html>
<head><title>Example of max() Function</title>
</head>
<body>
<script type="text/javascript">
document.write(Math.max(5,10) + "<br />");
document.write(Math.max(0,150,30,20,38) + "<br />");
document.write(Math.max(-5,10) + "<br />");
document.write(Math.max(-5,-10) + "<br />");
document.write(Math.max(1.5,2.5));
</script>
</body>
</html>
Output
10
150
10
-5
2.5
In above example it will return maximum number from the given list example.-5 and -10
minimum is -5, same way 1.5 and 2.5 minimum value is 2.5
4.9.3 Built in function of Date Object
Date Object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
Syntax
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(date as a String);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Once a Date object is created, a number of methods allow you to operate on it. Most methods
allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the
object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC)
with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
4.9.3.1 getDate()
The getDate() method returns the day of the month (from 1 to 31) for the specified date,
according to local time.
Syntax
Date.getDate()
Example
<html>
<head><title>Example of getDate() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date("June 26, 1983 02:55:00");
document.write(d.getDate());
</script>
</body>
</html>
Output
26
4.9.3.2 getDay()
The getDay() method returns the day of the week (from 0 to 6) for the specified date, according
to local time.Sunday is 0, Monday as 1 and so on.
Syntax
Date.getDate()
Example
<html>
<head><title>Example of getDate() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date("June 26, 1983 02:55:00");
document.write(d.getDay());
</script>
</body>
</html>
Output
0.
In above example return 0 means Sunday
4.9.3.3 getMonth()
The getMonth() method returns the month (from 0 to 11) for the specified date, according to
local time. January is 0, February is 1, and so on.
Syntax
Date.getMonth()
Example
<html>
<head><title>Example of getDate() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date("June 26, 1983 02:55:00");
document.write(d.getMonth());
</script>
</body>
</html>
Output
5
In above example returns 5 means June.
4.9.3.4 getFullYear()
The getFullYear() method returns the year (four digits) of the specified date, according to local
time.
Syntax
Date.getFullMonth()
Example
<html>
<head><title>Example of getDate() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
document.write(d.getFullYear());
</script>
</body>
</html>
Output will be 2011.
4.9.3.5 getHours()
The getHours() method returns the hour (from 0 to 23) of the specified date and time, according
to local time.
Syntax
Date.getHours()
Example
<html>
<head><title>Example of getHours() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date("June 26, 1983 02:55:00");
document.write(d.getHours());
</script>
</body>
</html>
Output
2
4.9.3.6 getMinutes()
The getMinutes() method returns the minutes (from 0 to 59) of the specified date and time,
according to local time
Syntax
Date.getMinutes()
Example
<html>
<head><title>Example of getMinutes() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date("June 26, 1983 02:55:00");
document.write(d.getMinutes());
</script>
</body>
</html>
Output
55
4.9.3.7 getSeconds()
The getSeconds() method returns the seconds (from 0 to 59) of the specified date and time,
according to local time.
Syntax
Date.getSconds()
Example
<html>
<head><title>Example of getSeconds(() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date("June 26, 1983 02:55:23");
document.write(d.getSeconds());
</script>
</body>
</html>
Output
23
4.9.3.8 getMilliseconds()
The getMilliseconds() method returns the milliseconds (from 0 to 999) of the specified date and
time, according to local time.
Syntax
Date.getMilliseconds()
Example
<html>
<head><title>Example of getMilliseconds() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date("June 26, 1983 02:55:23");
document.write(d. getMilliseconds());
</script>
</body>
</html>
Example will set milliseconds to 0, since no milliseconds was defined in the date.
4.9.3.9 setDate()
The setDate() method sets the day of the month (from 1 to 31), according to local time.
Syntax
Date.setDate(day)
Day required. An integer value between 1 to 31 representing day of month
Example
<html>
<head><title>Example of setDate() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
d.setDate(15);
document.write(d);
</script>
</body>
</html>
Output
Wed Jun 15 17:46:59 UTC+0530 2011
4.9.3.10 setMonth()
The setMonth() method sets the month (from 0 to 11), according to local time. January is 0,
February is 1, and so on.
Syntax
Date.setMonth(month,day)
month
day
Required. An integer between 0 and 11 representing the month
Optional. An integer between 1 and 31 representing the day
Example
<html>
<head><title>Example of setMonth() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
d.setMonth(1,5);
document.write(d);
</script>
</body>
</html>
Output
Sat Feb 5 17:51:41 UTC+0530 2011
In above example Month is set to February and Day will set to 5, Hour minute and seconds will
be current hour minute and second.
4.9.3.11 setFullYear()
The setFullYear() method sets the year (four digits), according to local time.
Syntax
Date.setFullYear(year,month,day)
year
month
day
Required. A four-digit value representing the year
Optional. An integer between 0 and 11 representing the month
Optional. An integer between 1 and 31 representing the day
Example
<html>
<head><title>Example of setFullYear() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
d.setFullYear(2011,5,2);
document.write(d);
</script>
</body>
</html>
Output
Thu Jun 2 17:56:46 UTC+0530 2011
In above example Month is set to June and Day will set to 2, Hour minute and seconds will be
current hour minute and second and year will set 2011.
4.9.3.12 setHours()
The setHours() method sets the hour (from 0 to 23), according to local time.
Syntax
Date.setHours(hour,min,sec,millisec)
Hour Required. An integer between 0 and 23 representing the hour
Min
Optional. An integer between 0 and 59 representing the minutes
Sec
Optional. An integer between 0 and 59 representing the seconds
Millisec Optional. An integer between 0 and 999 representing the milliseconds
Example
<html>
<head><title>Example of setHours() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
d.setHours(15,5,2);
document.write(d);
</script>
</body>
</html>
Output
Sun Jun 26 15:05:02 UTC+0530 2011
In above example Hour, min and sec set by user and Month day and Year will set current Month
day and Year, if you want you can set month day and year with help of function setFullYear().
4.9.3.13 setMinutes()
The setMinutes() method sets the minutes (from 0 to 59), according to local time.
Syntax
Date.setMinutes(min,sec,millisec)
Min
Required. An integer between 0 and 59 representing the minutes
Sec
Optional. An integer between 0 and 59 representing the seconds
Millisec Optional. An integer between 0 and 999 representing the milliseconds
Example
<html>
<head><title>Example of setMinutes() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
d.setMinutes(1);
document.write(d);
</script>
</body>
</html>
Output
Sun Jun 26 18:01:21 UTC+0530 2011
In above example Minutes, Seconds and Milliseconds set by user and Hour,Month day and Year
will set current hour,Month day and Year, if you want you can set month day and year with help
of other function.
4.9.3.14 setSeconds()
The setSeconds() method sets the seconds (from 0 to 59), according to local time.
Syntax
Date.setSeconds(sec,millisec)
Sec
Required. An integer between 0 and 59 representing the seconds
Millisec Optional. An integer between 0 and 999 representing the milliseconds
Example
<html>
<head><title>Example of setSeconds() Function</title>
</head>
<body>
<script type="text/javascript">
var d = new Date();
d.setSeconds(1);
document.write(d);
</script>
</body>
</html>
Output
Sun Jun 26 18:10:01 UTC+0530 2011
In above example Seconds and Milliseconds set by user and Hour Minutes, Month day and Year
will set current Month day and Year, if you want you can set month day and year with help of
other function.
4.10 What are Events?
The basic purpose of JavaScript is to add interactivity to your web pages. This interactivity is
provided by responding to user actions. It means when user performs some tasks, it reacts by
executing a piece of code. The set of tasks that user perform on a web page are called events.
Events are signals generated when specific actions occur. Scripts can be built to react to these
events. Various events available in JavaScript are as follows:
1. Abort:
This event is occurs when the user cancels loading of an image, or any document.
2. Blur:
This event occurs when input focus is removed from a form element or focus is removed from a
window.
3. Click:
This event occurs when the user clicks on a link or form element.
4. Double Click:
This event occurs when the user double clicks on a link or form element.
5. Change:
This event occurs when the value of a form field is changed by the user.
6. Drag Drop:
This event occurs when an icon is dragged and dropped into the browser.
7. Error:
This event occurs when an error occurs during loading of document or image.
8. Focus:
This event occurs when input focus is given to a form element or a window by clicking on it or
by pressing TAB key.
9. Load:
This event occurs when a page is loaded in the browser.
10. Mouse Down:
This event occurs when the user presses a mouse button.
11. Mouse Move:
This event occurs when the user moves the mouse.
12. Mouse Out:
This event occurs when the user moves the pointer off of a link or clickable area of an image.
13. Mouse Over:
This event occurs when the user moves the pointer over a hypertext link.
14. Mouse Up:
This event occurs when the user releases a mouse button.
15. Key Down:
This event occurs when the user presses any key.
16. Key Press:
This event occurs when the user presses or holds down a key.
17. Key Up:
This event occurs when the user releases a key.
18. Move:
This event occurs when the user moves the browser window or frame.
19. Resize:
This event occurs when the user resizes the browser window or frame.
20. Reset:
This event occurs when the user clears a form using the reset button.
21. Select:
This event occurs when the user selects text within the field.
22. Submit:
This event occurs when a form is submitted.
23. Unload:
This event occurs when the user leaves the page.
4.11 What are Event Handlers?
JavaScript identifies an event and takes an action by executing some piece of code. The
procedure of taking action is called event handling, code that take an action is called event
handler. Event handlers are small JavaScript code placed inside an HTML tag. Event Handlers
are scripts in the form of attributes of specific HTML tags. They help in handling (catching)
events. The basic format of an event handler is:
<html_tag other_attributes event_handler=”JavaScript Program;”>
Any JavaScript statements or functions can appear within the quotation marks of an event
handler. For example, if you have a form with a text field and want to call the function
checkField() whenever the value of text field changes, you should define as:
<input type=”text” onChange=”checkField();”>
Various event handlers are as follows:
onAbort
onBlur
onClick
onDblClick
onChange
onDragDrop
onError
onFocus
onLoad
onMouseDown
onMouseMove
onMouseOut
onMouseOver
onMouseUp
onKeyDown
onKeyPress
onKeyUp
onMove
onResize
onReset
onSelect
onSubmit
onUnload
Below table shows which window and form elements have event handlers available to them:
Sr.
No.
1
2
3
4
5
6
7
Object
Event Handlers Available
Selection List
Text
Textarea
Button
Checkbox
Radio Button
Hypertext Link
onBlur, OnChange, OnFocus
onBlur, OnChange, OnFocus, onSelect
onBlur, OnChange, OnFocus, onSelect, onKeyDown, onKeyPress
onClick, onBlur, onFocus, onMouseDown, onMouseUp
onClick, onBlur, onFocus
onClick, onBlur, onFocus
onClick, onMouseOver, onMouseOut, onKeyDown, onKeyPress,
onMouseDown, onMouseOut, onMouseOver, onMouseUp
8
onMouseOver, onMouseOut
9
10
11
Clickable Image
Area
Reset
Submit
Document
12
13
14
15
Window
Framesets
Form
Image
4.12
onClick, onBlur, onFocus
onClick, onBlur, onFocus
onLoad, onUnload, onError, onClick, onDblClick, onKeyDown,
onKeyPress, onMouseDown, onMouseUp
onLoad, onUnload, onBlur, onFocus, onDragDrop, onError, onResize
onBlur, onFocus, onMouseMove
onSubmit, onReset, onLoad
onLoad, onError, onAbort, onKeyDown, onKeyPress, onMouseOut,
onMouseOver
JavaScript Objects
JavaScript is an Object Oriented Programming (OOP) language.
An OOP language allows you to define your own objects and make your own variable types.
Object is an collection of related properties and methods. Properties represent features and
methods represent action that may be performed upon those objects. JavaScript objects are
different from C++/Java objects. Properties and methods can be added at any time even after the
creation of an object.
Object Properties
Object properties are usually variables that are used internally in the object's methods, but can
also be globally visible variables that are used throughout the page. Object properties accessed
using the dot(.) operator
The syntax for adding a property to an object is:
objectName.objectProperty = propertyValue;
Example
Following is a simple example to show how to get a document title using "title" property of
document object
var str = document.title
Object Methods:
The methods are functions that let the object do something or let something be done to it. There
is little difference between a function and a method, except that a function is a standalone unit of
statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
Example:
Following is a simple example to show how to use write() method of document object to write
any content on the document:
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object
called Object.
The new Operator:
The new operator is used to create an instance of an object. To create an object, the new operator
is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These
constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor:
A constructor is a function that creates and initializes an object. JavaScript provides a special
constructor function called Object() to build the object. The return value of the Object()
constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are not
variables and are not defined with the var keyword.
Example 1:
This example demonstrates how to create an object:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
To understand it in better way you can Try it yourself.
Example 2:
This example demonstrates how to create an object with a User-Defined Function. Here this
keyword is used to refer to the object that has been passed to a function:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
To understand it in better way you can Try it yourself.
Defining Methods for an Object:
The previous examples demonstrate how the constructor creates the object and assigns
properties. But we need to complete the definition of an object by assigning methods to it.
Example:
Here is a simple example to show how to add a function along with an object:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
this.price = amount;
}
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
JavaScript has several built-in or browser objects and DOM Objects. These objects are accessible
anywhere in your program and will work the same way in any browser running in any operating
system. The components of web pages are represented by objects that are organized in a
hierarchical structure called DOM (Document Object Model). The hierarchical structure
represents parent-child relationship. Child object is basically properties of their parent object.
These objects have properties and methods that can be used to work with web pages. The top of
the hierarchy is window object, which represents entire browser window that displays the
document. All other object are direct indirect child object of window. Let’s see one by one object
with their properties and method
4.13
Document Object
Each HTML document loaded into a browser window becomes a Document object The
Document object provides access to the elements in an HTML page from within your script. This
includes the properties of every form, link and anchor (and, where applicable, any sub-elements),
as well as global Document properties such as background and foreground colors.
Document object have different property and methods.
4.13.1
Properties
alinkColor
Syntax:
document.alinkColor = "colorinfo"
This property defines the color of an active link. The "color info" argument is a string that can
contain either the hexadecimal definition of the color or its literal description. If you use the hex
definition of a color it must be in the format rrggbb - for example, the hex value for the named
color 'forest green' is '228B22'.
anchor
This property is an array containing references to all the named Anchor objects in the current
document. These references are stored in the array in the order in which they are defined in the
source code. The anchor name as defined within the <A></A> tags in the HTML source.
Example
<html>
<a name="Trumpet"><h4>Trumpet</h4></a>
A<br>
<a name="Guitar"><h4>Guitar</h4></a>
B<br>
<a name="Piano"><h4>Piano</h4></a>
C<br>
<script language="JavaScript">
for(var counter=0; counter<=document.anchors.length; counter++)
{
document.write(document.anchors[counter].name);
}
</script>
</html>
Above example is of anchor property it will create anchor tag of Trumpet, guitar and
Piano,document.anchors.length will retutn length of anchor 3 and loop will execute 3 times and
print the name of anchor tag with the help of name property.
bgColor
Syntax: document.bgColor = "colorinfo"
This property defines a document's background color. The "colorinfo" argument is a string that
can contain either the hexadecimal definition of the color or its literal description
fgColor
Syntax: document.fgColor = "colorinfo"
This property defines a document's foreground (text) color. The "colorinfo" argument is a string
that can contain either the hexadecimal definition of the color or it's literal description.
Example
<HTML>
<HEAD>
<TITLE>Document Object Example</TITLE>
<SCRIPT type="text/JavaScript">
document.bgColor = "green";
document.fgColor = "Red";
</SCRIPT>
</HEAD>
<BODY>
Hello how r u??<br>
Welcome to Document Property of bgcolor and fgcolor..
</BODY>
</HTML>
Above example will set the background color to green and forecolor to Red of document
forms:
Syntax: document.forms["formID" ]
This property is an array containing references to all the Form objects in the current document.
These references are stored in the array in the order in which they are defined in the source code.
The "formID" argument is used to access items in the array and this can either be a string
containing the form name as defined within the <FORM> tag in the HTML source.
Example
<html>
<form name="Form1">
<input type="button" value="Green">
</form>
<form name="Form2">
<input type="button" value="Blue">
</form>
<script language="JavaScript">
document.write(document.forms.length," Form objects in document.");
</script>
</html>
images
Syntax: document.images["imageID"]
This property is an array containing references to all the Image objects in the current document.
These references are stored in the array in the order in which they are defined in the source code.
The "imageID" argument is used to access items in the array and this can either be a string
containing the image name as defined within the <IMG> tag in the HTML source.
Example
<html>
<h2>A Circle</h2>
<img src="Sunset.jpg">
<h2>A Square</h2>
<img src="Blue hills.jpg"><br>
<script language="JavaScript">
for(i=0;i<document.images.length;i++)
{
document.write("The source of image object ",(i+1));
document.write(" is <i><b>",document.images[i].src,"</b></i><br>");
}
</script>
</html>
Above example loop will execute 2 times, because length of image is 2, and print the source of
image.
lastModified
Syntax: document.lastModified
This property returns the date that the document was last modified. This property returns a string
relating to the date that the document was last modified.
Example
<script language="JavaScript">
document.write(document.lastModified," the following ");
</script>
Above example will return date of last modified date.
linkColor
Syntax: document.linkColor = "colorinfo"
This property defines the color of any hyperlinks in the document. The "colorinfo" argument is a
string that can contain either the hexadecimal definition of the color or it's literal description. If
you use the hex definition of a color it must be in the format rrggbb
Example
<html>
<script language="JavaScript">
document.linkColor="green";
</script>
<a href="Click1.html">javacript.com</a>
</html>
In above example linkcolor will set to green.
title
Syntax: document.title
This property returns the document's name as defined between the <TITLE></TITLE> tags.
url
Syntax: document.URL
This property is used to retrieve the document's full URL.
Example
<html><head>
<title>Example of document object</title>
<script language="JavaScript">
document.write(document.title);
document.write("<BR>");
document.write(document.URL);
</script></head>
</html>
Output
Example of document object
file://C:\Users\Desktop\document.html
In above example return the title of the document and URL will return url of document.
vlinkColor
Syntax: document.vlinkColor = "colorinfo"
This property defines the color of any visited links in the document. The "colorinfo" argument is
a string that can contain either the hexadecimal definition of the color or its literal description. If
you use the hex definition of a color it must be in the format rrggbb.
Example
<html>
<script language="JavaScript">
document.vlinkColor="green";
</script>
<a href="#">javacript.com</a>
</html>
In above example visited link color will set to green.
4.13.2 Methods
getElementById:
Syntax: document.getElementById(id)
This element receives a string containing the id of a specific element and returns a reference to it.
After obtaining a reference to the object, you can use the get and set attributes.
Example:
<html>
<head>
<script type="text/javascript">
function getElement()
{
var x=document.getElementById("myHeader") //object is created
alert("I am a " + x.tagName + " element") //tagName is property to return the tag Name ie H1
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1>
</body>
</html>
In above example user will click the document, function will call and alert message will print “I
am a H1 element”.
getElementsByName()
Syntax :document.getElementsByName(name)
The getElementsByName() method accesses all elements with the specified name, This element
receives a string containing the name of a specific element and returns a reference to it.
For example take an above example only change getElementById to getElementByName method
in function and add name attribute in <H1> tag.
function getElement()
{
var x=document.getElementByName("myHeader")
alert("I am a " + x.tagName + " element")
}
<h1 name="myHeader" onclick="getElement()">Click to see what element I am!</h1>
Open()
Syntax: document.open([Type [, replace]])
This method is used to open a stream to collect the output from any write or writeln methods.
The first of the optional parameters is Type which determines the type of document you are
writing to; if this parameter is not used, the default value is "text/html". The second parameter is
replace, also optional, which causes the history entry for the new document to inherit the history
entry from the document from which it was opened.
Close()
Syntax: document.close( )
This method closes an output stream previously opened with the document.open method and
forces data collected from any instances of the document.write or document.writeln methods to
be displayed.
Example
<script>
function newWindowTest()
{
var message1 = "Hello, world!"
var message2 = "This is a test."
newWindow.document.open("text/html", "replace")
newWindow.document.writeln(message1)
newWindow.document.write(message2)
newWindow.document.close()
}
newWindow=window.open('','','toolbar=no,scrollbars=no,width=200,height=150')
newWindowTest()
</script>
Output:
"Hello, world! This is a test."
The following code demonstrates this method and displays the output stream in a new window.
write()
Syntax: document.write("expression1", [expression2, [...]])
This method is used to write HTML expressions to the specified document in a current or new
window. Multiple arguments, ("expression1", [expression2, [...]]), can be listed and they will be
appended to the document in order of occurrence.
In general, it is not necessary to open the document using the document.open method; since the
document.write method will automatically open the file and discard (erase) the contents.
However, after the write is complete, you need to close the document by using the
document.close method. In some browsers, the results of the write may not be completely
displayed, due to buffering, until the close occurs.
Some JavaScript engines append newline when using writeln(...),but not when using write(...). I
recommend to use write("...\n") if newline is required.
Example:
<script>
newWindow = window.open('', 'newWin') //new window will created
var tagBoldOpen = "<b>"
var tagBoldClose = "</b>"
newWindow.document.write(tagBoldOpen)
newWindow.document.write("This is some bold text.", tagBoldClose)
newWindow.document.close()
</script>
Output
This is some bold text
Above example will print this is some bold text in new Window with bold letters because <b>
tag is used.

Writeln
Syntax: document.writeln("expression(s)")
This method is identical to the write method detailed above, with the addition of writing a new
line character after any specified expressions.
4.14 History Object
The history object contains the URLs visited by the user (within a browser window).
The History object is a predefined JavaScript object which is accessible through the history
property of a window object.
The window.history property is an array of URL strings which reflect the entries in the History
object. The History object consists of an array of URLs, accessible through the browser's Go
menu, which the client has visited within a window. It is possible to change a window's current
URL without an entry being made in the History object by using the location, replace method.
4.14.1 Properties
length
Syntax: history.length
The length property contains the number of elements in the History list.
<html>
<body>
<script type="text/javascript">
var ex = history.length;
document.write("The number of pages visited before this page is " +ex+ " pages!!!.")
</script>
</body>
</html>
The output of the above program is
The number of pages visited before this page is 2 pages!!!.
This means that there are 2 entries in the history list and denotes the number of pages visited
before visiting the current page.
4.14.2 Methods
back
Syntax: history.back()
The back method loads the previous URL in the History list, and is equivalent to the browser's
Back button and to history.go(-1).
forward
Syntax: history.forward()
The forward method loads the next URL in the History list, and is equivalent to the browser's
Forward button and to history.go(1).
go()
Syntax: history.go(Number|URL)
history.go(location)
The go method loads a specified URL from the History list.
The parameter can either be a number which goes to the URL within the specific position (-1
goes back one page, 1 goes forward one page), or a string. The string must be a partial or full
URL, and the function will go to the first URL that matches the string.
Example of history object methods, back() forward() and go () method are used
Example
history1.html
<html>
<head>
<script>
function test()
{
history.go(1);
}
</script>
</head>
<body>
<a href=Click1.html> Click 1 </a>
<a href="javascript:history.forward()">Forward</a></p>
<FORM name="form1">
<INPUT type="submit" value="length" onClick="alert(history.length)">
<INPUT type="button" value="GOto" onClick="test()">
</FORM>
</body>
</html>
Click1.html
<P><a href="javascript:history.back()">Back</a></P>
The result of code is shown in figure 4.23 and 4.24
Figure 4.23 example of history object
In above example when user click on Click1 link, new page will open click1.html
Figure 4.24 example of history object
In click1.html Back link will there when user click on back, history1.html will open, for going
back history.back() is used same way for moving forward history.forward() will used. Same way
for history.go(1) means moves in .forward one page
4.15 Navigator Object
The navigator object contains information about the browser.
4.15.1 Properties
appCodeName
Syntax: navigator.appCodeName
The appCodeName property returns the code name of the browser
Example
<script type="text/javascript">
document.write("CodeName: " + navigator.appCodeName);
</script>
appName
Returns the name of the browser
Syntax: navigator.appName
Example
<script type="text/javascript">
document.write("Application Name: " + navigator.appName);
</script>
Above example will print the Application name if you are using IE it will return Microsoft
Internet Explorer, if you are using Firefox it will return Netscape, if you are using opera it will
return Opera
appVersion
Returns the version information of the browser
Syntax: navigator.appVersion
Example
<script type="text/javascript">
document.write("Application Version: " + navigator.appVersion);
</script>
Above example give detail information about version, in google chrome it will give output
something like this,different browser different information will print
CodeName: 5.0 (Windows NT
Chrome/12.0.742.100 Safari/534.30
6.1)
AppleWebKit/534.30
(KHTML,
like
Gecko)
cookieEnabled
Determines whether cookies are enabled in the browser
Syntax: navigator.cookieEnabled
It will return true or false, it returns true if cookie is enable, false if cookie is disable
Example
<script type="text/javascript">
document.write("Cookies enabled: " + navigator.cookieEnabled);
</script>
platform
Returns for which platform the browser is compiled
Syntax: navigator.platform
Example
<script type="text/javascript">
document.write("platform: " + navigator.platform);
</script>
In above program will return Win32, Linux or MacPPC etc totally depends on which platform
and browser used for execute above code. For example
Internet Explorer 6.0 (Windows XP), Internet Explorer 5.5 (Windows XP), Firefox 1.0 (Preview
Release) (Windows XP), Firefox 1.04 (Windows XP), Firefox 1.04 (Windows XP), Opera 7.5
(Identify as Opera) (Windows XP)
Platform: Win32
Internet Explorer 5.23 (Mac Panther 10.3.7), Firefox 1.0 (Mac Panther 10.3.7)
Platform: MacPPC
Firefox 1.0 (Linux), Opera 7.54 (Identify as MSIE 6.0) (Linux)
Platform: Linux i686
4.15.2 Methods
javaEnabled
The javaEnabled() method returns a Boolean value that specifies whether the browser has Java
enabled
Syntax
navigator.javaEnabled()
Example
<script type="text/javascript">
document.write("Java enabled in your Browser " + navigator.javaEnabled());
</script>
Above example will retutn either true or false, if java enabled by your browser it will return true
else false.
4.16 Form Object
Forms allow us to prompt a user for input using elements such as radio buttons, checkboxes and
selection lists. Data gathered in this manner can then be posted to a server for processing. A form
is created by enclosing HTML controls and other elements within <form></form> tags. A page
can contain as many forms as required, but they cannot be overlapping or nested (the closing
</form> tag of a form must precede the opening tag of any subsequent form).
4.16.1 Properties
action
Syntax: formname.action = URL
This property specifies the URL address to which the data gathered by the form will be
submitted or using this property we also can set the URL.
Example
<html>
<head>
<title> Using the action property of the Form object</title>
</head>
<body>
<script language="JavaScript">
function getAction()
{
var actionValue = document.form1.action;
document.form1.msg.value = "Your form was submitted to the following URL:\n
" + actionValue ;
}
</script>
<form name="form1" action="Click1.html">
Enter your street address:<input type="text" name="address" size="40">
<br><br>
<input type="button" value="Submit"onClick=getAction()>
<br><br><br>
<textarea name="msg" rows="5" cols="62"></textarea>
</form>
</body>
</html>
The result of code is shown in figure 4.25
Figure 4.25 Example of action property of form object
elements
Syntax: object.elements
This property is an array containing an object for each element on the form. These objects
(checkboxes, radio buttons, etc.) are added to the array in the order that they appear in the
document's source code.
The result of code is shown in figure 4.26
Figure 4.26 Example of element property of form object
length
Syntax: object.length
This property returns the number of elements in a form.
Example
<html>
<head>
<title> Using the length property of the Form object</title>
</head>
<body>
<script language="JavaScript">
function showNumElements(){
alert("There are " + document.form1.length + " elements in this document");
}
</script>
<form name="form1">
Enter First Name:<input type="text" size=15><br>
Enter Last Name:<input type="text" size=20><br>
Enter address:<input type="text" size=40><br><br>
<input type="button" value="Submit" onClick=showNumElements()>
</form>
</body>
</html>
The result of code is shown in figure 4.27
Figure 4.27 Example of length property of form object
Above example length return number of elements in form. There are three text box and one
submit button.
method
Syntax: object.method
This property is a string specifying how information input in a form is submitted to the server.
This should return either 'get', which is the default, or 'post'.
Example
<html>
<head>
<title> Using the method property of the Form object</title>
</head>
<body>
<script language="JavaScript">
function informMethod(){
alert("The form method is:" + document.form1.method);
}
</script>
<form name="form1" method="get">
Click the button to see what type of Method is used for submission.
<input type="button" value="Click Here" onClick='informMethod()'>
</form>
</body>
</html>
The result of code is shown in figure 4.28
Figure 4.28 Example of method property of form object
name
Syntax: object.name
This property sets or returns the name of the form. Initially contains the name attribute of the
<form> tag.
Example
<html>
<head>
<title>Access the name property of the Form object</title>
</head>
<body>
<script language="JavaScript">
function showName(){
alert("Form Name is: " + document.form1.name);
}
</script>
<form name ="form1" >
Click on the button to get the name of the form
<input type="button" value="click me" onclick='showName()'>
</form>
</body>
</html>
The result of code is shown in figure 4.29
Figure 4.28 Example of name property of form object
Above example when user click on Click me Button function ShowName will call and alert will
print the name of form.
target:
Syntax: object.target
The name of the frame or window the form submission response is sent to by the server. Possible
values are:
name
The name of the target window or frame.
_blank Load the linked document into a new blank
window. This window is not named.
_parent Load the linked document into the immediate
parent of the document the link is in.
Default. Load the linked document into the window
_self
in which the link was clicked (the active window).
_top
Load the linked document into the topmost
window.
Example
<html>
<head>
<title> Using the target property of the Form object</title>
</head>
<body>
<script language="JavaScript">
function show()
{
var tar = document.form1.target;
if(tar == "_new")
{
alert("this window");
} else{
alert("The target has not been specified");
}
}
</script>
<form name="form1" target="_self">
<br><br><br>
<input type="button" value="submit" onClick='show()'>
</form>
</body>
</html>
The result of code is shown in figure 4.30
Figure 4.30 Example of target property of form object
4.16.2 Methods
reset
Syntax: object.reset( )
This method resets the default values of any elements in a form. Emulates the clicking of a Reset
button (although it is not necessary to have a reset button in a form to use this method).
Example
<html>
<body>
<script language="JavaScript">
function function1(){
document.myForm.reset();
}
</script>
<form name="myForm" method="post" action="">
<input type="text" size="50" value="Type something here">
<input type="button" value="reset" onClick="function1()">
</form>
</body>
</html>
Above example when user click on button reset, then all text box value will be cleared or reset.
submit
Syntax: object.submit( )
This method submits a Form. This is the same as clicking a Submit button, and it will perform
the action if action property is set.
4.17 Elements Object
The elements object is used in JavaScript to access all form elements such as fields or buttons
that are present within a form. Since each element inside the form is stored as an array element
within the array elements[], the user can make use of the loop concept to access any individual
element within a form in JavaScript.
For example
document.form1.elements[0]
Above statement is used to access the 1st element within the form. If a user wants to get the total
number of form elements within the form form1, it can be written by the following statement:
document.form1.elements.length
4.17.1 Properties
length
The length property of elements object returns the total number of elements within the form.
Example
<html>
<head>
<title> Using the elements.length property of the Form object</title>
</head>
<body>
<script language="JavaScript">
function getNum()
{
var numOfElements = document.form1.elements.length;
alert("The number of elements in this document are:" + numOfElements);
}
</script>
<form name="form1">
Dummy text box:
<input type="text" name="textbox1" size="25">
<input type="button" value="Dummy Button">
<input type="text" size="20" name="Sample">
<br>
Click on the button to get the number of elements in this form.
<input type="button" value="Get Elements" onClick='getNum()'>
</form>
</body>
</html>
The result of code is shown in figure 4.31
Figure 4.31 Example of length property of elements object
type
The type property of elements object is used to return the type of the form element accessed. The
returned value from this property would be a string type. In other words, the type of form
elements that are returned from this property can be any one of these: button, checkbox, file,
hidden, image, password, radio, reset, submit, text, textarea , select-one, select-multiple
Syntax:
Object.type
Example
<html>
<head>
<script type="text/javascript">
function testing(form1)
{
alert('hello');
for (j=0; j<form1.elements.length; j++)
{
if (form1.elements[j].type=="text")
{
if (form1.elements[j].value=="")
{
alert("Must Enter Value!!!");
break;
}
else
alert("Value is entered!!!");
}
}
}
</script>
</head>
<body>
<form name=form1>
<input type="text" value="xyz" onchange="testing(this.form)">
<form1>
</body>
</html>
The result of code is shown in figure 4.32
Figure 4.31 Example of type property of elements object
In the above example, function testing will call when user change the value of text box, that time
onchange event will call function testing, function testing can be used to check if any text box in
a form from the function call has been left empty. From each element on the form where the
function testing is called, using for loop on the elements array accesses this. The for loop runs
until the elements.length returns the total number of elements within the form. Each element in
the form is checked for text box type by using the if statement:
form1.elements[j].type=="text"
When if returns true then the value of this text box element is checked for empty by the if
statement:
form1.elements[j].value==""
4.18 Form Control Object
Many JavaScript objects are container of other objects. In that one of the container object is
Form, in Form object have their own sub objects. Different sub object are given below.
Object
Description
Properties
An GUI pushbutton  name - The name of the button
control
 type - The object's type. In this
case, "button".
 value - The string displayed on the
button.
checkbox
An GUI check box  checked - Indicates whether the
control
checkbox is checked. This is a read or
write value.
 defaultChecked - Indicates whether
the checkbox is checked by default.
This is a read only value.
 name - The name of the checkbox.
 type - Type is "checkbox".
 value - A read or write string that
specifies the value returned when the
checkbox is selected.
FileUpload This is created with  name - The name of the
the
INPUT FileUpload object.
type="file". This is  type - Type is "file".
the same as the text  value - The string entered which is
element with the returned when the form is submitted.
addition
of
a
directory browser
hidden
An object that
 name - The name of the Hidden
represents a hidden
object.
form field and is used  type - Type is "hidden".
for client/server
 value - A read or write string that
communications
is sent to the server when the form is
submitted.
password
A text field used to  defaultValue - The default value.
send sensitive data to  name - The name of the password
the server
object."
 type - Type is "password".
 value - A read or write string that
is sent to the server when the form is
submitted.
radio
A GUI radio button  checked - Indicates whether the
control.
radio button is checked. This is a read
or write value.
 defaultChecked
Indicates
whether the radio button is checked
by default. This is a read only value.
 length - The number of radio
buttons in a group.
button
Method
click(),
blur(),
focus()
click(),
blur(),
focus()
blur(),
focus()
No methods
exist for this
object
blur(),
select(),
focus()
click(),
blur(),
focus()
reset
A button object used
to reset a form back
to default values
select
A GUI selection list.
This is basically a
drop down list.
submit
A submit
object.
text
A GUI text field
object
textarea
A GUI text area field
object
button
 name - The name of the radio
button.
 type - Type is "radio".
 value - A read or write string that
specifies the value returned when the
radio button is selected.
 name - The name of the reset
object.
 type - Type is "reset".
 value - The text that appears on
the button. By default it is "reset".
 length - The number of elements
contained in the options array.
 name - The name of the selection
list.
 options - An array each of which
identifies an options that may be
selected in the list.
 selectedIndex - Specifies the
current selected option within the
select list
 type - Type is "select".
 name - The name of the submit
button.
 type - Type is "submit".
 value - The text that will appear on
the button.
 defaultValue - The text default
value of the text field.
 name - The name of the text field.
 type - Type is "text".
 value - The text that is entered and
appears in the text field. It is sent to
the server when the form is
submitted.
 defaultValue - The text default
value of the text area field.
 name - The name of the text area.
 type - Type is textarea.
 value- The text that is entered and
appears in the text area field. It is sent
to the server when the form is
submitted.
click(),
blur(),
focus()
blur(),
focus()
click(),
blur(),
focus()
blur(),
select(),
focus()
blur(),
select(),
focus()
Download