Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

7 JavaScript

The document discusses JavaScript, including its uses, features, capabilities, how it works in web pages, and differences between client-side and server-side scripting. It also covers variables, data types, numbers, and including scripts in HTML documents.

Uploaded by

pramod rockz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

7 JavaScript

The document discusses JavaScript, including its uses, features, capabilities, how it works in web pages, and differences between client-side and server-side scripting. It also covers variables, data types, numbers, and including scripts in HTML documents.

Uploaded by

pramod rockz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

JAVAScript

JAVAScript
A scripting or script language is a programming language that supports scripts — programs written for a
special run-time environment that automates the execution of tasks that could alternatively be executed one-
by-one by a human operator.

In general scripting languages are used in small doses, for specific tasks. Such simple tasks illustrate basic
features of the scripting language.

The basic uses of scripting include:


1. Page navigation, formatting and animation.
2. Dynamic page generation, and form validations.

1) JavaScript
JavaScript is a object–based scripting language developed by Netscape, to support the development of both
client and server components of web–based applications. On the client side it can be used to write programs
that are executed by a web browser within the context of web page. On the server side it can be used to write
web server programs that can process information submitted by a web browser and then updates browser’s
display accordingly.

JavaScript can update and change both HTML and CSS. It is lightweight and most commonly used as a part
of web pages, whose implementations allow client-side script to interact with the user and make dynamic
pages. JavaScript is a purely interpreted language.

How JavaScript Works in web:

Features of Javascript
 It is an interpreted language, embedded within HTML pages
 Minimal Syntax- Easy to learn
 Supports quick development and better performance
 Designed for programming user events
 Platform Independent / Architecture Neutral

Javascript Capabilities
 Improve the user interface of a website
 Make your site easier to navigate
 Easily create pop-up alert, windows
 Replace images on a page without reload the page
 Event handling and Form validations

K. L. Narayana 1
JAVAScript
2) Difference between client side and server side scripting:
Client Side Scripting Server Side Scripting
It runs on client machine i.e. web browser It runs on web server
Source code is visible to users Source code is not visible to users
Response from a client-side script is faster becasue the Response from a server-side script is slower
scripts are processed on the local computer. because the scripts are processed on the remote
computer.
Create control event procedures Access server resources such as databases and hide
business logic implementation
It is used for dynamic related functions. It is used for database specific functions
Examples: Javascript, VB script, Examples: PHP, JSP, ASP, ASP.Net, Ruby, Perl
ECMA(European Computer Manufacturers and many more.
Association) Script etc.

3) Difference Between Javascript and Java


JavaScript and Java are similar in some ways but fundamentally different in others. The JavaScript language
resembles Java but does not have Java's static typing and strong type checking.

JAVASCRIPT JAVA
JavaScript code run on browser only. Java creates application that can run in a virtual
machine or browser.
Local: JavaScript is embedded into Remote: Java Applet code is form a remote system.
downloaded HTML documents.
Interpreted: Interpreted by the client-side Compiled: Compiled on the server before executed on
computer. the client machine.
Object–Based: Uses built–in, extensible Object–oriented: Supports all features of OOPS.
objects, but no classes or inheritance. Applets consist of object classes with inheritance.
Loosely Typed: Variable can hold any type Strongly Typed: Variables can hold only one type of
of value. value.
JavaScript is text based dynamic and weakly Java is high-level, static,compiled and strongly typed
typed language. language.
Javascript source code visible to user. Java Applet code is not visible to user.

4) Include Scripts in an HTML Document


You can include any scripting language in a Web page within the <script>..</script> tags.

This tag can be used one or multiple times in the <head> as well as in the <body> element. Because HTML
pages are read sequentially, a lot of scripting code may appear in the head section of a document. All Java
Script functions should be written in head tag.

Attributes of Script

LANGUAGE:
It specifies the scripting language of the script. Possible values are JavaScript and VbScript.

SRC:
This attribute is used to indicate the URL of a file that contains an external script to load. Possible value is
URL. Specifies the location of an external script (Ex: .JS file).

TYPE:
Indicates the MIME type of the script to run. Possible value is text/JavaScript and text/VbScript.

2 K. L. Narayana
JAVAScript
MIME Types:
MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet
according to their nature and format. It consists of a type and a subtype, two strings, separated by a '/'.
Type Description Example of typical subtypes
Represents any document that contains text text/plain, text/html, text/css, text/javascript
Text
and is theoretically human readable
Represents any kind of images. Videos are not image/gif, image/png, image/jpeg,
Image included, though animated images (like animated image/bmp
gif) are described with an image type.
audio/midi, audio/mpeg, audio/webm,
Audio Represents any kind of audio files
audio/wav
Video Represents any kind of video files video/webm, video/ogg
application Represents any kind of binary data. application/pdf, application/xml,

Example1.html
<html> <head> <title>JAVASCRIPT Tutorials </title>
<SCRIPT>document.write("<h3>This is my first JavaScript Program</h3>")</SCRIPT>
</head><BODY>
<script>
document.write("<font color=red size=5> Welcome to the Web Designing </font>")
window.alert("Welcome to the World of Interactive Scripting")
</script></BODY></html>
Output:

5) Javascript as a Programming Language

Identifiers
An identifier in JavaScript is a name used to refer to a variable or function name. The first character must be
an alphabet (lowercase or uppercase) or an underscore (_). Subsequent characters may be any number of
alpha numeric or an underscore. Special character are not allowed except dollar sign $

Variables:
The value associated with a name need not be constant; new values may be assigned to existing names.
Since the value associated with a name may vary, the names are called variables.

For example, the following line of JavaScript assigns the value 2 to a variable named i.
i = 2;

And the following line adds 3 to i and assigns the result to a new variable sum:
sum = i + 3;

K. L. Narayana 3
JAVAScript
Variable Declaration
Declaring a variable type is not required, but it is good programming style to declare variables before
using them.

Example: var i; var sum, principal;

And you can combine variable declaration with initial assignment to the variable:
var i = 2;

Untyped Variables
Variables in JavaScript can hold values of any data type, so it is known as untyped variables.

For example, it is perfectly legal in JavaScript to assign a number to a variable and later assign a string to it:
x = 10;
x = "KLN"; // JavaScript allows the same variable to contain different types of data values.

Data Types
 Primitive data types
 Number: integer & floating-point numbers
 Boolean: logical values “true” or “false”
 String: a sequence of alphanumeric characters
 Composite data types (or Complex data types)
 Object: a named collection of data
 Array: a sequence of values
 Special data types
 null: an initial value is assigned
 undefined: the variable has been created but not yet assigned any value

Numbers
Numeric literals can be integer or floating-point, and integers can be expressed in decimal, octal, or
hexadecimal notation. All numbers in JavaScript are represented as floating-point values.

Integer literals
Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A leading 0 (zero)
on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal.

For Example: 29, 2912, 056, 0xFFF, and –345.

Floating–Point Literals
Floating–point can have the following parts: an integer, a decimal point ("."), a fraction (another decimal
number), an exponent part ("e" or "E") followed by an integer, which can be signed ("+" or "–"). A floating–
point literal must have at least one digit, plus either a decimal point or "e" (or "E").

For Example: 3.1415, –3.1E12, .1e12, and 2E–12

Boolean Literals
 A Boolean value is a logical value of either true or false.
 Often used in decision making and data comparison.

For Example: true, false

4 K. L. Narayana
JAVAScript
JavaScript operators:
 Assignment operators
 Arithmetic operators
 Comparison operators
 Bitwise operators
 Logical operators
 String operators
 Conditional (ternary) operator
 Comma operator
 Unary operators
 Relational operator
 Type of Operator

Arithmetic and Mathematical Opertions


JavaScript programs work with numbers using the arithmetic operators : + for addition, - for subtraction,
* for multiplication, and / for division.

In addition to these basic arithmetic operations, JavaScript supports more complex mathematical operations
through a large number of mathematical functions with Math object, so we use always use the literal name
Math to access them.

Example2:
<html> <BODY><script>
r=120; var a=Math.sin(r)
x=4; y=3; b = Math.sqrt(x*x + y*y);
document.write("<h2>Value of a = " + a +
"</h2>")
document.write("<h1>Value of b = " + b +
"</h1>")
</script></BODY></html>

+ Concatenate Operator
The + operator concatenates two strings. That is, it creates a new string that consists of the first string
followed by the second. Thus, for example, the following expression evaluates to the string "hello there":
"hello" + " " + "there". In javascript string can be kept in single or double quotes.

Example3:
<html> <BODY> <script>
a = "Engineering"; c=" "; b="College";
x = a + c + b; // here x value is "Engineering
College"
document.write("<font color=red size=6>" + x)
</script></BODY></html>

Strict comparison Operators (=== and !==)


In strict equality the objects being compared must have the same type and same value:
 Two strings are strictly equal when they have the same sequence of characters, same length, and
same characters in corresponding positions.
 Two numbers are strictly equal when they are numerically equal (have the same number value).
 Two Boolean operands are strictly equal if both are true or both are false.
 Two objects are strictly equal if they refer to the same Object.

K. L. Narayana 5
JAVAScript
Example4:
<html> <body> <script>
a=25; b="25"
x="BBSR"; y='BBSR'
z="BBS"
document.write("<font color=red size=6>")
document.write(" a==b " + (a==b) + "<p>")
document.write(" a===b " + (a===b) + "<p>")
document.write(" x==y " + (x==y) + "<p>")
document.write(" x===y " + (x===y) + "<br>")
document.write(" x===z " + (x===z) + "<br>")
</script> </body> </html>

The typeof Operator


It is a unary operator that is placed before any type of operand. The value of the typeof operator is a string
indicating the data type of the operand.

Possible values are "number", "string", "boolean", "object", "function", and "undefined" for undefined
values. Both arrays and objects return the "object" value.

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string,
variable, keyword, or object for which the type is to be returned.
var myFun = new Function("5+2") // typeof(myFun) is object
var shape="circle" // typeof shape is string
var size=1 // typeof(size) is number
var today=new Date() // typeof today is object
var BPUT; // typeof BPUT is undefined

For property values, the typeof operator returns the type of value the property contains:
typeof document.lastModified is string
typeof window.length is number

For methods and functions, the typeof operator returns results as follows:
typeof eval is function
typeof parseInt is function

Object Creation Operator (new)


The new operator is used to create object and array values of JavaScript programs.

Syntax:
new constructor

Example uses of the new operator are:


d = new Date();
var dob= new Date(2018,11,25)

The new operator works as follows: first, it creates a new object with no properties defined. Next, it invokes
the specified constructor function, passing the specified arguments, and passing the newly created object as
the value of the this keyword.

6 K. L. Narayana
JAVAScript
Null
The JavaScript keyword null is a special value that indicates "no value." Technically speaking, null is a
value of object type, so when a variable holds the value null, you know that it does not contain a valid object
or array. Null refers to “nothing”. You can declare and define a variable as “null” if you want absolutely
nothing in it.

For Example
var branch=null

Undefined
There is another special value occasionally used by JavaScript. This is the "undefined" value returned when
you use a variable that doesn't exist, or a variable that has been declared, but never had a value assigned to it.
There is no undefined keyword for the undefined value. The undefined value is not the same as null.

An “undefined” value is returned when you attempt to use a variable that has not been defined or you have
declared but you forgot to provide with a value.

Example5.html
<html><body> <script language="javascript"> Output:
var str = "29.12"; num = parseInt(str)
fnum = parseFloat(str)
College=null
document.write("<font size=5>str " + str + " is of type " + typeof(str))
document.write ("<br>num " + num + " is of type " + typeof(num))
document.write ("<br>fnum " + fnum + " is of type " + typeof(fnum))
document.write ("<br> parseInt is of type " + typeof(parseInt));
document.write ("<br> Date is of type " + typeof(new Date()));
document.write ("<br> BPUT is " + typeof(BPUT));
document.write ("<br> College is " + typeof(College));
document.write ("<br> Value of College is " + College);
</script></body></html>

The if Statement
The if statement is the "control statement" that allows to "make decisions," or to execute statements
conditionally.

This statement has two forms.


if (expression)
statement

In the first form, the expression is true, then statement is executed. If the expression is false, then statement
is not executed.

if (expression)
statement1
else
statement2

In the second form of the statement, the expression is evaluated, and if it is true, then statement1 is executed;
otherwise statement2 is executed.
K. L. Narayana 7
JAVAScript
The switch statement
Allows you to merge several evaluation tests of the same variable into a single block of statements.

Example6.html
<html> <script language="JavaScript">
var chr;
chr = prompt("Pls enter any character.");
switch(chr)
{ case 'a' : case 'e' : case 'i' : case 'o' : case 'u' : alert("Vowel"); break;
case 'A' : case 'E' : case 'I' : case 'O' : case 'U' : alert("Vowel"); break;
default : alert("CONSONANT");
}
</script> </html>

Output:

The while Statement


The while statement is the basic statement that allows JavaScript to perform repetitive actions. In the while
statement first, the expression is evaluated. If it is false, JavaScript moves on to the next statement in the
program. If it is true, then statement is executed, and expression is evaluated again.

Syntax:
while (Expression)
{ statements;
counter increment/decrement;
}

The Do–While Loop


 The do/while loop always executes statements in the loop in the first iteration of the loop.
 The termination condition expression is placed at the bottom of the loop.

Syntax:
do
{ statements;
counter increment/decrement;
} while (termination condition)

The for Statement


The initialization, the test, and the update are the three crucial manipulations of a loop variable, and the for
statement combines these three and makes them an explicit part of the loop syntax.

For example:
for(i = 0, j = 10 ; i < 10 ; i++, j--)
sum += i * j;
8 K. L. Narayana
JAVAScript
Example7.html
<html> <body> <h1> Enter your Date of Birth </h1> Output:
<table><tr> <th><font size=3>Date of Birth: </font>
<th><Select name=Date>
<option>DD<script>
for(i=1; i<=31;i++)
document.write("<option>" + i);
</script>
<th><Select name=Month><option>MM<script>
for(i=1; i<=12;i++)
document.write("<option>" + i);
</script><th><Select
name=Year><option>YYYY<script>
for(i=1901; i<=2020;i++)
document.write("<option>" + i);
</script> </table> </body> </html>

The for...in Statement


This statement is a somewhat different kind of loop with the following syntax:

syntax:
for (variable in object)
statement

The variable should be the name of a variable, or should be an element of an array or a property of an
object.

The for..in statement provides a way to loop through the properties of an object. The body of the for..in loop
is executed once for each property of object. Before the body of the loop is executed, the name of one of the
object's properties is assigned to variable, as a string. Within the body of the loop, you can use this variable
to look up the value of the object's property with the [ ] operator.

Example8.html
<html> <script language="JavaScript">
var book=" ";
var booklist = new Array("Chinese", "English", "Japaneese");
for (var counter in booklist) {
book += booklist[counter] + " ";
}
alert(book); </script> </html>

with statement
The with statement establishes the default object for a set of statements.

syntax:
with (object)
statement

The above with statement specifies that the Math object is the default object. The statements following the
with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript
assumes the Math object for these references.

K. L. Narayana 9
JAVAScript
Example9:
<html> <body> <script> Output:
var a, x, y, z, r=5
with(Math)
{ a=PI * r * r
x=pow(r,2)
y=sqrt(x); z=max(x,y);
}
document.write("<font color=red size=6> Area = "
+a)
document.write("<p> x = " + x)
document.write("<p> y = " + y)
document.write("<p> Max Value = " + z)
</script> </body> </html>

Similarly, instead of calling document.write() over and over again in a JavaScript program, you could use a
with(document) statement, and then invoke write() simply.

Example10:
<html> Output:
<body> <script>
with(document)
{ write("<font size=5>" + "Welcome to JAVAScript by KLN")
write("<p>" + "Design the Interactive Web Pages...")
write("<p>" + "By using HTML5, CSS3, XML, AJAX and Php")
}
document.write("<p>Besto of Luck")
</script>
</body> </html>

6) Functions
A function is a piece of code that is defined once in a program and can be executed many times by the
program. JavaScript functions can be passed arguments or parameters that specify the value or values that
the function is to operate upon, and can return values. Functions in JavaScript are closely integrated with
JavaScript objects.

Defining and Invoking Functions


The functions are defined with the function keyword, followed by:
 the name of the function
 a comma-separated list of argument names in parentheses
 the JavaScript statements that comprise the body of the function, contained within curly braces

Function syntax:
function funcname ([arg1 [,arg2 [..., argn]]])
{
statements //Function Body
}

return
When the return statement is executed, the expression is evaluated, and returned as the value of the function.
The return statement can be used to return a value like this:

10 K. L. Narayana
JAVAScript
Syntax:
function square(x)
{ return x*x;
}
The return statement may also be used without an expression to simply terminate execution of the function
without returning a value. It is a syntax error to use the return statement anywhere except in a function body.

Recursive Function
function factorial(x)
{ if (x <= 1)
return 1;
else
return x * factorial(x-1);
}

Function Call Operator


The () operator is used to invoke functions in JavaScript. Once a function is defined, you can invoke it by
following the function's name with a comma-separated list of arguments within parentheses. The following
line is a function invocation:

y = square(x);
Since JavaScript is an untyped language, you are not expected to specify a data type for function arguments.

Example11:
<!-- Generally Function defined in head --> Output:
<html> <head> <script>
function fact(num)
{ var f=1;
for(i=num; i>0; i--)
f = f *i;
document.write("<h2>Factorial of " + num + " = " + f)
}
</script> </head> <body> <script>
fact(5); fact(8)
</script> </body> </html>

Example12:
<!-- Generally Function defined in head --> Output:
<html> <head> <script>
function factorial(x)
{ if (x ==0)
return 1;
else
return x * factorial(x-1);
}
</script> </head> <body> <script>
var x=4, y=6
document.write("<h2>Factorial of " + x + " = " +
factorial(x)); z=factorial(y);
document.write("<h2>Factorial of " + y + " = " + z)
</script> </body> </html>

K. L. Narayana 11
JAVAScript
7) Built-in Functions
JavaScript provides several built-in functions for manipulating string and numeric values:
 parseInt converts a string to an integer of the specified radix (base), if possible.
 parseFloat converts a string to a floating–point number, if possible.
 eval attempts to evaluate a string representing any JavaScript literals or variables, converting it to a number.

Example13.html (Calculaor Example)


<html><head><title>Arithmetic Operation </title> <script language="JavaScript" >

function add()
{ document.fr1.output.value=parseInt(fr1.inputA.value)+parseInt(fr1.inputB.value);
}

function sub()
{ document.fr1.output.value= parseInt(fr1.inputA.value)-parseInt(fr1.inputB.value);
}

</script> </head><body bgcolor=cyan text=maroon>


<div align=center><h1> Different Calculations of Two Numbers</h1>
<form name=fr1> <table border=0>
<tr><td>Enter Number1<td><input type=text name=inputA value="0" >
<tr><td>Enter Number2<td><input type=text name=inputB value="0" >
<tr><td>The Result is ::::<td><input type=text name=output>
</table><br> <input type=button value="+" onClick=add()>
<input type=button value="–" onClick=sub()> </form></div> </body></html>
Output:

Example14.html (Evaluation of expressions by using Built–In eval Function)


<HTML> <HEAD> <TITLE>The Evaluation of Expression.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function doIt(form)
{
form.output.value = eval(form.text1.value)
form.text1.focus()
form.text1.select()
}
</SCRIPT> </HEAD> <BODY BGCOLOR="white">
<H1>The Evaluation of Arithmetic Expression</H1><HR>
<FORM><P>Enter an expression to evaluate:<BR>
<INPUT TYPE="text" NAME="text1" size=30>
<INPUT TYPE="button" VALUE="Evaluate" onClick="doIt(form)">
&nbsp;&nbsp;&nbsp;
<input type="reset" name="B2" value="Reset"><p>
Results:<BR><input type=text NAME="output" >
</FORM> </BODY></HTML>
12 K. L. Narayana
JAVAScript
Output:

8) Three Dialog Boxes


There are three Basic User Interaction methods of JavaScript from window object.

The first one is:


window.alert()
As you can see, whatever you put inside the quotation marks, it will display it.

The second one is:


window.confirm()
Confirm is used to confirm a user about certain action, and decides between two choices depending on what
the user chooses.

var x=window.confirm("Are you sure you are ok?")


if (x)
window.alert("Good!")
else
window.alert("Too bad")

Here the var x will get the result, namely, "true" or "false". Then we use a "if else" statement to give the
script the ability to choose between two paths, depending on its value.

The third one is:


window.prompt()

Prompt is used to allow a user to enter something, and do something with that info:
var n=window.prompt("please enter your name")

window.alert(n)

The prompt will store whatever the user typed in the prompt box, using n. Then display it.

Example15.html
<html> <body bgcolor=cyan><div align=center>
<h3>Window Properties alert, confirm, and prompt </h3>
<div align=center> <form>
<input type="Button" value="Ok Button" onclick="window.alert('Welcome to KLN JAVAScript')" >
<input type="Button" value="Ok & Cancel Button"
onclick="window.confirm('Are you want more Examples')" >
<input type="Button" value="Input Value" onclick="window.prompt('Enter your Gmail-ID :: ')">
</form> </div>
</body></html>
K. L. Narayana 13
JAVAScript
Output:

9) Object Hieratchy

Objects
An object is a data type that contains named pieces of data. An Object in context of JavaScript, can be
defined as collection of methods and properties consisting of a set of definable characteristics that one can
view or modify.

Every object is unique in some way. Three important facets of an object are what it looks like, how it
behaves, and how scripts control it. Those three facets are Properties, Methods and Event Handlers.

Properties
Every object has properties. To access a property, use the object name followed by a period and the property
name. Any physical object you hold in your hand has a collection of characteristics that defines it’s each of
those features is called a property.

Button object assigns three property values:


<input type=”button” name=”clicker” value=”Hit Me…..”>

To gain access to an object’s property, you use the hierarchical dot syntax scheme.
Document.formName.clicker.name
Document.formName.clicker.value

14 K. L. Narayana
JAVAScript
Methods
Object’s methods are called functions and its data are called its properties.

For Example:
Doucmnet.write(“Welcome to JAVA Script”);

10) Array Object


JavaScript does not have an explicit array data type. However, you can use the built–in Array object and its
methods to work with arrays in your applications. An array is a collection of data values. While each data
value contained in an object has a name, each data value in an array has a number, or index. Because
JavaScript is an untyped language, an element of an array may be of any type. Array elements may even
contain other arrays, which allows you to create data structures that are arrays of arrays.

Creating an Arrays
There is a predefined Array() constructor function that you can use to create arrays. You can use this
constructor in three distinct ways. The first is to call it with no arguments:
var a = new Array();

This method creates an empty array with no elements. It is like calling new Object(), except that it gives the
newly created object (i.e., an array) a length property set to 0.

The second technique is to call the Array() constructor with a specified length:
a = new Array(10);

The final technique allows you to specify values for the first n elements of an array:
a = new Array(56, "Ram Kumar", 78);

In this form, the constructor is passed two or more arguments. Each argument specifies an element value and
may be of any type. Elements are assigned to the array starting with element 0. The length property of the
array is set to the number of arguments that were passed to the constructor.

Array Length Property


arr1 = new Array(); // arr1.length == 0 (no elements defined)
arr2 = new Array(10); // arr2.length == 10 (empty elements 0-9 defined)
arr3 = new Array(1,2,3); // arr3.length == 3 (elements 0-2 defined)
arr4[5] = -1; // arr4.length == 6 (elements 0,1,2, and 5 defined)
arr5[49] = 0; // arr5.length == 50 (elements 0,1,2,5, and 49 defined)

Methods of an Array
concat Joins two arrays and returns a new array.
join Joins all elements of an array into a String.
pop Removes the last elements from an array and returns that element.
push Ads one or more elements to the end of an array and returns that last element added.
reverse Transposes the elements of an array: the first array element becomes the last and the last
becomes the first.
shift Removes the first element from an array and returns that element.
slice Extracts a section of an array and returns a new array.
splice Adds and/or remives elements form an array.
sort Sorts the elements of an array.
tostring Returns a string representing the specified object.
unshift Adds one or more elements to the front of an array and returns the new length of the array.

K. L. Narayana 15
JAVAScript
Array Methods
The Array.join() method converts all the elements of the array to a string, and concatenates them,
separating them with an optionally specified string passed as an argument to the method. If no separator
string is specified, then a comma is used. For example, the following lines of code produce the string
"1,2,3":

a = new Array(1,2,3); // Create a new array with these three elements.


s = a.join(); // s == "1,2,3"

And the following lines specify the optional separator to produce a slightly different result:
a = new Array(1,2,3);

s = a.join(", "); // s == "1, 2, 3". Note the space after the comma.

The Array.reverse() method reverses the order of the elements of an array. It does this "in place"--i.e., it
doesn't create a new array with the elements rearranged, but instead rearranges them in the already existing
array. For example, the following code, which uses the reverse() and the join() methods, produces the string
"3,2,1":

a = new Array(1,2,3); // a[0] = 1; a[1] = 2; a[2] = 3;


a.reverse(); // now a[0] = 3; a[1] = 2; a[2] = 1;
s = a.join() // s = "3,2,1"

The Array.sort() method, which sorts the elements of an array. Like the reverse() method, it does this "in
place". When sort() is called with no arguments, it sorts the array elements in alphabetical order (temporarily
converting them to strings, to perform the comparison, if necessary):

a = new Array("banana", "cherry", "apple");


a.sort();
s = a.join(", "); // s == "apple, banana, cherry".

Example16.html Sort the Names of 5 students


<html> <h3>Sort the Names of 5 Students</h3>
<body> <script>
names = new Array(5);
for(i=0; i<5; i++)
names[i]=window.prompt("Enter the Student Name :: ")
document.write("<h2> Original Names :: " + names + "</h2>");
names.sort(); //Sort the names
document.write("<h2> Sorted Names :: " + names + "</h2>");
str=names.join(", "); //joins the elements of an array and stored in the str
document.write("<Font size=5 color=red>" + str);
</script> </body></html>

Output:

16 K. L. Narayana
JAVAScript
Example17: Stack using Array
<html> <script>
function Stack()
{ this.stac=new Array();
this.pop=function()
{ return this.stac.pop();
}
this.push=function(item)
{ this.stac.push(item);
}
}
var stack=new Stack();
stack.push("Atul"); stack.push("Amit"); stack.push("Suraj");
stack.push("Ankita"); stack.push("Anaya"); stack.push("Nayan");
alert("Thank You " + stack.pop());
alert("Thank You " + stack.pop());
alert("Thank You " + stack.pop());
alert("Thank You " + stack.pop());
</script> </html>

11) Multidimensional Arrays


A JavaScript multidimensional array is an array of arrays, or, in other words, an array whose elements
consist of arrays. We demonstrate with the following multidimensional array:
var ar = [
['apple', 'orange', 'pear'],
['carrots', 'beans', 'peas'],
['LHC', 'GAL', 'OCT', 'ATTR']
];

How to Access Elements of a Multidimensional Array


To access elements of the nested arrays, use square brackets as the following demonstrates:
alert( ar[2][1] ); // GAL

The first square bracket references the desired element in the outer array. The second square bracket
references the desired element in the inner array. JavaScript array indexes start at zero.

Adding and Removing Elements in Multidimensional Arrays


You can use square bracket notation to add elements to the inner arrays. The following demonstrates adding
a new element at the end of the first sub-array, with console.log used to display the result:
ar[0][3] = 'banana'; //assigning the element at [0][3]

document.write(ar[0]); // ["apple", "orange", "pear", "banana"]

You can apply array methods to the nested arrays. Here we use the push method to add two new elements to
the second sub-array:
ar[2].push(“TIFAC”, “CORE”);

document.write(ar[2]); // ['LHC', 'GAL', 'OCT', 'ATTR', “TIFAC”, “CORE”]


You can also use array methods to remove elements from sub-arrays, as we demonstrate here with the pop
method:
ar[1].pop(); // remove last element from 2nd sub-array
alert( ar[1] ); // carrots, beans, peas
K. L. Narayana 17
JAVAScript
Example18: Multi Dimensional Array
<html> <head> <title>Multi Dimenstional Array</title></head> <body> <script>
var ar=[ ['apple', 'orange', 'pear'], ['carrots', 'beans', 'peas', "grapes", "mango"], ['LHC', 'GAL', 'OCT'] ];
ar[0][3]='banana';
document.write("<font size=6>" + ar[1]);
ar[2].push('ATTR', "TIFAC", "CORE");
ar[1].pop(); // remove last element from 2nd sub-array
document.write("<p>" + ar[2] + "<p>");
for (var i=0, len=ar.length; i<len; i++) {
// inner loop applies to sub-arrays
for (var j=0, len2=ar[i].length; j<len2; j++) {
// accesses each element of each sub-array in turn
document.write("<font color=red size=5>" + ar[i][j] + "\t");
}
document.write("<br>");
}
</script> </body></html>
Output:

Example19: Array of Student Rcords


<html> <head> <title>Multi Dimenstional Array</title></head>
<body> <script>
var student=[ [45, 'Ram Kumar', 98.5], [105, "Deepak Pandey", 87.5], [89, "RAJ Malhotra", 92.4] ];
for (var i=0, len=student.length; i<len; i++)
document.write("<font color=red size=5>" + student[i] + "<br>");
</script> </body> </html>
Output:

12) Document Object


The document object is one of the most important objects of JavaScript. The document object holds the real
content of the page. Properties and methods of the document object generally affect the look and content of
the document that occupies the window.

Document Object
Properties alinkColor, applet, area, bgColor, cookie, domain, fgColor, form, forms, Image,
lastModified, linkColor, Link, title, URL, vlinkColor.
Methods close, open, write, writeln.

Document.title Property:
Not every property about a document is set in a <body> tag attribute. If you assign a title to the page in the
<title> tag set within the head portion, that title text is reflected by the document.title property.

18 K. L. Narayana
JAVAScript
Document.write( ) Method:
The document.write( ) method can be used in both immediate scripts to create content in a page as it loads
and in deferred scripts that create new content in the same or different window. The method requires one
string parameter, which is the HTML content to write to the window or frame. Such string parameters can be
variables or any other expressions that evaluate to a string. Very often, the content being written includes
HTML tags.

Example20.html
<html> <head><title>This is an example of Java Script page</title> </head>
<body bgcolor=cyan text=red><h2>Welcome to the JavaScript course!</h2>
<script language="JavaScript">
var a=document.bgColor
var b=document.lastModified
var c=document.fgColor
document.write("<h1><small>Your Course Instructor is</small> Mr. KLN </h1>")
document.write("<h4>Background colour of the Browser : "+a)
document.write("<br>Last modified date of the Document : "+b)
document.write("<br>Foreground colour of the Browser : "+c)
</script> </body></html>
Output:

13) Navigator Object


The navigator object provides information about the browser such as version and type and other browser
specific information that helps your JavaScript code determine what browser is actually executing your
code.

Properties of Navigator Object:


appVersion Contains the version information of the browser.
appName Contains the name of the Browser.
appCodeName Reflects the code name of the current browser represented as a string.
userAgent Contains the browser’s user–agent header for a server.
mimeType An array of all MIME types currently supported by the browser.
javaEnabled Returns a Boolean value (true or false) indicating if java is enabled or disabled.

Example21.html
<html> <script>
document.write("<font size=5 color=red>",navigator.appName, "</font><br>")
document.write(navigator.appCodeName, "<br>")
document.write(navigator.appVersion, "<br>")
document.write(navigator.javaEnabled(), "<br>")
</script> </html>
Output:

K. L. Narayana 19
JAVAScript
14) String Object
JavaScript does not have a string data type. However, you can use the String object to work with strings.

Syntax: stringObjectName = new String(string)

For Example:
instructor = new String("Lakshmi Narayana")
var coll="National Institute of Science & Technology"

Properties and methods of String Object:


Operator +
Properties Length
anchor, big, blink, bold, fixed, fontcolor, italics, small, strike, sub, sup, charAt,
Methods
indexOf, lastIndexOf, link, split, substring, toLowerCase, toUpperCase

Operators:
The “+” operator will concatenate the two strings.
var msg1 = "Hello"; var msg2 = "World"
var msg = msg1 + " " + msg2 //msg="Hello World"

length property:
var len = “Hell World”.length //len=10

String Methods
charAt(position):
The charAt method returns the character at the specified position in string.
var x=“mango”.charAt(1) //x=“a”

indexOf(Str [, startIndex]):
Returns the index of the first occurrence of the search string (Str).
var y=“banana”.indexOf(“a”) //x=1
var y=“banana”.indexOf(“a”,2) //x=3

lastIndexOf(Str [, startIndex]):
Returns the index of the last occurrence of the search string (Str).
var y=“banana”.lastindexOf(“a”) //x=5
var y=“banana”.indexOf(“a”,2) //x=3

substr(start [, len]):
Returns a substring within a string .
var str1=“Kolkata”.substr(0,4) //str1=“Kolk”

substring(sart, end):
The substring method takes two arguments and returns a subset of the string between the two arguments.
var str1="Kolkata".substring(2,5) //str1="lka"

toUpperCase():
var upstr =“hello”.toUpperCase() // upstr=“HELLO”

toLowerCase():
var lowstr =“HELLO”.toLowerCase() // lowstr=“hello”

20 K. L. Narayana
JAVAScript
Example22.html (Lower case to uppercase Convesion Program)
<html> <head><title>Lower case to uppercase Convesion Program</title> <script>
function upper()
{ document.converter.input.value=document.converter.input.value.toUpperCase()
}
</script> </head><body bgcolor=slate text=cyan>
<h2 align=center> Enter Lower case Letters for Conversion to Uppercase
<form name=converter><br>Enter name in Lowercase :
<input type=text name=input value=" " size=50 onChange="upper()"> </h2>
<font color=red size=5> After Entering Your Name Press TAB </font> </form></body></html>

Example23.html
<html><body><script>
var name="K. Lakshmi Narayana"
document.write("<p>" + name.bold())
document.write("<p>" + name.italics())
document.write("<p>" + name.strike())
</script></body></html>

Example24.html (Number Convesion Table)


<html><head><title>Number Conversion Table</title></head> Output:
<BODY> <h2>Numbers in Different Formats</h2>
<HR size=5 color=red> <TABLE border=2
bordercolor=maroon>
<TR> <TH>Decimal <TH>Octal <TH>Hexadecimal
<TH>Binary
<SCRIPT language=JavaScript>
var content = " "
for(var i = 115; i <= 127; i++)
{ content += "<TR><TD>" + i.toString(10)
content += "<TD>" + i.toString(8)
content += "<TD>" + i.toString(16)
content += "<TD></font>" + i.toString(2)
}
document.write(content)
</SCRIPT> </TABLE>
</BODY></HTML>

15) Math Object


The built–in Math object has properties and methods for mathematical constants and functions. For example,
the Math object's PI property has the value of pi (3.141...), which you would use in an application as
Math.pi

Properies of Math
Name Description
E Returns the mathematical constant E, the base of natural logarithms, approximately 2.718.
LOG10E Returns the base 10 logarithm of E (approximately equal to 0.434).
LOG2E Returns the base 2 logarithm of E (approximately equal to 1.442).
PI Returns the ratio of the circumference of a circle to its diameter ( approximately 3.14159).
SQRT1_2 Returns the square root of 1/2 i.e. 0.5, approximately 0.707.
SQRT2 Returns the square root of 2 (approximately 1.414).

K. L. Narayana 21
JAVAScript
Methods of Math
Method Description
abs Absolute value
sin, cos, tan Standard trigonometric functions; argument in radians
acos, asin, atan Inverse trigonometric functions; return values in radians
exp, log Exponential and natural logarithm, base e
ceil Returns least integer greater than or equal to argument
floor Returns greatest integer less than or equal to argument
min, max Returns greater or lesser (respectively) of two arguments
pow Exponential; first argument is base, second is exponent
round Rounds argument to nearest integer
sqrt Square root

16) Date Object


JavaScript does not have a date data type. However, you can use the Date object and its methods to work
with dates and times in your applications. It stores the date as the number of milliseconds since January 1,
1970, 00:00:00.

How to Create a Date Object


dateObjectName = new Date([parameters])

where dateObjectName is the name of the Date object being created; it can be a new object or a property of
an existing object.

i) new Date(). [for example today = new Date() ].


ii) new Date(milliseconds). [for example inauguration_day = new Date("September 19, 1997 10:05:00") ].
iii) new Date(dateString). [for example marr_day = new Date(2003,1,1) ].

Date get Methods


Method Description
getDate() Get the day as a number (1-31)
getMonth() Get the month (0-11)
getFullYear() Get the four digit year (yyyy)
getDay() Get the weekday as a number (0-6)
getHours() Get the hour (0-23)
getMinutes() Get the minutes (0-59)
getSeconds() Get the seconds (0-59)

Date set Methods


Method Description
setDate(date) Sets the day of the month as the date. Ex: setDate(25)
setMonth() Sets the month of the year as the month. Ex: setMonth(11)
setFullYear() Sets the calendar year as the year. Ex: setFullYear(2020)
setHours() Sets the number of elapsed hours in the day as the hour
setMinutes() Sets the number of elapsed minutes in an hour as the minutes.
setSeconds() Sets the number of elapsed seconds in a minute as the seconds.

22 K. L. Narayana
JAVAScript
Example25.html (Display the date in dd/mm/yyyy format)
<html><script>
var today_date= new Date()
var myyear=today_date.getFullYear()
var mymonth=today_date.getMonth()+1
var mytoday=today_date.getDate()
document.write(" <font color=red size=6>Today is Christmas : ")
document.write(+mytoday+"/"+mymonth+"/"+myyear+"</font>")
document.write("<h1>Wish You have a Good Luck and Bright Feature.<h1>")
document.write("<h3>Default Date Format is: "+today_date+"</h3>")
</script></html>
Output:

Example26: Digital Clock


<html> <head> <script>
function startTime()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = "<font color=red size=7>"+ h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}

function checkTime(i)
{
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script> </head>
<body onload="startTime()">
<div id="txt"></div>
</body></html>
Output:

17) Window Object


The window object is the "parent" for all other objects. You can create multiple windows in JavaScript
application.

Window Object Properties:


closed, status , document , Frame , frames , history , length , location , name, opener ,
Properties
parent.

K. L. Narayana 23
JAVAScript
Window Object Methods:
 Open( ) and close( ): Opens and closes a browser window; you can specify the size of the window, its
content, and whether it has a button bar, location field, and other "chrome" attributes.
 alert( ): Displays an Alert dialog box with a message.
 confirm( ): Displays a Confirm dialog box with OK and Cancel buttons.
 prompt( ): Displays a Prompt dialog box with a text field for entering a value.
 blur( ): Removes focus from a window.
 focus( ): Gives focus to a window.
 setTimeout( ): Evaluates an expression after the specified time.
 print( ): Prints the contents of the window.
 resizeBy( ): Resizes an entire eindow by moing the window’s bottom–right corner by the specified amount.

Syntax:
resizeBy(horizontal, vertical)
Horizontal: The number of pixels by which to resize the window horizontally.
Vertical: The number of pixels by which to resize the window vertically.

To make the current window 5 pixels narrow and 10 pixels taller than its curent dimensions, use this statement:
self.resizeBy(–5, 10) // Relativ ePositioning

You can refer to the properties, methods, and event handlers of the current window or another window (if
the other window is named) using any of the following methods:
 self or current window: self and window are synonyms for the current window, and you can use
them optionally to refer to the current window.
 top or parent: top and parent are also synonyms that you can use in place of the window name. top
refers to the topmost Navigator window, and parent refers to a window containing a frameset.
 name of a window variable: The window variable is the variable specified when a window is
opened. For example, msgWindow.close() closes a window called msgWindow.

Opening a new window using JavaScript


To open a window, simply use the open() method. (window.open())
window.open("URL")

For example
<input type="button" value="Click here" onClick="window.open('www.nist.edu')">

You can also include the name and attributes to the open() method.
open("URL","name","attributes")

The complete list of attributes you can add:


Width Height toolbar
Location Directories status
scrollbars Resizable Menubar

For example to open a new Window


<form> <input type="button" value="Click here to see"
onclick="window.open('page2.htm', 'win1','width=200,height=200,menubar,scrollbars,status')" >
</form>

24 K. L. Narayana
JAVAScript
Example27.html
<HTML><HEAD><TITLE> Prize Winners </TITLE>
<SCRIPT>
var bGrounds=new Array("Green","red","Blue","Yellow","Lime");
var thisBG=0;
var bgColorCount=5;
function rotateBG()
{ if(document.images)
{ thisBG++;
if(thisBG == bgColorCount)
thisBG=0;
document.bgColor=bGrounds[thisBG];
setTimeout("rotateBG()", 700);
}
}
</SCRIPT> </HEAD> <BODY BGCOLOR="blue" onLoad="rotateBG()">
<div align=center><font color=maroon size=7>Congratulations!!!!!!!!!! <br>
<font color=yellow size=6>You Won the Scholarship. . . . . <br>
<!Assume that in the parent directory we have a images directory on that car.jpg is available>
<img src="../images/flag.jpg"> </div> <font color=red size=7 face=impact>
<marquee behavior=alternate>nist.edu</marquee> </font>
</BODY></HTML>
Output

Example28.html
<html><body><form> <font color=red size=6> bput.ac.in Registration Form. . .</font>
<p><big>Enter your E–mail ID :</big> &nbsp;&nbsp;&nbsp;<input type="text"> </p>
<p><big>Enter your password : &nbsp;&nbsp;&nbsp;</big>
<input type="password" name="My Password" size="20" maxlenngth="15"></p>
<p align=center> <input type=button value=LOGIN onclick="window.open('Example24.html')">
&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value=CANCEL>
</form></body></html>
Output:

Window.status property
The window bar at the bottom of the browser window normally displays the URL of link when you roll the
mouse pointer on it. Here we can display the status of the window.

K. L. Narayana 25
JAVAScript
Example29.html
<html><head><script>
function showStatus(msg)
{ window.status = msg
return true
}
</SCRIPT></HEAD><BODY>
<h1> Move your mouse pointer on the below Links and saw the status BAR </h1>
<a href="www.yahoo.com" onMouseOut="return showStatus('chating with yahoo')">
yahoo mail</a> &nbsp;&nbsp;&nbsp;&nbsp;
<A HREF="www.nist.edu" onMouseOver = "return showStatus('nist.edu')"
onMouseOut="return showStatus('Thank you for visiting our Web Site')">
NIST Website</a> </body></html>
Output:

Example30.html Load the page in the same Window


<html><head> <script language="JScript">
function reWrite()
{ var newcontent= "<HTML><BODY bgcolor=cyan><h1>"
newcontent +="<marquee behavior=alternate>lakshmi.edu</marquee></h1>"
newcontent +="<br><font color=red size=6>Developed by K. Lakshmi Narayana </font>"
newcontent += "<h3> Associate Professor, Dept. of CSE"
newcontent +="</body></html>"
document.write(newcontent);
document.close();
}
</script></head><body>
<div align=center><h1> Example of docuemnt.write on the Same Window
<form><input type=button value="Replace Content" onClick=reWrite()>
</form></div></body></html>
Output:

Example31.html Load a page in the Different window by using open() and close() Methods
<html><head> <script>
var newWindow
function makeWindow()
{ newWindow = window.open("","","status, height=200,width=400")
}
function reWrite()
{ if(newWindow.closed)
{ makeWindow();
}
26 K. L. Narayana
JAVAScript
var newcontent= "<HTML><BODY bgcolor=cyan><h1>Wish You have a Good Luck!"
newcontent +="<h3>It's from Lakshmi Narayana K. "
newcontent +="</body></html>"
newWindow.document.write(newcontent);
newWindow.document.close();
}
</script></head><body onLoad=makeWindow()><div align=center>
<h1> Example of docuemnt.write on Another Window </h1>
<form><input type=button value="Replace Content" onClick=reWrite()>
</div></form></body></html>
Output:

Example32.html Open a new HTML page in a new window by using open() and close() Methods
<html><head>
<script>
var newwindow
function windowopen( )
{ newwindow = window.open("Example24.html","new", "HEIGHT=350, WIDTH=400")
}
function windowclose( )
{ newwindow.close()
}
</SCRIPT>
</HEAD><BODY>
<FORM><font color=red size=6> Web Designing Tutorials. . . . .
<br> HTML, JavaScript, and FlashMx. . . . . </font>
<div align=right>
<INPUT TYPE="Button" onClick="windowopen()" value=" OPEN Tutorials " ><br>
<INPUT TYPE="Button" onClick="windowclose()" value="CLOSE Tutorials"></div>
</font> </form></body></html>
Output:

K. L. Narayana 27
JAVAScript
18) Event Handlers
Events are actions that take place in a document, usually as the result of user activity. Script code could be
added to HTML documents through special attributes called event handlers.

Examples of events include a user clicking a button, presenting a key, moving a window, or even simply
moving the mouse around the screen.

For example:
onClick="alert('hello!')"

JavaScript Event Handlers


OBJECT SUPPORTED EVENT HANDLERS
Area onClick()[1] onMouseOut() onMouseOver()
Button onBlur()[2] onClick() onFocus()[2]
Checkbox onBlur()[2] onClick() onFocus()[2]
FileUpload onBlur() onChange() onFocus()
Form onReset() onSubmit()
Frame onLoad() onUnload()
Image onAbort() onError() onLoad()
Link onClick() onMouseOut() onMouseOver()
Radio onBlur()[2] onClick() onFocus()[2]
Reset onBlur()[2] onClick() onFocus()[2]
Select onBlur()[2] onChange() onFocus()[2]
Submit onBlur()[2] onClick() onFocus()[2]
Text onBlur() onChange() onFocus()
Textarea onBlur() onChange() onFocus()
Window onBlur() onError() onFocus() onLoad() onUnload()

Event Handlers as Functions


Specifying an event handler as a string within an appropriate HTML tag defines a JavaScript function that is
invoked by the browser when the appropriate event occurs.

onClick Event handler


Any event handlers are added inside html tags, not inside <script></script>. The onClick handlers
execute something only when users click on form buttons, check boxes, etc, or text links, therefore they can
only be inserted in these tags.

Example:
<HTML><BODY>
<P> Click on the button below. </P>
<FORM NAME="frm1">
<INPUT TYPE="Button" NAME="cmdClickMe" VALUE="ClickMe" onClick="ClickMe()">
</FORM> <SCRIPT>
function ClickMe()
{ alert("A simple example of Button action. onClick Events")
}
</SCRIPT> </BODY></HTML>
28 K. L. Narayana
JAVAScript
Example:
<HTML><form name="go">
Light Blue<input type="checkbox" name="C1" onclick="document.bgColor='lightblue'">
Yellow<input type="checkbox" name="C2" onclick="document.bgColor='yellow'">
Light Green<input type="checkbox" name="C3" onclick="document.bgColor='lightgreen'">
</form> </html>

onLoad Event handlers


The onload event handler is used to call the execution of JavaScript after a page /frameset /image has
completely loaded. It is added like this:

<body onload="inform()"> //Execution of code will begin after the page has loaded.
<frameset onload="inform()"> //Execution of code will begin after current frame has loaded.
<img src="whatever.gif" onload="inform()"> //Execution begin after the image has loaded.

Example
<html> <head><title>Body onload example</title></head>
<body onload="alert(‘Hello students welcome to Java Script Class by KLN’)">
<font color=red face=impact size=6> Welcome to my Java Script pages </font>
</body> </html>

onUnload
onunload executes JavaScript immediately after someone leaves the page. A common use (though not that
great) is to thank someone as that person leaves your page for coming and visiting.

Example
<body onunload="alert('Thank you. Please come back to this site and visit again, ok?')">

Event handler return values:


Event handles are functions, which are associated with events. Similar to other functions, event–handling
functions can also return some value to the statement which invoked it.

Example33.html:
<html> <head>
<font color=red size=5> Click the below link to visit My Web Designing Examples. </font>
<br><br><br><script>
num=0
function handler()
{ return confirm("Are you sure you want to visit Web Designing Examples. . . ")
}
</script> </head> <body>
<a href="../webtutorials.html" onClick='return handler()'> Web Designing Examples </a>
</body></html>

Output:

K. L. Narayana 29
JAVAScript
19) FORM OBJECT
Each form in a document creates a Form object. A document can contain more than one form, Form objects
are stored in an array called forms as the first forms[0], the second forms[1], and so on. In addition to
referring to each form by name, you can refer to the first form in a document as document.forms[0]

Likewise, the elements in a form, such as text fields, radio buttons, and so on, are stored in an elements
array. So you could refer to the first element of the first form as document.forms[0].elements[0]

FORMS AND FORM ELEMENTS:


A form object can be referenced either by its position in the array of forms contained by a document or by
name. A form is contained by a document, and it in turn contains any number of elements.

CREATING FORM:
Forms are created by using the <form> tag. You can set attributes for Form.

Form Attributes/Properties:
action, name, target, method, elements[]

Form Elements:
Text object, Button object, Checkbox object, Radio object, Select object, Textarea object, Buttoon object

Accessing a Form:
document.forms[0] or document.formName

Accessing Form elements:


document.forms[0].elements[0] or document.forms[0].elementname or document.formaname.elementname

TEXT OBJECTS
Each of the four text–related HTML form elements– text, textarea, password, and hidden.

BUTTON OBJECT
There are three types of buttons, button submit and reset.

CHECKBOX OBJECT
The key property of a checkbox object is whether or not the box is checked. The checked property is a
Boolean value; true if the box is checked, false if not.

Example34.html
<html><head><title>check box example</title>
<script language="JScript" >
function inspect()
{ if(document.forms[0].checkThis.checked)
alert("You Can Collect Soft Copy of Web Designing from your instructors. . .");
else
alert("Fine. You take examples in Floppy form your respective computers!");
}
</script></head><body bgcolor=slate text=red>
<div align=center><h2>Are you want Soft copy of Web Designing Examples. . .</h2>
<br><br>
<form> <input type=checkbox name=checkThis >Soft Copy Wanted<br><br><br><br>
<input type=button value="Inspect Box" onClick=inspect()>
</div> </form></body></html>
30 K. L. Narayana
JAVAScript
Output:

20) RADIO OBJECT


You must assign the same name to each of the radio buttons in the group. You can have multiple groups
within a form, but each member of the same group must have the same name. The browser maintains an
array list of objects with the same name.

Example35.html (Passing “form data” to Functions)


<html><head><script language=JScript>
function processData(form1)
{ for(var i=0;i<form1.cooldrink.length;i++)
{ if(form1.cooldrink[i].checked)
break
}
var cool=form1.cooldrink[i].value
var pername=form1.pername.value
alert(" Thank You Mr. " + pername + " for choosing "+ cool +" ...................");
}
</script></head><body text=navy> <h1>Please Order for any of the Cool Drink. </h1>
<form name=form1><h4>Enter your Name : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type=text name=pername size=40><br><br><br>
Choose Your Favourate Cooldrink <br>
<br><input type=radio name=cooldrink value="COKE" checked> Coke<br>
<input type=radio name=cooldrink value="PEPSI" > Pepsi<br>
<input type=radio name=cooldrink value="FANTA" > Fanta<br>
<input type=radio name=cooldrink value="LIMCA" > Limca<br>
<input type =button value="Take any Drink" onClick=processData(this.form)>
</form></body></html>
Output:

21) SELECT OBJECT


The selected object is really a compound object; the object that contains an array of option objects.
Moreover the object can be established in HTML to display itself as a pop–up list or a scrolling list, the
latter configurable to accept multiple selections by users. The most important property of the selected object
itself is the selectedIndex property, accessed as follows:
Document.form[0].selectName.selectedIndex

K. L. Narayana 31
JAVAScript
Two important properties of an option item are text and value, accessed as follow:
Document.form[0].selectName.options[n].text
Document.form[0].selectName.options[n].value

The text property is the string that appears on screen in the selected object, the text is defined outside of the
<option> tag. But inside the <option> tag you can set a VALUE attribute, which like the radio buttons
shown earlier. This value is the index number of the item that is currently selected.

Example36.html
<html>
<head><script language=JScript>
function goThere()
{ var list = document.formselect.branch
var location = list.options[list.selectedIndex].text
alert("You have choosen a " + location +" Branch ")
}
</script></head>
<body> <form name=formselect><h3>
Choose Your Branch :: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<select name=branch onChange=goThere()>
<option selected value=CSE>Computer Science Engineering
<option value=IT>Information Technology
<option value=ECE>Electronics & Communication Engineering
<option value=ECE>Electrical & Electronics Engineering
<option value=ECE>Civil Engineering
<option value=ECE>Mechanical Engineering
</select> </form></body></html>
Output:

22) Validations in Form by Using Javascript


Let’s first define what is meant by validating forms. Well, using JavaScript, you can check what a user
enters into a form, intercept a form from being submitted and ask the user to retype or fill in the unfilled
entries of a form before submission.

Example37.html Email Validation:


<html>
<body align="center" text=green font= arial>
<form target="" onsubmit=""> <h1> Enter email id :</h1>
<input type="text" id='chkemailid'>
<input type="button" name="submit" value="validate email id" onclick="validateEmail()">
</form>
<script>
function validateEmail()
{
try{
emailField = document.getElementById('chkemailid');

32 K. L. Narayana
JAVAScript

var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address'); return false;
}
else
{
alert('Thank you for entereing Valid Email...'); return true;
}
}
catch(Exception) { alert(Exception.message) }
}
</script> </body> </html>
Output:

Example38.html Password Validation:


<html> <head>
<script type="text/javascript">
function validation()
{ var a = document.form.pass.value;
k=0;
if(a=="")
{ alert("Please Enter Your Password");
document.form.pass.focus(); return false;
}

if ((a.length < 6) || (a.length > 10))


{ alert("Your Password must be 6 to 10 Character");
document.form.pass.select(); return false;
}
count=0;
for(i=0;i<=a.length;i++)
{
if(a.charAt(i)>="A" && a.charAt(i)<="Z" )
count=count+2;
}
if(count==0)
{ alert("your paasword must contain one upper case");
document.form.pass.focus();
return false;
}
count=0;
for(i=0;i<=a.length;i++)
{ if(a.charAt(i)>="0" && a.charAt(i)<="9" )
count=count+2;
}
K. L. Narayana 33
JAVAScript
if(count==0)
{
alert("your paasword must contain one digit");
document.form.pass.focus();
return false;
}
count=0;
for(i=0;i<=a.length;i++)
{
if(a.charAt(i)=="!" || a.charAt(i)=="@" || a.charAt(i)=="#" || a.charAt(i)=="$" ||
a.charAt(i)=="%" ||
a.charAt(i)=="^" || a.charAt(i)=="&" ||a.charAt(i)=="*" ||a.charAt(i)=="_" )
count=count+2;
}
if(count==0)
{ alert("your paasword must contain one special character");
document.form.pass.focus(); return false;
}
}
</script> </head>
<body>
<form name="form" method="post" onsubmit="return validation()">
<table>
<tr> <td> Passsword: <td><input type="password" name="pass"">
*(6-10 chars, atleast 1- Uppercase alphabet, 1-digit, 1-special symbol)
<tr> <td> <td>
<input type="submit" name="sub" value="Submit"> &nbsp; <input type=reset>
</table></form> </body> </html>
Output:

Example39.html: Enter all the Text Fields without leaving empty which are compulsory
<HTML>
<HEAD><TITLE>Elements Array</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function verifyIt()
{ var form = document.forms[0]
for (i = 0; i < form.elements.length; i++)
{ if (form.elements[i].type == "text" && form.elements[i].value == "")
{ alert("Please fill out all fields.")
form.elements[i].focus()
return false;
}
}
alert("Thank You for Filling the Form");
}
</SCRIPT>
</HEAD>
34 K. L. Narayana
JAVAScript
<BODY bgcolor=cyan text=navy> <h2> Enter Your Details</h2>
<FORM><table cellspcing=5><tr><td>Enter your first name <td>
<INPUT TYPE="text" NAME="firstName" onKeyReleased=verifyIt()>
<tr><td>Enter your last name <td> <INPUT TYPE="text" NAME="lastName">
<tr><td>Enter Your Gender<td>
<INPUT TYPE="radio" NAME="gender" checked>Male &nbsp;&nbsp;&nbsp;&nbsp;
<INPUT TYPE="radio" NAME="gender">Female
<tr><td>Enter your Email–ID<td><INPUT TYPE="text" NAME="email">
<tr><td>Enter your Place of Birth <td><INPUT TYPE="text" NAME="city"></table>
</FORM><CENTER><FORM>
<INPUT TYPE="button" NAME="act" VALUE="Verify" onClick="verifyIt()">
</FORM></CENTER> </BODY></HTML>
Output:

Example40.html: Accept only digits


<HTML><HEAD><TITLE>Letting Only Numbers Pass to a Form Field</TITLE>
<SCRIPT language=JavaScript>
function checkIt(evt)
{ var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode < 48 || charCode > 57)
{ status = "This field accepts numbers only."
return false
}
status = ""
return true
}
</SCRIPT> </HEAD>
<BODY> <font color=red face=arial size=4>Take Only Numbers from the Text field
<HR size=5 color=navy> <FORM onsubmit="return false">
Enter Your Expected Annual Salary: &nbsp;&nbsp;&nbsp;
<INPUT onkeypress="return checkIt(event)" name=numeric
onChange='alert("Thank you we will intimate after One WEEK!!!!!!")'> &nbsp;Rs.
</FORM> <br>After entering the Numbers Press TAB
</BODY></HTML>
Output:

K. L. Narayana 35
JAVAScript
HOW TO Enable JAVAScript in Google Chrome.....
1) first seelct the settings of the chrome.

2) Then go to bottom of the page you will find Advanced

3) click on the advanced you will get Privacy and Security and click on Content Settings

36 K. L. Narayana
JAVAScript

4) click on javascript

5) you will get one new window you can set Allowed for javascript.

K. L. Narayana 37
JAVAScript
HOW Enable DEBUGGER of JAVAScript in Google Chrome
Generally we required the debugger when the output is not coming.
1) Press the F12 function key in the Chrome browser to launch the JavaScript debugger.

2) click on sources and and clikc on the page.

you will get the ERROR at line number 3 print is not a function

3) Open the source code of the javascript file and modify the code.
<html> <body> <script>
var x=10
document.print("Value of x = " + x);
</script> </body></html>

4) Now you can Run it.


38 K. L. Narayana
JAVAScript
External JavaScript file
We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files
into a single file. It increases the speed of the webpage.

Let’s create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.

message.js
function msg()
{
alert("Hello welcome to KLN JAVAScript Classes...");
}

Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.

index.html
<html>
<head>
<script type="text/javascript" src="message.js"> </script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form> </body> </html>

Output:

K. L. Narayana 39

You might also like