0% found this document useful (0 votes)
11 views75 pages

JavaScript Basics for Web Development

Uploaded by

griya6232
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views75 pages

JavaScript Basics for Web Development

Uploaded by

griya6232
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 1: PH 602.

5 [E1] Web Development With AngularJS , NodeJS 1

Chapter :: Using JavaScript in an HTML Page


=====================================
Introduction
 JavaScript is an Object-oriented \ Object based Computer Programming
Language.
 It is an Interpreted programming or script language from Netscape.
 The scripting languages are easier and faster to code.
 Its first appearance was in Netscape 2.0 in 1995 with the name 'LiveScript'.

Features of JavaScript
 JavaScript is an open source scripting language.
 It is lightweight.
 It creates network-centric applications.
 It is platform independent.
 It validates form data.
 It reduces server load.

Advantages of JavaScript
 JavaScript saves server traffic.
 It performs the operations very fast.
 It is simple to learn and implement.
 It is versatile.
 JavaScript pages are executed on the client side.
 JavaScript extends its functionality to the web pages.

Disadvantages of JavaScript
 JavaScript cannot be used for networking applications.
 It doesn't have any multithreading or multiprocessor capabilities.
 It has security issues being a client-side scripting language.

What is a script?
 Script is a small, embedded program.
 The most popular scripting languages on the web are, JavaScript or VBScript.
 HTML does not have scripting capability, you need to use <script> tag.
 The <script> tag is used to generate a script.
 The </script> tag indicates the end of the script or program.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 2

Example : Type attribute

<script type = “text/javascript”>


[Link](“AIMIT – ST ALOYSIUS COLLEGE”);
</script>

The 'type' attribute indicates which script language you are using with the type attribute.

Example : Language attribute

<script language= “javascript”>


[Link](“AIMIT – ST ALOYSIUS COLLEGE”);
</script>

You can also specify the <script language> using the 'language' attribute.

Uses of Client-Side Scripting

 Client-Side Scripting is an important part of the Dynamic HTML (DHTML).


 JavaScript is the main client-side scripting language for the web.
 The scripts are interpreted by the browser.
 Client-Side scripting is used to make changes in the web page after they arrive at
the browser.
 It is useful for making the pages a bit more interesting and user-friendly.
 It provides useful gadgets such as calculators, clocks etc.
 It enables interaction within a web page.
 It is affected by the processing speed of the user's computer.

Operation of Client-Side Scripting

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 3

Integrating Java Scripts in Html:


JavaScript statements can be easily embedded in any HTML document by enclosing the
statements between an opening <SCRIPT> and closing </SCRIPT> tag.
Syntax:

<SCRIPT LANGUAGE=”JAVASCRIPT”>
-------Javascript statements-----
</SCRIPT>

The script tag can be placed either in the head or the body of the HTML document. But it
is preferred to place the script tag in the head of the document to ensure that all
JavaScript definitions have been made before the body of the document is displayed.

Consider the following sample code which displays “ This is my first java script
program” in the browser.

</HTML>

<BODY>

<SCRIPT
LANGUAGE="JAVASCRIPT">

[Link]("This is my first
java script program")

</SCRIPT>

</BODY>
</HTML>
Hiding Scripts using Comment tags:
All browsers do not support JavaScript. Older browsers, such as Netscape Navigator 1,
Internet Explorer 2 do not recognize the </SCRIPT> tag and as a consequence, display as
text all the JavaScript statements between <SCRIPT> and </SCRIPT> .
In order to prevent this, you can have the JavaScript statements surrounded by
HTML comment tags ( <!-- and - -> ). These comment tags cause the JavaScript
statements to be treated as comments by browsers, which do not support JavaScript.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 4

The use of HTML comment tag is as follows:


<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!- -
[Link]("This is my first java script program")
-->
</SCRIPT>
</BODY>
</HTML>

<NOSCRIPT>and </NOSCRIPT> tag:

Browsers that do not support JavaScript to use this tag will display HTML
enclosed within a <NOSCRIPT> tag in plain text. Browsers that support JavaScript
ignore the code within this tag.

The following example shows the use of <NOSCRIPT> tag

<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!- -
[Link]("This is my first java script program")
-->
</SCRIPT>
<NOSCRIPT>
<B> upgrade to java enabled browser </B>
</NOSCRIPT>

</BODY>
</HTML>

JavaScript Entities:
JavaScript entities allow the value of an HTML attribute to be provided by a JavaScript
expression. This allows the attribute values to be dynamically calculated during the
loading of a page. JavaScript entities have to be used in the following manner

&{ Expression };
where expression is the JavaScript expression to be evaluated.

Note:
Microsoft Internet Explorer does not support JavaScript Entities.
Eg:
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 5

<html>
<head> <script language=”javascript”>
col=”red”
</script>
</head>
<body>
<h1 color=”&col”>this text will be displayed in red color</h1>
</body>
</html>

The <script> tags “SRC” attribute

The script tag provides an alternative way for including the JavaScript code in an HTML
document using the “SRC” attribute, which may be used to specify a file containing the
JavaScript statements.

Example:
<html>
<head>
</head>
<body>
<script language=”javascript” src=”[Link]”>

</script></body>
</html>
In the above example “[Link]” is the file containing JavaScript statements as shown
below
---------------------------------------[Link]------------------------------
[Link](“THIS TEXT IS DISPLAYED FROM THE FILE [Link]”)

Rules for writing the JavaScript code


 Script should be placed inside the <script> tag.
 A semicolon at the end of each statement is optional.
 The single line comment is just two slashes (//) and multiple line comment starts
with /* and ends with */.
 Use '[Link]' for writing a string into HTML document.
 JavaScript is case sensitive.
 You can insert special characters with backslash (\& or \$).

==============================================================

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 6

CHAPTER : Basics of JavaScript


Variables:
Variables are used to store values. Variable names are case sensitive.
Variable names can begin with an uppercase letter(A—Z),lowercase letters (a—z) ,an
underscore character(_), or dollat sign character($). The remaining character can
consists of letters, the underscore character , the dollar sign character , or digits (0—
9)
Examples for valid variable names:

OrderNumber
Name
$Rs
Rs_$

Data Types:
JavaScript supports four primitive types of values and supports complex types, such
as arrays and objects.
The four primitive types are:
1. Number
Consists of integers and floating point numbers and a special NaN (not a
number) value.
2. Boolean
Consists of the logical values true and false
3. String
Consists of string values that are enclosed in single or double quotes.
[Link]
Consists of a single value , undefined , which is used to indicate that a variable
has not been assigned a value.

Operators:
The set of operators that JavaScript uses is very similar to c,c++ programming
languages. The operators can be classified as bellow:

 Assignment
 Comparision
 Arithmetic
 BitWise
 Logical
 String
 Special

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 7

Arithmetic operators:

Operator Meaning Example Result


+,- Unary Positive, +500 500
Negative -100 -100

+ Addition 5+10 15

- Subtraction 5 – 10 -5
* Multiplication 5 * 10 15

/ Division 22 / 7 3.14159
% Modulus 5 mod 2 1
++ Increment operator
-- Decrement operator

The Remainder Operator / modulus operator( %).


This operator finds the remainder when one number is divided by another.
Example:
[Link](6%8)
[Link](7%8)
[Link](8%8)
[Link](9%8)
[Link](10%8)

This statement would display the values:


6
7
0
1
2

Increment and Decrement operators( ++ , --):


The operator ++ adds 1 to its operand, and –- subtracts one, in otherwords
x=x+1;
is same as ++x;
and
x=x-1;
is same as x--;
Both the increment and decrement operators may either precede (prefix) or follow
(postfix) the operand. For example,
x=x+1; can be written
++x or x++
There is , however, a difference between the prefix and postfix forms when you use these
operators in an expression. When an increment or decrement operator precedes its
operand, the increment and decrement operation is performed before obtaining the value
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 8

of the operand for use in the expression. If the operator follows its operand, the value of
the operand is obtained before incrementing or decrementing it.
For example
x=10;
y= ++x;
sets y to 11. However if you write the code as
x=10;
y=x++;
y is set to 10. Either way, x is set to 11.

Relational Operators

The Relational operators are used to construct a relational expression.


The complete set of JavaScript relational operators are given in the following table.
Operator Comparison Example Meaning
== Equal to X==Y Is X equal to Y?
> Greater than X>Y Is X Greater than Y?
< Less tan X<Y Is X less than Y?
>= Greater than OR Equal to X>=Y Is X Greater than or equal to Y?
<= Less than Or Equal to X<=Y Is X less than Y?
!= Not Equals X != Y Is X not equal to Y?

Logical /comparison Operators

Logical operators are used to combine one or more relational expressions. They compare
two relational expressions and return true or false value based on the result of the
comparison.
The following table lists the commonly used Logical operators to construct a logical
expression.
For Example: ( X < 10) and (Y > 10)

Operator Example Result after Evaluation


&& X && Y true if both X and Y are
true; false Otherwise
|| X || Y true X or Y , or both of
them, are true; false only if
both X and Y are false.
! !X true if X is false, false if X
is true.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 9

Bitwise Operators
Bitwise operators can be applied only to char and int data types. You cannot use bitwise
operators on float, double, long double, void, Boolean, or other, more complex types.

Operator Action
& AND
| OR
^ XOR
~ NOT (one’s complement)
>> Shift right
<< Shift left
>>> Unsigned right shift
Bitwise Operators

Operation on bits
Following are the operations used commonly in JavaScript on bits
1) AND (&&)
Input 1 Input 2 Result
Example:
0 0 0
1.) k=3 && 0 result : k=0
0 1 0
1 0 0
2.) i=1,j=1;
1 1 1
k=I && j result k=1
And truth table
3.) i=5, j=-14;
k=I && j; result k=1; Input 1 Input 2 Result
0 0 0
2) OR ( || ) 0 1 1
1 0 1
Example: 1 1 1
1.) k=3 || 0 result : k=1 OR truth table

2.) i=1,j=1;
k=I || j result k=0

3.) i=5, j=-14;


k=I || j; result k=1;

Left shift operator ( << )


This operator shifts the bits of a binary number to the left side and adds 0 to the
right side.
Example: int I =17, k; i=10001
K=i<<3; i<<3= 10001000
Result k=136.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 10

Right shift operator ( >>)


This operator shifts the bits of a binary number to the right side. Thus the shifted
bits are lost from the number.
Example: int I =17, k i=10001
K=i>>3 i>.3= 100
Result k=4.

Unsigned Right Shift(>>>)


The binary representation of operand x is shifted y bits to the right. Left most bits will be
discarded.
Eg:
The expression 25 >>>2 implies 11001 has to be shifted 2 bits to the right –110 which is
6.

JavaScript Control and Looping Structure

1. If Statement
 IF statement is a conditional branching statement.
 In 'IF' statement, if the condition is true a group of statement is executed. And if
the condition is false, the following statement is skipped.

Syntax : If statement

if(condition)
{
//Statement 1;
//Statement 2;
}

Example : Simple Program for IF Statement

<html>
<body>
<script type="text/javascript">
var num = prompt("Enter Number");
if (num > 0)
{
alert("Given number is Positive!!!");
}
</script>
</body>
</html>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 11

Output:

2. If – Else Statement
 If – Else is a two-way decision statement.
 It is used to make decisions and execute statements conditionally.

Flow Diagram of If – Else Statement

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 12

Syntax : If-Else statement

if (condition)
{
//Statement 1;
}
else if(condition)
{
//Statement 2;
}
else
{
//Statement 3;
}

Example : Simple Program for If-Else Statement

<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find Odd or Even");
no = parseInt(no);
if (isNaN(no))
{
alert("Please Enter a Number");
}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 13

Output:

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 14

3. Switch Statement
 Switch is used to perform different actions on different conditions.
 It is used to compare the same expression to several different values.

Flow Diagram of Switch Statement

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 15

Syntax

switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
case condition 3:
//Statements;
break;
.
.
case condition n:
//Statements;
break;
default:
//Statement;
}

Example : Simple Program for Switch Statement

<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");
switch (day)
{
case (day="1"):
[Link]("Sunday");
break;
case (day="2"):
[Link]("Monday");
break;
case (day="3"):
[Link]("Tuesday");
break;
case (day="4"):
[Link]("Wednesday");
break;
case (day="5"):
[Link]("Thursday");
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 16

break;
case (day="6"):
[Link]("Friday");
break;
case (day="7"):
[Link]("Saturday");
break;
default:
[Link]("Invalid Weekday");
break;
}
</script>
</head>
</html>

Output:

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 17

4. For Loop
 For loop is a compact form of looping.

It includes three important parts:


1. Loop Initialization
2. Test Condition
3. Iteration

 All these three parts come in a single line separated by semicolons(;).

Flow Diagram of 'For' Loop

Syntax

for(initialization; test-condition; increment/decrement)


{
//Statements;
}

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 18

Example : Palindrome Program using For Loop

<html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = [Link]("strr").value;
var i = [Link];
for(var j=i; j>=0; j--)
{
revstr = revstr+[Link](j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}
</script>
<form>
Enter a String or Number: <input type="text" id="strr"
name="checkpalindrome"><br>
<input type="submit" value="Check" onclick="palindrome();">
</form>
</body>
</html>

Output:

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 19

5. For-in Loop
 For-in loop is used to traverse all the properties of an object.
 It is designed for looping through arrays.

Syntax

for (variable_name in Object)


{
//Statements;
}

6. While Loop
 While loop is an entry-controlled loop statement.
 It is the most basic loop in JavaScript.
 It executes a statement repeatedly as long as expression is true.
 Once the expression becomes false, the loop terminates.

Flow Diagram of While Loop

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 20

Syntax

while (condition)
{
//Statements;
}

Example : Fibonacci Series Program using While Loop

<html>
<body>
<script type="text/javascript">
var no1=0,no2=1,no3=0;
[Link]("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
[Link](no3+"<br>");
}
</script>
</body>
</html>

Output:

7. Do-While Loop
 Do-While loop is an exit-controlled loop statement.
 Similar to the While loop, the only difference is condition will be checked at the
end of the loop.
 The loop is executed at least once, even if the condition is false.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 21

Flow Diagram of Do – While

Syntax

do
{
//Statements;
}
while(condition);

Example : Simple Program on Do-While Loop

<html>
<body>
<script type ="text/javascript">
var i = 0;
do
{
[Link](i+"<br>")
i++;
}
while (i <= 5)
</script>
</body>
</html>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 22

Output:
0
1
2
3
4
5

Difference between While Loop and Do – While Loop

While Loop Do – While Loop


In while loop, first it checks the condition In Do – While loop, first it executes the
and then executes the program. program and then checks the condition.
It is an entry – controlled loop. It is an exit – controlled loop.
The condition will come before the body. The condition will come after the body.
If the condition is false, then it terminates It runs at least once, even though the
the loop. conditional is false.
It is a counter-controlled loop. It is a iterative control loop.

8. Break Statement
 Break statement is used to jump out of a loop.
 It is used to exit a loop early, breaking out of the enclosing curly braces.

Syntax:
break;

Flow Diagram of Break Statement

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 23

9. Continue Statement
 Continue statement causes the loop to continue with the next iteration.
 It skips the remaining code block.

Flow Diagram of Continue Statement

Syntax:
continue;

=======================================================

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 24

Chapter :: Predefined JavaScript Objects:


Java Scripts Supports Following Predefined Objects:

1. The Array Object


2. The String Object
3. The Date Object
4. The Boolean Object
5 The Math Object
6 The DOM Form Object
7 The Window Object
8 The DOM Form Object

1. The Array Object:


An Array is a data structure used to store a set of values. Each element of an array can
be referenced using an index.
Array Declaration
Every array has to be declared before it is used. Array object can be declared in any
one of the following manner
1)
Arrayname = new Array(arraylength)
2)
Arrayname = new Array()

Aaraylength is the length of an array, which denotes the number of elements that can
be stored in the array. The first element of an array has an index 0, the next element
has an index 1 and so on.

Eg:
To store names of five students the array can be declared as follows:
Student = new Array(5)

To display the third element of the student array

[Link](Stuent[2])

In many cases arrays are initialized after declaration, however, it is


possible to initialize an array during declaration. Such arrays are known as “dense
arrays”. It is done as follows:

Days = new Array(“Mon’,’Tue’,’wed’,’thu’,’fri’,’sat’,’sun’)


Here the new operator is used for allocating memory to an object.
Note:

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 25

Javascript does not impose any restrictions on the type of elements stored in an
array. you can store an integer, string, Boolean value and also an array object as
elements of an array.
For example consider the following
myArray = new Array( 1, “India”, 3.55, 4)
the length of myArray is 10 and it has the following statements,
myArray[0]=1
myArray[1]=”India”
myArray[2]=3.55
myArray[3]=4

the length property:


Syntax:
[Link]
The method length of an array object returns the size of an array.

length The length property is used to determine the length of an array

myArray = new Array( 1, 2, 3, 4, 5, 6)

The Array Object provides the following methods:

toString() Converts an array to a string. The array elements are separated by


commas.

E.g:
[Link]([Link]())
This Stmt will display the output as:
1,2,3,4,5,6

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 26

Join(separator) Joins array element together but separated by the separator string.
The function returns the output as a string
E.g
[Link]([Link](“-“))
This Stmt will display the output as:
1-2-3-4-5-6

Sort() Sorts the contents of an array based upon the ascii value of each
character.
e.g
arr=new Array(1,2,3,10)
[Link]([Link]())
This Stmt will display the output as:
1,10,2,3

reverse() Reverse the contents of the array. The last element becomes first and
the first element becomes the last.
E.g
[Link]([Link]())
This Stmt will display the output as:
6,5,4,3,2,1
pop() It removes the last element from an array and returns that element.
It adds one or more elements to the end of an array and returns the
push()
new length of the array.

2. String Object:

String value
Alphanumeric data in JavaScript is known as “String”, which is one or more
characters enclosed within single or double quotes. If a string begins with single
quote then it has to end with a single quote. Similarly, if a string begins with double
quote it must end with a double quote.

Consider the following examples


S1=’ this is a sample string’
S2=”this is also a sample string”

The string object provides the following methods, which can be used to manipulate
any string

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 27

toLowerCase() Converts the entire string to lowercase

Eg:
Str = “ I Love India”
[Link]()
[Link](Str)  would displays the out put as
i love india

toUpperCase() Converts the entire string to uppercase


Eg:
Str = “ I Love India”
[Link]()
[Link](Str)  would displays the out put as
I LOVE INDIA

subString(index) Returns a substring from a string beginning at index.

Eg:
Str = “I Love India”
Temp= Str. substring (7)
[Link](Temp)  would displays the out put as
India

subString(index1,index2) Returns a substring from a string beginning at index1 and


ending at index2.

Eg:
Str = “I Love India”
Temp= Str. subString (0,6)
[Link](Temp)  would displays the out put as
I Love

Split(separator) Separates the entire string into an array of substrings


based upon the separator(de-limiter) character.

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

Eg:
Str = “I Love India”
Temp= Str. charAt (8)
[Link](Temp)  would displays the out put as
n

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 28

indexOf(pattern) Returns the index of first occurrence of the substring


considering the initial index at zero(0)
Eg:
Str = “I Love India”
Temp= Str. indexOf (“dia”)
[Link](Temp)  would displays the out put as
9

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 29

The Boolean Object

The Boolean object allows the creation of user defined Boolean values.
For example , you can declare the object mytrue to represent the Boolean true and
object myfalse to represent the Boolean false. It can be done in the following manner.

myTrue= new Boolean(true)


myFalse = new Boolean(false)

now you will be able to use the objects myTrue and MyFalse as Boolean true and
Boolean false respectively.

Consider the following program


<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
myTrue= new Boolean(true)
myFalse = new Boolean(false)
[Link](" mytrue = "+myTrue)
[Link](" <br> myFalse = "+myFalse)
[Link]("<br> mytrue+myFalse = "+(myFalse+myTrue))
</SCRIPT>
</BODY>
</HTML>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 30

The out put of the above program is given bellow.

The Date Object


The Date object provides methods to work with date and time. The Date object can be
constructed in one of the following ways.
Method 1:
Var = new Date()
Creates an instance of the date object and assigns the current date and time.

Method 2:
Var = new Date (year, month , day, hours, minutes, seconds, milliseconds)

Creates an instance of the date object with the date specified by the year, month, day,
hours, seconds, and milliseconds. The year and month parameters must be specified,
the other parameters are optional.
Note:
If the optional parameters are included, then they must specified in the given order.

The date object provides the following methods.

getDate() Returns the day of the month from the date object
getDay() Returns the day of the week from the date object, starting Monday as 1.
getMonth() Returns the month of the year from the date object. It returns ‘0’ for
January, ‘1’ for February so on and ‘11’ for December.
setMonth() Sets the month of the year for the date object.
getYear() Returns the year from the date object.
setYear() Sets the year for the date object.
getFullYear() Returns the year in four digit format from the date object.
setFullYear() Sets the year in four digit format for the date object.
getTime() Returns the time in milliseconds since midnight January 1 , 1970 from
the date object.
getHours() Return the hours, minutes and seconds from the date object.
getMinutes()
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 31

getSeconds()

setHours() Sets the hours, minutes and seconds for the date object.
setMinutes()
setSeconds()

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 32

Consider the following program which displays the system date and time.

<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
d=new Date()
[Link](" d= "+d)
[Link](" <br> [Link]()
"+[Link]())
[Link](" <br> [Link]()
"+[Link]())
[Link](" <br> [Link]()
"+[Link]())
[Link](" <br> [Link]()
"+[Link]())

</SCRIPT>
</BODY>
</HTML>

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 33

JavaScript DOM Form Object

1. Form Object
 Form object represents an HTML form.
 It is used to collect user input through elements like text fields, check box and
radio button, select option, text area, submit buttons and etc.

Syntax:
<form> . . . </form>

Form Object Properties

Property Description
Action It sets and returns the value of the action attribute in a form.
enctype It sets and returns the value of the enctype attribute in a form.
Length It returns the number of elements in a form.
It sets and returns the value of the method attribute in a form that is GET or
Method
POST.
Name It sets and returns the value of the name attribute in a form.
Target It sets and returns the value of the target attribute in a form.

Form Object Methods

Method Description
reset() It resets a form.
submit() It submits a form.

2. Hidden Object
 Hidden object represents a hidden input field in an HTML form and it is invisible
to the user.
 This object can be placed anywhere on the web page.
 It is used to send hidden form of data to a server.

Syntax:
<input type= “hidden”>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 34

Hidden Object Properties

Property Description
Name It sets and returns the value of the name attribute of the hidden input field.
Type It returns type of a form element.
Value It sets or returns the value of the value attribute of the hidden input field.

3. Password Object
 Password object represents a single-line password field in an HTML form.
 The content of a password field will be masked – appears as spots or asterisks in
the browser using password object.

Syntax:
<input type= “password”>

Password Object Properties

Property Description
defaultValue It sets or returns the default value of a password field.
It sets or returns the maximum number of characters allowed in a password
maxLength
filed.
Name It sets or returns the value of the name attribute of a password field.
readOnly It sets or returns whether a password fields is read only or not.
Size It sets or returns the width of a password field.
Value It sets or returns the value of the attribute of the password field.

Password Object Methods

Method Description
select() It selects the content of a password field.

4. Checkbox Object
 Check box object represents a checkbox in an HTML form.
 It allows the user to select one or more options from the available choices.

Syntax:
<input type= “checkbox”>

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 35

Checkbox Object Properties

Property Description
Name It sets or returns the name of the checkbox.
Type It returns the value “check”.
Value It sets or returns the value of the attribute of a checkbox.
checked It sets or returns the checked state of a checkbox.
defaultChecked It returns the default value of the checked attribute.

Checkbox Object Methods

Method Description
click() It sets the checked property.

5. Select Object
 Select object represents a dropdown list in an HTML form.
 It allows the user to select one or more options from the available choices.

Syntax:
<select> … </select>

Select Object Collections

Collection Description
options It returns a collection of all the options in a dropdown list.

Select Object Properties

Property Description
Length It returns the number of options in a dropdown list.
selectedIndex It sets or returns the index of the selected option in a dropdown list.
Type It returns a type of form element.
name It returns the name of the selection list.

Select Object Methods

Method Description
add() It adds an option to a dropdown list.
remove() It removes an option from a dropdown list.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 36

6. Option Object
 Option object represents an HTML <option> element.
 It is used to add items to a select element.

Syntax:
<option value> . . . </option>

Option Object Properties

Property Description
Index It sets or returns the index position of an option in a dropdown list.
Text It sets or returns the text of an option element.
defaultSelected It determines whether the option is selected by default.
Value It sets or returns the value to the server if the option was selected.
Prototype It is used to create additional properties.

Option Object Methods

Methods Description
blur() It removes the focus from the option.
focus() It gives the focus to the option.

Example : Simple Program on Option Object Method

<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = [Link];
var fav = [Link][a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
[Link]("Your Favorite Fruit is <b>"+fav+".</b>");
}
}
</script>
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 37

</head>
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select" onClick="optionfruit([Link]);">
</form>
</body>
</html>

Output:

Your Favorite Fruit is Mango.

7. Radio Object
Radio object represents a radio button in an HTML form.
Syntax:
<input type= “radio”>

Radio Object Properties

Property Description
Checked It sets or returns the checked state of a radio button.
defaultChecked Returns the default value of the checked attribute.
Name It sets or returns the value of the name attribute of a radio button.
Type It returns the type of element which is radio button.
Value It sets or returns the value of the radio button.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 38

Radio Object Methods

Method Description
blur() It takes the focus away from the radio button.
click() It acts as if the user clicked the button.
focus() It gives the focus to the radio button.

8. Text Object
Text object represents a single-line text input field in an HTML form.
Syntax:
<input type= “text”>

Text Object Properties

Property Description
Value It sets or returns the value of the text field.
defaultValue It sets or returns the default value of a text field.
Name It sets or returns the value of the name attribute of a text field.
maxLength It sets or returns the maximum number of characters allowed in a text field.
readOnly It sets or returns whether a text field is read-only or not.
Size It sets or returns the width of a text field.
Type It returns type of form element of a text field.

9. Textarea Object
Textarea object represents a text-area in an HTML form.

Syntax:
<textarea> . . . </textarea>

Textarea Object Properties

Property Description
Value It sets or returns the value of the text field.
defaultValue It sets or returns the default value of a text field.
Name It sets or returns the value of the name attribute of a text field.
Type It returns type of form element of a text field.
Rows It displays the number of rows in a text area.
Cols It displays the number of columns in a text area.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 39

The Document Object


For manipulating the document that is currently visible in the browser window

The document object represents your web [Link] you want to access any element in an
HTML page, you always start with accessing the document object.

Methods of document object

We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description
write("string") writes the given string on the doucment.
writes the given string on the doucment with newline
writeln("string")
character at the end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.

Adding and Deleting Elements

Method Description
[Link](element) Create an HTML element
[Link](element) Remove an HTML element
[Link](element) Add an HTML element
[Link](new, old) Replace an HTML element
[Link](text) Write into the HTML output stream

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 40

Example: To read paragraphs from an file


<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is the welcome message.</p>
<h2>Technology</h2>
<p id="second">This is the technology section.</p>
<script type="text/javascript">
var paragraphs = [Link]("p");
alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
[Link]("second").innerHTML = "The orginal message is
changed.";
</script>
</body>
</html>

JavaScript DOM Window Object


[Link] Object

 Window object is a top-level object in Client-Side JavaScript.


 Window object represents the browser's window.
 It represents an open window in a browser.
 It supports all browsers.
 The document object is a property of the window object. So, typing
[Link] is same as [Link].
 All global variables are properties and functions are methods of the window
object.
 window object open method
o Creates a window
o Three parameters—the URL of the page to open in the new window,
the name of the window, a string of comma-separated, all-lowercase
feature names, each followed by an = sign and either "yes" or "no" to
determine whether that feature should be displayed in the new
window
o If these parameters are omitted, the browser defaults to a new
window containing an empty page, no title and all features visible.

win1=open("[Link]","cal1","menubar=no, toolbar=yes");

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 41

Window Object Properties

Property Description
Document It returns the document object for the window (DOM).
Frames It returns an array of all the frames including iframes in the current window.
It returns the boolean value indicating whether a window has been closed or
Closed
not.
History It returns the history object for the window.
innerHeight It sets or returns the inner height of a window's content area.
innerWidth It sets or returns the inner width of a window's content area.
Length It returns the number of frames in a window.
Location It returns the location object for the window.
Name It sets or returns the name of a window.
Navigator It returns the navigator object for the window.
Opener It returns a reference to the window that created the window.
outerHeight It sets or returns the outer height of a window, including toolbars/scrollbars.
outerWidth It sets or returns the outer width of a window, including toolbars/scrollbars.
Parent It returns the parent window of the current window.
Screen It returns the screen object for the window.
Screen It returns the X coordinate of the window relative to the screen.
Screen It returns the Y coordinate of the window relative to the screen.
Self It returns the current window.
Status It sets the text in the status bar of a window.
Top It returns the topmost browser window that contains frames.

Window Object Method

Method Description
alert() It displays an alert box.
confirm() It displays a dialog box.
prompt() It displays a dialog box that prompts the visitor for input.
setInterval() It calls a function or evaluates an expression at specified intervals.
setTimeout() It evaluates an expression after a specified number of milliseconds.
clearInterval() It clears a timer specified by setInterval().
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 42

clearTimeOut() It clears a timer specified by setTimeout().


close() It closes the current window.
open() It opens a new browser window.
createPopup() It creates a pop-up window.
focus() It sets focus to the current window.
blurt() It removes focus from the current window.
moveBy() It moves a window relative to its current position.
moveTo() It moves a window to the specified position.
resizeBy() It resizes the window by the specified pixels.
resizeTo() It resizes the window to the specified width and height.
print() It prints the content of the current window.
scrollBy() It scrolls the content by the specified number of pixels.
scrollTo() It scrolls the content to the specified coordinates.

[Link] Object
 Navigator object is the representation of Internet browser.
 It contains all the information about the visitor's (client) browser.

Navigator Object Properties

Property Description
appName It returns the name of the browser.
appCodeName It returns the code name of the browser.
appVersion It returns the version information of the browser.
cookieEnabled It determines whether cookies are enabled in the browser.
Platform It returns which platform the browser is compiled.
userAgent It returns the user agent header sent by the browser to the server.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 43

Navigator Object Methods

Description
Method
javaEnabled() It specifies whether or not the browser is Java enabled.

Example : Simple Program on Navigator Object

<html>
<body>
<script type="text/javascript">
[Link]("<b>Browser: </b>"+[Link]+"<br><br>");
[Link]("<b>Browser Version: </b>"+[Link]+"<br><br>");
[Link]("<b>Browser Code:
</b>"+[Link]+"<br><br>");
[Link]("<b>Platform: </b>"+[Link]+"<br><br>");
[Link]("<b>Cookie Enabled:
</b>"+[Link]+"<br><br>");
[Link]("<b>User Agent: </b>"+[Link]+"<br><br>");
[Link]("<b>Java Enabled: </b>"+[Link]()+"<br><br>");
</script>
</body>
</html>

Output:

Browser: Netscape
Browser Version: 5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36
Browser Code: Mozilla
Platform: Linux x86_64
Cookie Enabled: true
User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36
Java Enabled: true

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 44

[Link] Object
 History object is a part of the window object.
 It is accessed through the [Link] property.
 It contains the information of the URLs visited by the user within a browser
window.

History Object Properties

Property Description
Length It returns the number of URLs in the history list.
Current It returns the current document URL.
Next It returns the URL of the next document in the History object.
Previous It returns the URL of the last document in the history object.

History Object Methods

Method Description
back() It loads the previous URL in the history list.
forward() It loads the next URL in the history list.
go(“URL”) It loads a specific URL from the history list.

[Link] Object
 Location object is a part of the window object.
 It is accessed through the '[Link]' property.
 It contains the information about the current URL.

Location Object Properties

Property Description
Hash It returns the anchor portion of a URL.
Host It returns the hostname and port of a URL.
hostname It returns the hostname of a URL.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 45

Href It returns the entire URL.


pathname It returns the path name of a URL.
Port It returns the port number the server uses for a URL.
protocol It returns the protocol of a URL.
Search It returns the query portion of a URL.

Location Object Methods

Method Description
assign() It loads a new document.
reload() It reloads the current document.
replace() It replaces the current document with a new one.

Conversion functions:
eval() This function converts a string to a numerical value. For example consider
the following
Sum=eval(“1234”)
When the above statement is executed, it will assign the value 1234 to the
variable [Link] function eval() takes a string as a parameter and returns a
numerical value. If the string value, which is passed as a parameter doesnot
represent a valid numerical value , then it results in an error.

parseInt() This function extracts the first integer part from a given string. If the string
does not begin with an integer then this function returns ‘0’.
For example num=parseInt(“123string”) will result in a value 123 being
assigned to the variable num and num=parseInt(“xyz123”) will result in a
value ‘NaN’ being assigned to the variable num because the string xyz123
does not begin with an integer.

ParseFloat() This function extracts the first floating-point number from a given string.
For example parseFloat(“1.23xyz”) returns 1.23.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 46

Example : Simple Program on Location Object

<html>
<body>
<script type="text/javascript">
[Link]("<b>Path Name: </b>"+[Link]+"<br><br>");
[Link]("<b>Href: </b>"+[Link]+"<br><br>");
[Link]("<b>Protocol: </b>"+[Link]+"<br><br>");
</script>
</body>
</html>

Output:

Path Name: /home/tutorialride2/location_object.html


Href: [Link]
Protocol: undefined

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 47

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 48

Example :
To remove all characters other than alphabets and numbers

var str=[Link];
var re=/[^A-Za-z0–9]/g
var lowRegStr = [Link]().replace(re, '');

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 49

Functions in JavaScript:

 Function is a reusable code-block that will be executed whenever it is called.


 Function is a great time saver.
 It is used for performing repetitive tasks where you can call the same function
multiple times to get the same effect.
 It allows code reusability.
 JavaScript provides number of built-in functions.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 50

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 51

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 52

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 53

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 54

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 55

Common Built-in Functions

Functions Description
Returns true, if the object is Not a Number.
isNan()
Returns false, if the object is a number.
If the string begins with a number, the function reads through the string
parseFloat until it finds the end of the number; cuts off the remainder of the string
(string) and returns the result.
If the string does not begin with a number, the function returns NaN.
If the string begins with an integer, the function reads through the string
until it finds the end of the integer, cuts off the remainder of the string and
parseInt
returns the result.
(string)
If the string does not begin with an integer, the function returns NaN (Not
a Number).
String
Converts the object into a string.
(object)
eval() Returns the result of evaluating an arithmetic expression.

User-defined Functions
 User-defined function means you can create a function for your own use. You can
create yourself according to your need.
 In JavaScript, these functions are written in between the <HEAD> tag of the
HTML page.

Functions are set of statements, which perform a specific task. Functions may or may not
return a value. Every function has a name and an argument list, which is optional. In
JavaScript functions are declared in the following manner.

function FunctioNname (argument list){


Function
--- JavaScript Statements------- Definition

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 56

The keyword function indicates that the following statements will be part of the function.
The scope of the function is defined by {} and statements form the body of the function.
Functions are not executed until they are explicitly called using function call statements.

Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the
name of that function as shown in the example code.

Example:
In the bellow program a function is designed to perform the task of calculating the time
required to travel a certain distance at a certain speed.

<HTML>
<head>
<SCRIPT LANGUAGE="JAVASCRIPT">
function caltimedistance()
{
var x = parseFloat([Link])
var y = parseFloat([Link])
result=x/y
[Link]=result
}

</SCRIPT>

</head>

<BODY>
<form name=f1>
<h1> Time to distance calculator </h1>
<br> Distance in miles <input type=text name=t1>
<br> Speed in miles per hour <input type=text name=t2>
<br> <input type=button value=claculate onclick=caltimedistance()>
<br> answer (nuber of hours)<input type=text name=t3>
</form>
</BODY>
</HTML>

Function Parameters
A function can take multiple parameters separated by comma.

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 57

function inc(sum){
sum=sum+200;
return sum;
}

The return Statement


A JavaScript function can have an optional return statement. This is required if you want
to return a value from a function. This statement should be the last statement in a
function.

Example: here inc function increments the value by 200 and returns value to the other
function add

function add(){
n1= parseInt([Link]);
n2= parseInt([Link]);
sum= n1+n2;
newsum=inc(sum)
[Link](" result "+ newsum);
}

function inc(sum){
sum=sum+200;
return sum;
sum=sum+10;
}

Local and Global Variables:


Depending on where it is defined, a variable may have a local or a global scope. The
scope of a variable is the range within which the declaration and assignment of the
variable is applied. A Global Variable, declared outside of a function using the var
keyword, is accessible from any window or frame in which JavaScript is running.
A Local Variable is one that is usually declared within a function. If you want a variable
to be available to other script or functions within JavaScript, use the var keyword and
declare the variables outside of a function.

Different Dialog Boxes/ Window Object methods available in JavaScript:

[Link] Method
The Alert method displays a dialog box containing a message and an OK button.
Syntax
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 58

Alert(“Good Morning”)

2 Confirm Method
The Confirm() method is similar to the alert() method except that it produces a dialog
box with a message, an OK button, and a Cancel button. The confirm method returns
true if the user clicks OK and false if the user Clicks Cancel.
Syntax
Val= confirm("Good Morning")

3 The prompt Method

The Prompt method displays a message to the user and prompts the user to type
information into a text field. It provides the capability to display default text in the text
filed.

Syntax
Prompt(“text”,” default text_Field_value”)

Eg:
a=prompt("Good Morning","india")

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 59

JavaScript Event Handling


Introduction to Event Handling

 Event Handling is a software routine that processes actions, such as keystrokes


and mouse movements.
 It is the receipt of an event at some event handler from an event producer and
subsequent processes.

Event Handlers

Event
Description
Handler
onAbort It executes when the user aborts loading an image.
It executes when the input focus leaves the field of a text, textarea or a
onBlur
select option.
It executes when the input focus exits the field after the user modifies its
onChange
text.
In this, a function is called when an object in a button is clicked, a link is
onClick pushed, a checkbox is checked or an image map is selected. It can return
false to cancel the action.
onError It executes when an error occurs while loading a document or an image.
It executes when input focus enters the field by tabbing in or by clicking
onFocus
but not selecting input from the field.
onLoad It executes when a window or image finishes loading.
The JavaScript code is called when the mouse is placed over a specific
onMouseOver
link or an object.
The JavaScript code is called when the mouse leaves a specific link or an
onMouseOut
object.
onReset It executes when the user resets a form by clicking on the reset button.
onSelect It executes when the user selects some of the text within a text or textarea

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 60

field.
onSubmit It calls when the form is submitted.
onUnload It calls when a document is exited.

The following program is the example for handling onclick event

<html>
<head>
<SCRIPT LANGUAGE="javascript">
function sumitinfo(){
if ( [Link]=="")
alert("enter login name")
else if ( [Link]=="")
alert("enter passowd name")
}
</SCRIPT>
</head>
<body bgcolor="red"><pre>
<form name=qz>
wellcome to:
<h1> Nisiki Technologies(p) L.t.d</h1>
<hr>
login name <INPUT TYPE="TEXT" name="log" VALUE="">
Password <INPUT TYPE="Password" TEXT" NAME="pas"
VALUE="">
<input type="button" value="submit" onclick=sumitinfo() >
<INPUT TYPE="reset" NAME="RESET" value="reset">
</form>
</body>
</html>

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 61

JavaScript Events
 The change in the state of an object is known as an Event.
 In html, there are various events which represents that some activity is
performed by the user or by the browser.
 When javascript code is included in HTML, js react over these events and
allow the execution.
 This process of reacting over the events is called Event Handling.
Thus, js handles the HTML events via Event Handlers

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 62

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 63

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 64

Classes in Java Script and Building objects

1 .BY OBJECT LITERAL

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 65

3. BY CREATING INSTANCE OF OBJECT DIRECTLY

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 66

3 BY CREATING OBJECT CONSTRUCTOR

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 67

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 68

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 69

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 70

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 71

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 72

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 73

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 74

Scripting Object Model/JavaScript Object Model/VbScript Object Model

Internet Explorer scripting object model

WINDOW

FRAME HISTORY NAVIGATOR SCRIPT

FORM
LOCATION DOCUMENT

….
LINK

ANCHOR

(HTML
ELEMENTS)
FORM
button,textfield
,check boxes
etc

BROWESER OBJECT DESCRIPTION


Window object To access the browser window. It is the top
most object in the browser object hierarchy
Document object To access the document displayed in the
browser. It is used to access the contents
displayed by head and body sections.
Image object To access an image embedded in the
HTML document.
Form object To access an html form
Anchor object To access an anchor
Link object To access a text or image based link
Location It represents an URL and be used to modify
parts of an existing URL
History It keeps track of all the URL accessed in
the current window.
Elements To access all the form elements in the
HTML element.
[bsa] Dept of MCA, AIMIT
[Link] College (Autonomous), Mangalore.
Unit 1: PH 602.5 [E1] Web Development With AngularJS , NodeJS 75

IMPORTANT QUESTIONS

 Write a note on javascript


 Explain the uses of client side scripting
 Explain the advantages and disadvantages of javascripting
 Write a note on Data types in JavaScript
 Explain with an example how JavaScript code can be embedded into an HTML
document.
 Write a JavaScript function to generate Fibonacci numbers between given range.
 Explain the different logical operators in JavaScript with example.
 Explain the different Bitwise operators in JavaScript with example.
 Explain different looping statements in JavaScript with example
 Explain different conditional statements in JavaScript with example
 Explain how do you create functions in JavaScript with example
 Write a JavaScript function to check whether a given number is Armstrong or
not
 Write a note on conversion functions in JavaScript
 Explain Regular Expressions in JavaScript with example
 Explain Event handing in JavaScript with example
 Explain Array Object and its related methods with example
 Explain Math Object and its related methods with example
 Explain String Object and its related methods with example
 Explain Boolean Object and its related methods with example
 Explain Date Object and its related methods with example
 Explain Different types of Dialog Boxes/ Window Object methods in
JavaScript
 Explain how to create classes in javascript with example
 Explain Window object and its related methods with example
 Explain Document object and its related methods with example
 Explain Form object and its related methods with example

GOOD LUCK

[bsa] Dept of MCA, AIMIT


[Link] College (Autonomous), Mangalore.

You might also like