Download as pdf or txt
Download as pdf or txt
You are on page 1of 183

Client Side Scripting Language (Elective) - 22519

Unit 1
Basics of JavaScript Programming – [10 hours]
[12 Marks- R = 04, U = 04, A = 04]
Syllabus: -
1.1. Features of JavaScript.
1.2. Object Name, Property, method, Dot syntax, main event.
1.3. Values and Variables.
1.4. Operators and Expressions – Primary Expressions, Object and Array initializers,
function definition expression, property access expressions, invocation expressions.
1.5. If statement, if…else, if…elseif, nested if statement.
1.6. Switch…case statement.
1.7. Loop statement – for loop, for…in loop, while loop, do…while loop, continue
statement.
1.8. Querying and setting properties and deleting properties, property getters and setters.

Unit Outcomes (UO’s): -


1a. Create object to solve the given problem.
1b. Develop JavaScript to implement the Switch-case statement for the given problem.
1c. Develop JavaScript to implement loop for solving the given iterative problem.
1d. Display properties of the given object using getters and setters.
1e. Develop program using basic features of JavaScript to solve the given problem.

1.1 Introduction – What is JavaScript:-


 JavaScript was initially created to “make web pages alive”. The programs in this
language are called as “Scripts”.
 JavaScript can be written right in a HTML web pages and run automatically as the
page loads. Scripts are provided and executed as plain text. It doesn’t need special
preparation or compilation to run.
 JavaScript is a dynamic computer programming language. 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.
 It is an interpreted programming language with object-oriented capabilities.

Gramin Polytechnic, Vishnupuri, Nanded 1


Client Side Scripting Language (Elective) - 22519

 JavaScript was first known as “LiveScript”, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.

Fig 1.1: The process of Client Side Scripting


1.1.1 Features of JavaScript:-
JavaScript is a client side technology, it is mainly used for gives client side validation,
but it has lot of features which are given below:-
 JavaScript is an Object based scripting language JavaScript is object based
language as it provides predefined objects.
 Giving the user more control over the browser.
 It Handling dates and time.
 It Detecting the user's browser and OS,
 It is light weighted.
 Validating users input.
 JavaScript is a scripting language and it is not java.
 JavaScript is interpreter based scripting language.
 JavaScript is case sensitive.
 Every statement in JavaScript must be terminated with semicolon (;).
 Most of the JavaScript control statements syntax is same as syntax of control
statements in C language.
 An important part of JavaScript is the ability to create new functions within
scripts. Declare a function in JavaScript using function keyword.
1.1.2 Limitations of JavaScript:-
JavaScript have some limitations which are given below;

Gramin Polytechnic, Vishnupuri, Nanded 2


Client Side Scripting Language (Elective) - 22519

• Client-side JavaScript does not allow the reading or writing of files.


• It cannot be used for networking applications because there is no such support
available.
• It doesn't have any multithreading or multiprocessor capabilities.
1.1.3 Steps for writing JavaScript program:-
• To write a JavaScript, you need a web browser and either a text editor or an HTML
editor.
• To add JavaScript code to an HTML file, create or open an HTML file with your
text/HTML editor. A basic HTML file has some basic HTML tags, such as <html>,
<head> and <body>.
• To write JavaScript code into HTML code, you need to enclose it within a set of
<script></script> tags.
• You will sometimes see some JavaScript code between the <head></head> tags. Or,
you may see it in the <body></body> tags (or even in both places).
• The opening <script> tag has one required attribute and one optional attribute. The
required attribute is the type attribute, while the optional attribute is src (which
allows you to point to an external script file, covered later in this answer). The value
of the type attribute is set to text/javascript.
Example:- (JavaScript program to print Hello, World)
<html>
<head>
<title>My Web Page</title>
<script type="text/javascript">
document.write(“Hello, world!”) // JavaScript Code
</script>
</head>
</html>

1.2 Object Name, Property, method, Dot syntax, main event:-


1.2.1 Object Name:-
 Object is a non-primitive data type in JavaScript.

Gramin Polytechnic, Vishnupuri, Nanded 3


Client Side Scripting Language (Elective) - 22519

 It is like any other variable; the only difference is that an object holds multiple values
in terms of properties and methods. Properties can hold values of primitive data types
and methods are functions.
 Following are the ways for creating objects in JavaScript:-
 Creating objects using object literal syntax: - This is really simple. All you
have to do is throw your key value pairs separated by ‘:’ inside a set of curly
braces({ }) and your object is ready to be served (or consumed), like below:

Example:- (JavaScript program to create object literal)


<script type="text/javascript">
var studInfo={studName:"ABC",colName:"Gramin",brName:"CO"};
</script>

 Creating objects using the ‘new’ keyword: - This method of object creation
resembles the way objects are created in class-based languages, like Java. So,
to create an object using the ‘new’ keyword, you need to have a constructor
function.
Example:- (JavaScript program to create object using New keyword)
<script type="text/javascript">
var studInfo=new Object();
studInfo.studName="ABC";
studInfo.colName="Gramin";
studInfo.brName="CO";
document.write(studInfo.studName);
</script>

1.2.2 Property:-
• A property of an object can be explained as a variable that can be attached to the
object.
• Object properties are basically the same as ordinary JavaScript variables, except for
the attachment to objects.
• A property is a “key:value” pair where:-
 Key:- is a string (also called a “property name”)

Gramin Polytechnic, Vishnupuri, Nanded 4


Client Side Scripting Language (Elective) - 22519

 Value:- it can be anything.

Example:- (JavaScript program to explain Property)


<html>
<title>Property Example</title>
<script type="text/javascript">
var studInfo={studName:"ABC",colName:"Gramin",brName:"CO"};
document.write(studInfo.studName);
</script>
</html>

1.2.3 Method:-
 JavaScript methods are actions that can be performed on objects.
 Object Methods in JavaScript can be accessed by using functions. Functions in
JavaScript are stored as property values.
 When you click Submit button on Form it process some set of instructions that is
nothing but the method.

Example:- (JavaScript program to explain JavaScript methods)


<html>
<title>Method Example</title>
<script type="text/javascript">
function disp()
{
var studInfo={studName:"ABC",colName:"Gramin",brName:"CO"};
document.write(studInfo.studName);
}
</script>
<input type="button" value="click me" onclick="disp()">
</html>
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 5


Client Side Scripting Language (Elective) - 22519

1.2.4 Dot syntax:-


 In JavaScript, you refer to the methods and properties of an object using the Dot
Syntax.
 When you do this, you must include the name of the object. JavaScript uses the Dot
Syntax to separate the name of the object from its properties and methods.
 One of the best example is:- “document. Write(“Hello World!”);”
 Here you are using the method write () of the document object.
1.2.5 Main Event:-
 JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.
 When the page loads, it is called an event.
 Without events and handlers we would never be able to create client-side web
applications.
 Events allow JavaScript to detect when a certain action has been performed by the
user, e.g. hovering over an element, clicking a link, scrolling the page, resizing the
window, when the user clicks a button, that click is an event.
 Other examples include events like pressing any key, closing a window, resizing a
window, when the mouse moves over an element etc.
1.3 Values and Variables:-
 Variable means anything that can vary. JavaScript includes variables which hold the
data value and it can be changed anytime.
 JavaScript uses reserved keyword var to declare a variable. A variable must have a
unique name. You can assign a value to a variable using equal to (=) operator when
you declare it or before using it.
 JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine.
 JavaScript provides different data types to hold different types of values. There are
two types of data types in JavaScript:-
 Primitive data type
 Non-primitive (reference) data type
 JavaScript primitive data types: - There are five types of primitive data types in
JavaScript. They are as follows:

Gramin Polytechnic, Vishnupuri, Nanded 6


Client Side Scripting Language (Elective) - 22519

Data Type Description


String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

 JavaScript non-primitive data types :- The non-primitive data types are as follows:

Data Type Description


Object represents instance through which we can access
members
Array represents group of similar values
RegExp represents regular expression

1.4 Operators and Expressions:-


1.4.1 Primary Expressions:-
 A primary expression is one that needs no further evaluation to resolve its value.
 A primary expression is a specific object, identifier, or literal and may also be the
result of evaluating another nested expression that is surrounded by the grouping
operators (parentheses).
 The this keyword is classed as a primary expression. The value returned by the this
keyword depends on the execution context currently being processed.
 An identifier is a primary expression if it refers to an object or function.
 Constants and string literals are by definition primary expressions.
 Any expression within the grouping operators (parentheses) becomes a primary
expression since the rules of precedence dictate that it must be resolved completely
before being replaced into the expression to which it is an operand.
1.4.2 Operators:-
JavaScript has the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Bitwise Operators
 Logical Operators

Gramin Polytechnic, Vishnupuri, Nanded 7


Client Side Scripting Language (Elective) - 22519

 Assignment operators
 Special Operators
1.4.2.1 Arithmetic Operators:-
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11

1.4.2.2 Comparison Operators:-


The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
Operator Description Example
== Is equal to 10==20 = false
Identical (equal and of same
=== 10==20 = false
type)
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false

1.4.2.3 Bitwise Operators:-


The bitwise operators perform bitwise operations on operands. A bitwise operator
treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal,
or octal numbers. Bitwise operators perform their operations on such binary representations,
but they return standard JavaScript numerical values. The bitwise operators are as follows:
Operator Description Example
& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false

Gramin Polytechnic, Vishnupuri, Nanded 8


Client Side Scripting Language (Elective) - 22519

~ Bitwise NOT (~10) = -10


<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2

1.4.2.4 Logical Operators:-


Logical operators are typically used with Boolean (logical) values; when they are,
they return a Boolean value. However, the && and || operators actually return the value of
one of the specified operands, so if these operators are used with non-Boolean values, they
may return a non-Boolean value. The following operators are known as JavaScript logical
operators.
Operator Description Example
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

1.4.2.5 Assignment Operators:-


An assignment operator assigns a value to its left operand based on the value of its
right operand. The simple assignment operator is equal (=), which assigns the value of its
right operand to its left operand. That is, x = y assigns the value of y to x. The following
operators are known as JavaScript assignment operators.
Operator Description Example
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0

1.4.2.6 Special Operators:-


The following operators are known as JavaScript special operators.
Operator Description
Conditional Operator returns value based on the condition. It
(?:)
is like if-else.
Comma Operator allows multiple expressions to be evaluated
,
as single statement.

Gramin Polytechnic, Vishnupuri, Nanded 9


Client Side Scripting Language (Elective) - 22519

delete Delete Operator deletes a property from the object.


in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
checks what is returned in a generator by the generator's
yield
iterator.

1.4.3 Object and Array Initializers:-


 Object and array initializers are expressions whose value is a newly created object or
array. These initializer expressions are sometimes called “object literals” and
“array literals.”
 Unlike true literals, however, they are not primary expressions, because they include
a number of sub expressions that specify property and element values.
 An array initializer is a comma-separated list of expressions contained within
square brackets. The value of an array initializer is a newly created array.
 The elements of this new array are initialized to the values of the comma-separated
expressions:
[] An empty array
[1+2,3+4] A 2-element array.
[[1,2,3], [4,5,6], [7,8,9]]; Nested array
[1,,,,5]; Array having five elements
 Object initializer expressions are like array initializer expressions, but the square
brackets are replaced by curly brackets, and each sub expression is prefixed with a
property name and a colon:
var p = { x:2.3, y:-1.2 }; An object with 2 properties
var q = {}; An empty object with no properties
q.x = 2.3; q.y = -1.2; Now q has the same properties as p
var rectangle = { upperLeft: { x: 2, y: Nested Object literals
2 },
lowerRight: { x: 4, y: 5 } };

Gramin Polytechnic, Vishnupuri, Nanded 10


Client Side Scripting Language (Elective) - 22519

1.4.4 Function definition expression:-


 The function expression is also called an anonymous function because it doesn't
have a name.
 This function expression derives using the function operator to create a function, and
the result can be stored in a variable or object property.
 Anonymous function, defined at run-time.
 This way defining functions are hoisted, means they can accessed before they are
declared.

Syntax:-
// Function declaration
function add(num1, num2)
{
return num1 + num2;
}

// Function expression
var add = function (num1, num2)
{
return num1 + num2;
};

1.4.5 Property access expression:-


A property access expression evaluates to the value of an object property or an array
element. JavaScript defines two syntaxes for property access:
1. expression. Identifier: - The first style of property access is an expression followed
by a period and an identifier. The expression specifies the object, and the identifier
specifies the name of the desired property.
2. expression [ expression ] :- The second style of property access follows the first
expression (the object or array) with another expression in square brackets. This
second expression specifies the name of the desired property or the index of the
desired array element.
Example:-
1. var o = {x:1,y:{z:3}}; // An example object
2. var a = [o,4,[5,6]]; // An example array that contains the object
3. o.x // => 1: property x of expression o
4. o.y.z // => 3: property z of expression o.y
5. o["x"] // => 1: property x of object o

Gramin Polytechnic, Vishnupuri, Nanded 11


Client Side Scripting Language (Elective) - 22519

Example cont..:-
6. a[1] // => 4: element at index 1 of expression a
7. a[2]["1"] // => 6: element at index 1 of expression a[2]
8. a[0].x // => 1: property x of expression a[0]

1.4.6 Invocation expression:-


 An invocation expression is JavaScript’s syntax for calling (or executing) a function
or method.
 It starts with a function expression that identifies the function to be called.
 The function expression is followed by an open parenthesis, a comma-separated list
of zero or more argument expressions, and a close parenthesis.
 When an invocation expression is evaluated, the function expression is evaluated
first, and then the argument expressions are evaluated to produce a list of argument
values.

Example:-
1. f(0) // f is the function expression; 0 is the argument expression.
2. Math.max(x,y,z) // Math.max is the function; x, y and z are the arguments.
3. a.sort() // a.sort is the function; there are no arguments.

1.5 Conditional statements:-


Conditional statements are used to decide the flow of execution based on different
conditions. If a condition is true, you can perform one action and if the condition is false, you
can perform another action.

Gramin Polytechnic, Vishnupuri, Nanded 12


Client Side Scripting Language (Elective) - 22519

There are mainly three types of conditional statements in JavaScript.


1. If statement
2. If…Else statement
3. If…Else If…Else statement
4. Nested if statement
1.5.1 If statement:-
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.
Syntax:-
if (condition)
{
Statements to be executed if condition is true
}

Example:- (JavaScript program to find greatest from two numbers using if


stmt)
<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{
a=30;
b=20;
if(a>b)
{
alert("a is greater");
}
}
</script> </html>

1.5.2 If…else statement:-


The 'if...else' statement is the next form of control statement that allows JavaScript to
execute statements in a more controlled way.

Gramin Polytechnic, Vishnupuri, Nanded 13


Client Side Scripting Language (Elective) - 22519

Syntax:-
if (condition)
{
Statements to be executed if condition is true
}
Else
{
Statements to be executed if condition is false
}

Example:- (JavaScript program to find greatest from two numbers using


if…else stmt)
<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{
a=10;
b=20;
if(a>b)
{
alert("a is greater");
}
else
{
alert("b is greater");
}
}
</script> </html>

1.5.3 If…else if statement:-


The if...else if... statement is an advanced form of if…else that allows JavaScript to
make a correct decision out of several conditions.

Gramin Polytechnic, Vishnupuri, Nanded 14


Client Side Scripting Language (Elective) - 22519

Syntax:-
if (condition 1) {
Statement(s) to be executed if condition 1 is true
} else if (condition 2) {
Statement(s) to be executed if condition 2 is true
} else if (condition 3) {
Statement(s) to be executed if condition 3 is true
} else {
Statement(s) to be executed if no condition is true
}

Example:- (JavaScript program to find greatest from three numbers using


if…else if stmt)
<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{ a=10;
b=20;
c=40;
if(a>b & a>c)
{ alert("a is greater");}
else if(b>a & b>c)
{ alert("b is greater"); }
else
{ alert("c is greater"); }
}
</script> </html>

1.5.4 Nested if statement:-


Embedding If Statement inside another IF Statement called JavaScript Nested If
Statement. The JavaScript Else Statement allows us to print different statements depending

Gramin Polytechnic, Vishnupuri, Nanded 15


Client Side Scripting Language (Elective) - 22519

upon the expression result (TRUE, FALSE). Sometimes we have to check even further when
the condition is TRUE. In this situation, we can use JavaScript Nested IF statement, but be
careful while using it.
Syntax:-
if ( test condition 1)
{ //If the test condition 1 is TRUE then these it will check for test condition 2
if ( test condition 2)
{ //If the test condition 2 is TRUE then these statements will be executed
Test condition 2 True statements;
}
else
{ //If the c test condition 2 is FALSE then these statements will be executed
Test condition 2 False statements;
}
else
{ //If the test condition 1 is FALSE then these statements will be executed
Test condition 1 False statements;
}

Example:- (JavaScript program to demonstrate nested if else stmt)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{ a=40;
if(a==10)
{alert("a is equal to 10");
if(a<20)
{ alert("a is smaller than 20"); }
else
{ alert("a is greater than 20"); }
}
Else { alert("a is not equal to 10"); }
} </script> </html>

Gramin Polytechnic, Vishnupuri, Nanded 16


Client Side Scripting Language (Elective) - 22519

1.6 Switch Case statements:-


The switch statement evaluates an expression and executes code as a result of a
matching case. At first it can look a bit intimidating, but the basic syntax is similar to that of
an if statement. It will always be written with switch () {}, with parentheses containing the
expression to test, and curly brackets containing the potential code to execute.

Syntax:-
switch (expression)
{
case condition 1: statement(s)
break;

case condition 2: statement(s)


break;
...
case condition n: statement(s)
break;
default: statement(s)
}

Gramin Polytechnic, Vishnupuri, Nanded 17


Client Side Scripting Language (Elective) - 22519

The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.

Example:- (JavaScript program to demonstrate Switch -Case)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{
var ch;
ch=prompt("enter ur choice");
switch(parseInt(ch))
{
case 1:
alert("pressed 1");
break;
case 2:
alert("pressed 2");
break;
default:
alert("invalid choice");
}
}
</script>
</html>

1.7 Loop statements:-


Looping in programming languages is a feature which facilitates the execution of a set
of instructions/functions repeatedly while some condition evaluates to true. Following are the
looping statements used in JavaScript:
1.7.1 For Loop:-
For loop provides a concise way of writing the loop structure. A for statement
consumes the initialization, condition and increment/decrement in one line thereby providing
a shorter, easy to debug structure of looping.

Gramin Polytechnic, Vishnupuri, Nanded 18


Client Side Scripting Language (Elective) - 22519

1. Initialization condition: Here, we initialize the variable in use. It marks the start of a
for loop. An already declared variable can be used or a variable can be declared, local
to loop only.
2. Testing Condition: It is used for testing the exit condition for a loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
3. Statement execution: Once the condition is evaluated to true, the statements in the
loop body are executed.
4. Increment/ Decrement: It is used for updating the variable for next iteration.
5. Loop termination: When the condition becomes false, the loop terminates marking
the end of its life cycle.

Syntax:-
for (initialization; test condition; increment/decrement statement)
{
Statement(s) to be executed if test condition is true
}

Example:- (JavaScript program to demonstrate For…Loop)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{ var i;
for (i=0;i<=10;i++)

Gramin Polytechnic, Vishnupuri, Nanded 19


Client Side Scripting Language (Elective) - 22519

Example cont..:-
for (i=0;i<=10;i++)
{
document.write(i);
}
}
</script>
</html>

1.7.2 For…in Loop:-


JavaScript also includes another version of for loop also known as the for..in Loops.
The for..in loop provides a simpler way to iterate through the properties of an object.

Syntax:-
for (variableName in Object)
{
statement(s)
}

Example:- (JavaScript program to demonstrate For…In loop)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{
var languages = { first : "C", second : "Java",
third : "Python", fourth : "PHP",
fifth : "JavaScript" };
for (i in languages)
{
document.write(languages[i] + "<br >");
}
}
</script>
</html>
Gramin Polytechnic, Vishnupuri, Nanded 20
Client Side Scripting Language (Elective) - 22519

1.7.3 While Loop:-


A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if
statement.

 While loop starts with the checking of condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason it is also called Entry control loop
 Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for
the next iteration.
 When the condition becomes false, the loop terminates which marks the end of its life
cycle.

Syntax:-
while (expression)
{
Statement(s) to be executed if expression is true
Counter;
}

Example:- (JavaScript program to demonstrate While loop)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{ var i=1;
while(i<=10)

Gramin Polytechnic, Vishnupuri, Nanded 21


Client Side Scripting Language (Elective) - 22519

Example cont..:-
{
document.write(i);
i++;
}
}
</script>
</html>

1.7.4 Do…While Loop:-


The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be executed at least once,
even if the condition is false.

Syntax:-
do
{
Statement(s) to be executed;
Counter;
} while (expression);

Example:- (JavaScript program to demonstrate Do…While loop)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{ var i=1;
do
{
document.write(i);
i++;
} while(i<=10)
}
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 22


Client Side Scripting Language (Elective) - 22519

1.7.5 Break and Continue statements:-


When JavaScript encounters a break statement in a loop it immediately exits the loop
without executing any other statements in the loop. Control is immediately transferred to the
statement following the loop body.

Example:- (JavaScript program to demonstrate break stmt)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{
for(i=1;i<=10;i++)
{
if(i==4)
{
break;
}
document.write(i);
}
document.write("<br> Exit from loop...");
}
</script>
</html>

When JavaScript encounters a continue statement in a loop it stops the execution of


the current iteration and goes back to the beginning of the loop to begin the next iteration.

Example :- (JavaScript program to demonstrate continue stmt)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{
for(i=1;i<=10;i++)
{

Gramin Polytechnic, Vishnupuri, Nanded 23


Client Side Scripting Language (Elective) - 22519

Example cont…:-
if(i==4)
{
continue;
}
document.write(i);
}
document.write("<br> Exit from loop...");
}
</script>
</html>

1.8 Querying, Setting Properties and Deleting Properties:-


1.8.1 Querying and Setting Properties:-
 To obtain the value of a property, use the dot (.) or square bracket ([]) operators
described in Property Access Expressions. The left-hand side should be an expression
whose value is an object.
 If using the dot operator, the right-hand must be a simple identifier that names the
property.
 If using square brackets, the value within the brackets must be an expression that
evaluates to a string that contains the desired property name

Example :-
1. var author = book.author; // Get the "author" property of the book.
2. var name = author.surname // Get the "surname" property of the author.
3. var title = book["main title"] // Get the "main title" property of the book.

 To create or set a property, use a dot or square brackets as you would to query the
property, but put them on the left-hand side of an assignment expression:

Example :-
1. book.edition = 6; // Create an "edition" property of book.
2. book["main title"] = "Gramin"; // Set the "main title" property.

Gramin Polytechnic, Vishnupuri, Nanded 24


Client Side Scripting Language (Elective) - 22519

1.8.2 Deleting Properties:-


The delete operator is used to completely remove the properties from the JavaScript
object. Deleting is the only way to actually remove a property from an object.

Example :-
1. delete book.edition; // deletes "edition" property of book.
2. Delete book["main title"]; // deletes the "main title" property.

Example:- (JavaScript program to demonstrate delete property)


<html>
<input type="button" value="click me" onclick="disp()">
<script type="text/javascript">
function disp()
{
var studInfo={studName:"ABC",colName:"Gramin",brName:"CO"};
document.write(studInfo.studName+' '+studInfo.colName+"<br>");
document.write(delete studInfo.colName);
}
</script>
</html>

1.8.3 Property getters and setters:-


 In JavaScript, getter and setter are two conventional methods that are used for
retrieving and updating the value of a variable.
 Accessor properties are represented by “getter” and “setter” methods. In an object
literal they are denoted by get and set.

Syntax :-
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};

Gramin Polytechnic, Vishnupuri, Nanded 25


Client Side Scripting Language (Elective) - 22519

 An object property is a name, a value and a set of attributes. The value may be
replaced by one or two methods, known as setter and a getter.
 When program queries the value of an accessor property, JavaScript invoke getter
method (passing no arguments). The return value of this method becomes the value of
the property access expression.
 When program sets the value of an accessor property. JavaScript invoke the setter
method, passing the value of right-hand side of assignment. This method is
responsible for setting the property value.
o If property has both getter and a setter method, it is read/write property.
o If property has only a getter method, it is read-only property.
o If property has only a setter method, it is a write-only property.
 getter works when obj.propName is read, the setter – when it is assigned.

Example:- (JavaScript program to demonstrate getter and setter)


<html>
<head>
<title>Functions</title>
<body>
<script type="text/Javascript">
var myCar = {
/* Data properties */
defColor: "blue",
defMake: "Toyota",
/* Accessor properties (getters) */
get color() {
return this.defColor;
},
get make() {
return this.defMake;
},
/* Accessor properties (setters) */
set color(newColor) {
this.defColor = newColor;
},
set make(newMake) {
this.defMake = newMake;
Gramin Polytechnic, Vishnupuri, Nanded 26
Client Side Scripting Language (Elective) - 22519

Example cont…:-
this.defMake = newMake;
}
};
document.write("Car color:" + myCar.color + " Car Make: "+myCar.make)
/* Calling the setter accessor properties */
myCar.color = "red";
myCar.make = "Audi";
/* Checking the new values with the getter accessor properties */
document.write("<p>Car color:" + myCar.color); // red
document.write(" Car Make: "+myCar.make); //Audi
</script>
</head>
</body>
</html>

Question Bank:-
Remember Level:-
1. Enlist features of JavaScript.
2. Define terms (i). Method, (ii). Property, (iii). Event, (iv). Object Name
3. Define (i). Break and (ii). Continue statements.
Understand Level:-
1. What do you mean by Object in JavaScript explain with an example.
2. Explain JavaScript Variables with an example
3. Explain <script> tag with example.
4. Explain JavaScript Operators and expressions.
5. Explain how object and array initializer works.
6. Explain function definition expression.
7. Explain property access expression and invocation expression.
8. What is conditioning statement? Explain if…else and if…else if statement.
9. Explain Switch Case statement in JavaScript.

Gramin Polytechnic, Vishnupuri, Nanded 27


Client Side Scripting Language (Elective) - 22519

10. Explain Loop statements –For loop, for…in loop, while loop. Do…while loop, in
JavaScript.
11. How to set and delete properties in JavaScript with an example
12. Explain the concept of getter and setters in JavaScript with an example.
Apply Level:-
1. Write a JavaScript program to implement arithmetic operators.
2. Write a JavaScript program to demonstrate if…else if statement.
3. Write a JavaScript program to demonstrate nested if statement.
4. Write a JavaScript program to demonstrate Switch case statement.
5. Write a JavaScript program to demonstrate for loop statement.
6. Write a JavaScript program to demonstrate for…in loop statement.
7. Write a JavaScript program to demonstrate while loop statement.

Gramin Polytechnic, Vishnupuri, Nanded 28


Client Side Scripting Language (Elective) - 22519

Unit 2
Array, Function and String – [10 hours]
[14 Marks- R = 02, U = 04, A = 08]
Syllabus: -
2.1 Array- declaring an Array, Initializing an Array, Defining an Array elements, Looping
an Array, Adding an Array element, Sorting an Array element, Combining an Array elements
into a String, Changing elements of an Array, Objects as associative Arrays.
2.2 Function- Defining a function, writing a function, Adding an arguments, Scope of
variable and arguments.
2.3 Calling a function- Calling a function with or without an argument, calling a function
from HTML, Function calling another function, returning a value from a function.
2.4 String- Manipulate a string, Joining a string, retrieving a character from a given
position, retrieving a position of character in a string, dividing text, copying a sun string,
converting string to number and numbers to string, changing the case of string, finding a
Unicode of a character-charCodeAt(), fromCharCode().
Unit Outcomes (UO’s): -
2a. Create array to solve the give problem.
2b. Perform the specified string manipulation operation on the given String(s).
2c. Develop JavaScript to implement the given function.
2d. Display JavaScript to convert the given Unicode to character form.
2e. Develop JavaScript to convert the given character to Unicode and vice-versa.

2.1 Array:-
Arrays are complex variables that allow us to store more than one value or a group of values
under a single variable name. Every value is associated with numeric index starting with 0.

Gramin Polytechnic, Vishnupuri, Nanded 29


Client Side Scripting Language (Elective) - 22519

JavaScript arrays can store any valid value, including strings, numbers, objects, functions,
and even other arrays, thus making it possible to create more complex data structures such as
an array of objects or an array of arrays.
2.1.1 Declaring an Array:-
There are basically two types for declaring an array:-
1. Array Literal:-
Array literal syntax is simple. It takes a list of values separated by a comma and
enclosed in square brackets.
Syntax:-
var <array-name> = [element0, element1, element2,... elementN];

Example:- (JavaScript program to demonstrate array by literal)


<html>
<h1> Array Literal Example</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=[101,102,103];
var i;
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
}
</script>
</html>

2. Creating instance of Array / Array Constructor:-


You can initialize an array with Array constructor syntax using new keyword.

Syntax:-
1. var arrayName = new Array();
2. var arrayName = new Array(Number length);
3. var arrayName = new Array(element1, element2, element3,...
elementN);

Gramin Polytechnic, Vishnupuri, Nanded 30


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate array by constructor)


<html>
<h1> Array by creating instance</h1>
<input type="button" value="click" onclick="disp()">
<script language="javascript">
function disp()
{
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
}
</script>
</html>

2.1.2 Initializing an Array:-


Initialization is the process of assigning values to an array. The simplest way to create
an array in JavaScript is enclosing a comma-separated list of values in brackets.
Example:- (JavaScript program to demonstrate array initialization)
<html>
<h1> Array Literal Example</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=["ABC","BBC","CCC"];
var i;
for(i=0;i<a.length;i++)

Gramin Polytechnic, Vishnupuri, Nanded 31


Client Side Scripting Language (Elective) - 22519

Example cont..:-
{
document.write(a[i] + "<br/>");
}
}
</script>
s</html>

2.1.3 Defining Array Elements:-


 An array is an ordered collection of values: each value is called an element, and
each element has a numeric position in the array, known as its index.
 Arrays in JavaScript are zero-based, which means that the index of the first element
is 0.

Example:- (JavaScript program to demonstrate defining array elements)


<html>
<h1> Defining elements of Array</h1>
<input type="button" value="click" onclick="disp()">
<script language="javascript">
function disp()
{
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
document.write("<br> Element at 0th place="+emp[0]);
document.write("<br> Element at 1st place="+emp[1]);
document.write("<br> Element at 2nd place="+emp[2]);
}
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 32


Client Side Scripting Language (Elective) - 22519

2.1.4 Looping an Array:-


JavaScript for loops iterate over each item in an array. JavaScript arrays are zero
based, which means the first item is referenced with an index of 0.
Referencing items in arrays is done with a numeric index, starting at zero and ending
with the array length minus 1.
Example:- (JavaScript program to demonstrate looping through an array
elements)
<html>
<input type="button" value="click" onclick="disp()">
<script language="javascript">
function disp()
{
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
}
</script>
</html>

2.1.5 Adding an Array Element:-


There are several ways to add elements to existing arrays in JavaScript. One can add
elements to the end of an array using “push”, to the beginning using “unshift”, or to the
middle using “splice”.
You can also add a new element to an array simply by specifying a new index and
assigning a value, as the following demonstrates:
Ex:- var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar

Gramin Polytechnic, Vishnupuri, Nanded 33


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate adding new element in array )


<html>
<h1> Array program</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=[101,102,103];
a[3]=104;
var i;
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
}
</script>
</html>

1. Array push Method:-


The array push method allows you to add one or more elements to the end of an
array. It modifies the array upon which it is invoked and returns the new length of the array.

Syntax:-
arrayName.push(element1,element2,…..,element N);

Example:- (JavaScript program to demonstrate adding new element in array


by push method )
<html>
<h1> Array program</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{

Gramin Polytechnic, Vishnupuri, Nanded 34


Client Side Scripting Language (Elective) - 22519

Example cont..:-
var a=[101,102,103];
var i;
document.write("Before Push" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
a.push(104);
document.write("After Push" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
}
</script>
</html>

2. Array unshift Method:-


The array unshift method is used to add elements to the beginning of an array. It
accepts multiple arguments, adjusts the indexes of existing elements, and returns the new
length of the array. The unshift method modifies the array on which it is invoked.

Syntax:-
arrayName.unshift(element1,element2,…..,element N);

Example:- (JavaScript program to demonstrate adding new element in array


using unshift method)
<html>
<h1> Array program</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=[101,102,103];

Gramin Polytechnic, Vishnupuri, Nanded 35


Client Side Scripting Language (Elective) - 22519

Example cont..:-
var a=[102,103,104];
var i;
document.write("Before unshift" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
a.unshift(101);
document.write("After unshift" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
}
</script>
</html>

3. Array splice Method:-


The array splice method can be used for adding and/or removing elements from an
array. The first argument specifies the location at which to begin adding or removing
elements. The second argument specifies the number of elements to delete, if any. When
using splice to add elements to an array, the second argument would be zero. The third and
subsequent arguments are elements to be added to the array.

Syntax:-
array.splice(index, howmany, item1, ....., itemX);
where:-
1. Index - Required. An integer that specifies at what position to add/remove
items, Use negative values to specify the position from the end of the array.
2. Howmany - Optional. The number of items to be removed. If set to 0, no
items will be removed.
3. item1, ..., itemX - Optional. The new item(s) to be added to the array

Gramin Polytechnic, Vishnupuri, Nanded 36


Client Side Scripting Language (Elective) - 22519

Example :- (JavaScript program to demonstrate adding new array element


using splice method)
<html>
<h1> Array program</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=[101,102,104];
var i;
document.write("Before splice" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
a.splice(2,0,103);
document.write("After splice" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
}</script>
</html>

2.1.6 Sorting an Array:-


1. Array.Sort():-
The JavaScript Array object has a built-in method sort () for sorting array elements in
alphabetical order or in ascending order.

Syntax:-
arrayName.sort();

Gramin Polytechnic, Vishnupuri, Nanded 37


Client Side Scripting Language (Elective) - 22519

Example :- (JavaScript program to demonstrate sorting array elements)


<html>
<h1> Array program</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=["CCC","AAA","BBB"];
var i;
document.write("Before sorting" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
a.sort();
document.write("After Sorting" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
}
</script>
</html>

2. Array.reverse():-
You can use the reverse () method to reverse the order of the elements of an array or
in descending order. This method reverses an array in such a way that the first array element
becomes the last, and the last array element becomes the first.

Syntax:-
arrayName.reverse();

Gramin Polytechnic, Vishnupuri, Nanded 38


Client Side Scripting Language (Elective) - 22519

Example :- (JavaScript program to demonstrate reversing array elements)


<html>
<h1> Array program</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=["CCC","BBB","AAA"];
var i;
document.write("Before reversing" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
a.reverse();
document.write("After reversing" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
}
</script>
</html>

2.1.7 Combining an Array Elements into a string:-


There are following two methods for combining Array elements into a string:-
1. Array.join():-
Array.join() function is used to join the elements of the array together into
a string.

Syntax:-
arrayName.join([separator]);

A string to separate each elements of the array. If leave it by default array element
separate by comma ( , ).

Gramin Polytechnic, Vishnupuri, Nanded 39


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate join())


<html>
<h1> Combining Array into a string</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=[103,101,102];
document.write(a.join('|'));
}
</script>
</html>

2. Array.concat():-
The concat() method is used to merge two or more arrays. This method
does not change the existing arrays, but instead returns a new array.

Syntax:-
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]]);

Example:- (JavaScript program to demonstrate concat())


<html>
<h1> Combining Array into a string program</h1>
<input type="button" value="click me" onclick="disp()">
<script language="javascript">
function disp()
{
var a=[101,102,103];
var i;
document.write("Before concat" + "<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i] + "<br/>");
}
b=a.concat(104);

Gramin Polytechnic, Vishnupuri, Nanded 40


Client Side Scripting Language (Elective) - 22519

Example cont…:-
document.write("After concat" + "<br/>");
for(i=0;i<b.length;i++)
{
document.write(b[i] + "<br/>");
}
}
</script>
</html>

2.1.8 Changing Elements of an Array:-


For changing elements of an array following methods are used:-
1. array.shift():-
JavaScript array shift() is an inbuilt function that removes the first item from
an array and returns that removed item. The shift() method changes the length of the
array on which we are calling the shift() method. JavaScript Array Shift method is not
pure function as it directly modifies the array.

Syntax:-
arrayName.shift();

Example:- (JavaScript program to demonstrate shift())


<html>
<head>
<title>JavaScript Array shift Method</title>
</head>
<body>
<script type = "text/javascript">
var element = [105, 1, 2, 3].shift();
document.write("Removed element is : " + element );
</script>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 41


Client Side Scripting Language (Elective) - 22519

2. array.unshift()-
JavaScript array unshift() method adds one or more elements to the beginning of
an array and returns the new length of the array.

Syntax:-
arrayName.unshift(element1,element2,…..,element N);

Example:- (JavaScript program to demonstrate unshift())


<html>
<head>
<title>JavaScript Array unshift Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
document.write("<br />Before Unshift array is : " + arr );
var length = arr.unshift("water");
document.write("<br />Returned array is : " + arr );
document.write("<br /> Length of the array is : " + length );
</script>
</body>
</html>

3. array.Pop():-
JavaScript array pop() method removes the last element from an array and returns
that element.

Syntax:-
arrayName.pop();

Example:- (JavaScript program to demonstrate pop())


<html>
<head>
<title>JavaScript Array pop Method</title>
</head>
<body>
<script type = "text/javascript">
Gramin Polytechnic, Vishnupuri, Nanded 42
Client Side Scripting Language (Elective) - 22519

Example cont…:-
<script type = "text/javascript">
var numbers = [101, 102, 103];
var element = numbers.pop();
document.write("Popped element is : " + element );
</script>
</body>
</html>

4. array.Push():-
JavaScript array push() method appends the given element(s) in the last of the array
and returns the length of the new array.
Syntax:-
arrayName.push(element1,element2,…..,element N);

Example:- (JavaScript program to demonstrate push())


<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script type = "text/javascript">
var numbers = [101, 102, 103];
document.write("Array Before Push : " + numbers);
var element = numbers.push(104,105);
document.write("Array After Push : " + numbers);
</script>
</body>
</html>

2.1.9 Object as Associative Array:-


Associative arrays are dynamic objects that the user redefines as needed.
When you assign values to keys in a variable of type Array, the array is

Gramin Polytechnic, Vishnupuri, Nanded 43


Client Side Scripting Language (Elective) - 22519

transformed into an object, and it loses the attributes and methods of Array. The length
attribute has no effect because the variable is no longer of Array type.

Syntax:-
arrayName={“key1”:value1,”key2”:value2,…..,”key N”:value N};

We cannot use a simple for loop because the elements are not accessible by an index
(besides the fact that we must use a special function to determine the position of the last), but
the simpler for in loop is ideal. Keys are assigned to the variable "key", and with the key we
access the value.
Example:- (JavaScript program to demonstrate associative array)
<html>
<head>
<title>JavaScript Associative Array</title>
</head>
<body>
<script type = "text/javascript">
var arr = { "one" : 1, "two" : 2, "three": 3 };
for(var key in arr)
{
var value = arr[key];
document.write(key + " = " + value + '<br>');
}
</script>
</body>
</html>
2.2 Function:-
 A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again.
 It helps programmers in writing modular codes. Functions allow a programmer
to divide a big program into a number of small and manageable functions.
 Like any other advanced programming language, JavaScript also supports all
the features necessary to write modular code using functions.

Gramin Polytechnic, Vishnupuri, Nanded 44


Client Side Scripting Language (Elective) - 22519

 Functions always return a value. In JavaScript, if no return value is specified,


the function will return undefined.
2.2.1 Defining a Function:-
 A function is created with an expression that starts with the keyword function.
 Functions have a set of parameters and a body, which contains the statements
that are to be executed when the function is called.
 The function body of a function created this way must always be wrapped in
braces, even when it consists of only a single statement.
 A function can have multiple parameters or no parameters at all.

Syntax:-
function name(parameters)
{
statements
}

2.2.2 Writing a Function:-

Example:- (JavaScript program to demonstrate Function)


<html>
<h1>Function Example</h1>
<input type="button" value="click me" onclick="disp()">
<script languge="javascript">
function disp()
{
document.write("welcome to Function without parameter");
}
</script>
</html>

2.2.3 Adding an Argument:-


Arguments are the values the function receives from each parameter when the
function is executed.
Example:- (JavaScript program to demonstrate function with arguement)
<html>
<h1> Function with Arguements</h1>
<input type="button" value="click me" onclick="disp(r)">

Gramin Polytechnic, Vishnupuri, Nanded 45


Client Side Scripting Language (Elective) - 22519

Example cont..:-
<script type="text/javascript">
var r=prompt("enter the radius");
function disp(r)
{
var a;
a=3.14*r*r;
document.write(a);
}
</script>
</html>

2.2.4 Scope of Variable and Argument:-


Scope in JavaScript refers to the current context of code, which determines the accessibility
of variables to JavaScript. The two types of scope are local and global:
 Global variables are those declared outside of a block.
 Local variables are those declared inside of a block.
Example:- (JavaScript program to demonstrate variable scope)
<html>
<h1>Scope of Variable Example</h1>
<input type="button" value="click me" onclick="disp()">
<script languge="javascript">
var glob="Global Variable"; //declaration of global variable
function disp()
{
var loc="Local Variable"; //declaration of local variable
document.write("<br>"+glob);
document.write("<br>"+loc);
}
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 46


Client Side Scripting Language (Elective) - 22519

2.3 Calling a Function:-


To invoke a function somewhere later in the script, you would simply need to write
the name of that function.
2.3.1 Calling a Function with or without argument:-
Syntax:- (Calling Function without argument)
function name();

Example:- (JavaScript program to demonstrate function calling without


argument)
<html>
<script type="text/javascript">
function disp()
{
document.write("Function gets Called");
}
disp();
</script>
</html>

Syntax:- (Calling Function with argument)


function name (argument);

Example:- (JavaScript program to function calling with argument)


<html>
<script type="text/javascript">
function disp(a)
{
document.write(a);
}
disp("By passing argument");
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 47


Client Side Scripting Language (Elective) - 22519

2.3.2 Calling a Function from HTML:-


JavaScript is mainly used for actions on user events like onClick(), onMouseOver()
etc. But what if you need to call a JavaScript function without any user events then it would
be to use the onLoad() of the <body> tag.

Example:- (JavaScript program to demonstrate calling function from HTML


tag)
<html>
<h1> Function called from HTML Example</h1>
<body onLoad="open()">
<script type="text/javascript">
function open()
{
alert("Function called from HTML-Open");
}
</script>
</body></html>

2.3.3 Function calling from another Function:-


Following are steps for calling one Function from another Function:-
1. First declare the first Function.
2. Write some statements inside first Function.
3. Declare second Function.
4. Call first Function from second Function.

Example:- (JavaScript program to demonstrate calling function from another


function)
<html>
<h1> Function call Example</h1>
<script type="text/javascript">
function first(a)
{
document.write(a);
}
function second()
{

Gramin Polytechnic, Vishnupuri, Nanded 48


Client Side Scripting Language (Elective) - 22519

Example cont..:-
first("Function called from another Function");
}
second();
</script>
</html>

2.3.4 Returning a Value from Function:-


 JavaScript provides for passing one value back to the code that called it after
everything in the function that needs to run has finished running.
 JavaScript passes a value from a function back to the code that called it by using the
return statement. The value to be returned is specified in the return.
 That value can be a constant value, a variable, or a calculation where the result of the
calculation is returned.

Syntax:-
return value;

Example:- (JavaScript program to demonstrate returning value from a


function)
<html>
<h1> Function Return Example</h1>
<script type="text/javascript">
function disp()
{
var a="Return statement example";
return(a);
}
document.write(disp());
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 49


Client Side Scripting Language (Elective) - 22519

2.4 String:-
In JavaScript, the textual data is stored as strings. There is no separate type for a
single character. The String object lets you work with a series of characters. There are 2
ways to create string in JavaScript:-
1. By string literal: - The string literal is created using double quotes.

Syntax:-
var stringname="string value";

2. By string object (using new keyword): - The syntax of creating string object using
new keyword,
Syntax:-
var stringname=new String("string literal");

Example:- (JavaScript program to demonstrate string by literal)


<html>
<h1> String Example</h1>
<script type="text/javascript">
var a="String by literal";
document.write("<br>"+a);
var b=new String("String by object");
document.write("<br>"+b);
</script>
</html>

2.4.1 Manipulating a String:-


Methods Description Syntax
It provides the char value present at String.charAt(index);
charAt()
the specified index.
It provides the Unicode value of a String.charCodeAt(index);
charCodeAt() character present at the specified
index.
It provides a combination of two or String.concat(str1,str2,...,strn);
concat()
more strings.

Gramin Polytechnic, Vishnupuri, Nanded 50


Client Side Scripting Language (Elective) - 22519

1. indexOf(ch);
It provides the position of a char 2. indexOf(ch,index);
indexOf()
value present in the given string. 3. indexOf(str);
4. indexOf(str,index);
It provides the position of a char 1. lastIndexOf(ch);
2. lastIndexOf(ch,index);
value present in the given string by
lastIndexOf() 3. lastIndexOf(str);
searching a character from the last 4. lastIndexOf(str,index);
position.
It searches a specified regular string.search(regexp);
expression in a given string and
search()
returns its position if a match
occurs.
It searches a specified regular string.match(regexp);
expression in a given string and
match()
returns that regular expression if a
match occurs.
It replaces a given string with the string.replace(oldstr,newstr);
replace()
specified replacement.
It is used to fetch the part of the string.substr(start,length);
given string on the basis of the
substr()
specified starting position and
length.
It is used to fetch the part of the string.substring(start,end) ;
substring() given string on the basis of the
specified index.
It is used to fetch the part of the string.slice(start,end);
slice() given string. It allows us to assign
positive as well negative index.
It converts the given string into string.toLowerCase();
toLowerCase()
lowercase letter.
It converts the given string into string.toLocaleLowerCase();
toLocaleLowerCase() lowercase letter on the basis of
host?s current locale.
toUpperCase() It converts the given string into string.toUpperCase();

Gramin Polytechnic, Vishnupuri, Nanded 51


Client Side Scripting Language (Elective) - 22519

uppercase letter.
It converts the given string into string. toLocaleUpperCase();
toLocaleUpperCase() uppercase letter on the basis of
host?s current locale.
It provides a string representing the object.toString();
toString()
particular object.
It provides the primitive value of string.valueOf();
valueOf()
string object.
It splits a string into substring array, string.split(separator, limit)
split() then returns that newly created
array.
It trims the white space from the String trim()
trim()
left and right side of the string.

2.4.2 Joining a String:-


There are two ways of doing string concatenation in JavaScript.
1. + Operator:- The + operator does string concatenation as soon as one of its
operands is a string. Then the other operand is converted to string.
Syntax:-
String 1 + string 2;

Example:- (JavaScript program to demonstrate + operator)


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin ";
var s2="Poly";
var s3=s1+s2;
document.write("<br>"+s3);
</script>
</html>

2. str.concat() :- str.concat() function is used to join two or more strings together in


JavaScript.

Gramin Polytechnic, Vishnupuri, Nanded 52


Client Side Scripting Language (Elective) - 22519

Syntax:-
str.concat(string2, string3, string4,......, stringN);

Example:- (JavaScript program to demonstrate concat())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin ";
var s2="Poly";
var s3=s1.concat(s2);
document.write("<br>"+s3);
</script>
</html>

2.4.3 Retrieving a Character from given position:-


The JavaScript string charAt() method is used to find out a char value present
at the specified index in a string.
The index number starts from 0 and goes to n-1, where n is the length of the
string. The index value can't be a negative, greater than or equal to the length of the
string.

Example:- (JavaScript program to demonstrate retrieving char from given


position)
<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly";
document.write("<br>"+s1.charAt(7));
</script> </html>

2.4.4 Retrieving a Position of Character in a String:-


There are 3 methods for retrieving the position of character in a string:-
1. indexOf():-The indexOf() method returns index of given character value or
substring. If it is not found, it returns -1. The index counter starts from zero.

Gramin Polytechnic, Vishnupuri, Nanded 53


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate indexOf())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly";
var s2=s1.indexOf("P");
document.write("Position = "+s2);
</script>
</html>

2. lastIndexOf():-The lastIndexOf() method returns last index of the given


character value or substring. If it is not found, it returns -1. The index counter
starts from zero.
Example:- (JavaScript program to demonstrate lastIndoeOf())
<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly Nanded";
var s2=s1.lastIndexOf("a");
document.write("Position = "+s2);
</script>
</html>

3. search():-The search() method searches a string for a specified value, and


returns the position of the match. The search value can be string or a regular
expression. This method return -1 if no match is found.

Syntax:-
String.search(word);

Gramin Polytechnic, Vishnupuri, Nanded 54


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate search())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly Nanded";
var s2=s1.search("Nanded");
document.write("Position = "+s2);
</script>
</html>

2.4.5 Dividing text:-


Java String split() method is used for splitting a String into its substrings based on the
given delimiter or regular expression.

Example:- (JavaScript program to demonstrate split())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly Nanded";
var s2=s1.split(" ");
document.write("After spliting = "+s2);
</script>
</html>

2.4.6 Copying a Sub-String:-


There are 2 methods used in JavaScript for copying a Sub-String:-
1. substring ():-The substring() method returns a new string that is a substring of this
string.
Example:- (JavaScript program to demonstrate substring())
<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly Nanded";
var s2=s1.substring(1,7);
var s3=s1.substring(7);
Gramin Polytechnic, Vishnupuri, Nanded 55
Client Side Scripting Language (Elective) - 22519

Example cont…:-
var s3=s1.substring(7);
document.write("Output = "+s2);
document.write("<br>");
document.write("Output = "+s3);
</script>
</html>

2. substr():-The substr() method extracts parts of a string, beginning at the character at


the specified position, and returns the specified number of characters.
Example:- (JavaScript program to demonstrate substr())
<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly Nanded";
var s2=s1.substr(1,7);
var s3=s1.substr(7);
document.write("Output = "+s2);
document.write("<br>");
document.write("Output = "+s3);
</script>
</html>

2.4.7 Converting String to Numbers and Numbers to String:-


1. parseInt():-The parseInt() is an inbuilt function in JavaScript which is used to accept
the string convert it into an integer.

Syntax:-
parseInt(Value, radix);

Parameters: It accepts two parameter which are specified below-


 Value: “Value” contains a string which is converted to an integer.
 radix: This parameter represents the radix or base to be used and it is optional.
The radix parameter is used to specify which numeral system to be used

Gramin Polytechnic, Vishnupuri, Nanded 56


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate parseInt())


<html>
<script type="text/javascript">
var s1="1107";
var s2=parseInt(s1);
document.write("Output = "+s2);
</script>
</html>

2. parseFloat():-The parseFloat() is an inbuilt function in JavaScript which is used to


accept the string and convert it into a floating point number.

Syntax:-
parseFloat(Value);

Example:- (JavaScript program to demonstrate parseFloat())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="3.14";
var s2=parseFloat(s1);
document.write("Output = "+s2);
</script>
</html>

3. Number():- The Number() is used to string to number.

Syntax:-
Number(Value);

Example:- (JavaScript program to demonstrate Number())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="3.14";

Gramin Polytechnic, Vishnupuri, Nanded 57


Client Side Scripting Language (Elective) - 22519

Example cont…:-
var s2=Number(s1);
document.write("Output = "+s2);
</script>
</html>

4. toString():-The JavaScript toString function is a String function that converts the


specified expression to the string object.

Example:- (JavaScript program to demonstrate toString())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="3.14";
var s2=s1.toString();
document.write("Output = "+s2);
</script>
/html>

2.4.8 Changing the Case of String :-


1. toUpperCase():-This function converts the entire string to Upper case. This function
does not affect any of the special characters, digits and the alphabets that are already
in upper case.
Example:- (JavaScript program to demonstrate toUpperCase())
<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="gramin poly nanded";
var s2=s1.toUpperCase();
document.write("Output = "+s2);
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 58


Client Side Scripting Language (Elective) - 22519

2. toLowerCase():-This function converts the entire string to lower case. This function
does not affect any of the special characters, digits and the alphabets that are already
in the lower case.
Example:- (JavaScript program to demonstrate toLowerCase())
<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="GRAMIN POLY NANDED";
var s2=s1.toLowerCase();
document.write("Output = "+s2);
</script>
</html>

2.4.9 Finding a Unicode of a Character:-


1. charCodeAt():-In JavaScript, charCodeAt() is a string method that is used to
retrieve a Unicode value for a character at a specific position in a string. Because
the charCodeAt() method is a method of the String object, it must be invoked
through a particular instance of the String class.

Syntax:-
string.charCodeAt([position]);

Example:- (JavaScript program to demonstrate charCodeAt())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1="Gramin Poly Nanded";
var s2=s1.charCodeAt(1);
document.write("Output = "+s2);
</script>
</html>
2. formCharCode():- In JavaScript, fromCharCode() is a string method that is
used to create a string from a sequence of Unicode values. Because the
fromCharCode() method is a static method of the String constructor, it must be

Gramin Polytechnic, Vishnupuri, Nanded 59


Client Side Scripting Language (Elective) - 22519

invoked through the String constructor object rather than through the particular
instance of the String class.

Syntax:-
String.fromCharCode(value1, value2, ... value_n);

Where,- value1, value2, ... value_n


The Unicode values to convert to characters and then concatenate together into a string.

Example:- (JavaScript program to demonstrate fromCharCode())


<html>
<h1> String Example</h1>
<script type="text/javascript">
var s1=String.fromCharCode(112,70,50);
document.write("Output = "+s1);
</script>
</html>

Question Bank:-
Remember Level:-
1. What is an array?
2. Differentiate between concat() and join() methods of array object.
3. What is (i). shift(), (ii). unshift(), (iii). Pop() and (iv). Push()
4. What is the use of splice().
5. Define function with an example.
6. What is the use of return statement?
Understand Level:-
1. How to create array in JavaScript.
2. How to combine Array into String
3. Explain concept of object as associative array in JavaScript with an example.
4. Explain scope of variables declared in function with example.
5. How to call function from HTML tag explain with example.
6. Explain String functions in JavaScript with an example
7. Explain the use of split() with an example.

Gramin Polytechnic, Vishnupuri, Nanded 60


Client Side Scripting Language (Elective) - 22519

8. Explain charCodeAt(), fromCharCode() methods in JavaScript


Apply Level:-
1. Write a JavaScript program to demonstrate Array Literal.
2. Write a JavaScript program to create and initialize array elements.
3. Write a JavaScript program to create and print array elements.
4. Write a JavaScript program to create and print array elements using for loop.
5. Write a JavaScript program to sort elements in array.
6. Write a JavaScript program to sort array elements in ascending and descending order.
7. Write a JavaScript program to combine array elements into strings using separator.
8. Write a JavaScript program to demonstrate shift(), unshift(), push(),pop(), splice().
9. Write a JavaScript program to create a function.
10. Write a JavaScript program to demonstrate function calling with arguments.
11. Write a JavaScript program to call function from another function
12. Write a JavaScript program to declare a string.
13. Write a JavaScript program to demonstrate string concatenation.
14. Write a JavaScript program to demonstrate string concatenation using concat().
15. Write a JavaScript program to retrieve character at specified position from string.
16. Write a JavaScript program to retrieve the position of given character from string.
17. Write a JavaScript program to implement indexOf().
18. Write a JavaScript program to find first and last index of given character from string.
19. Write a JavaScript program to implement search().
20. Write a JavaScript program to demonstrate the use of substring().
21. Write a JavaScript program to implement substr().
22. Write a JavaScript program to convert String to Integer.
23. Write a JavaScript program to convert String to Float.
24. Write a JavaScript program to convert Number to String.
25. Write a JavaScript program to change all characters to Uppercase.
26. Write a JavaScript program to change all characters to Lowercase.

Gramin Polytechnic, Vishnupuri, Nanded 61


Client Side Scripting Language (Elective) - 22519

Unit 3
Form and Event Handling – [06 hours]
[10 Marks- R = 02, U = 04, A = 04]
Syllabus: -
3.1 Building blocks of a Form, Properties and methods of form, Button, Text, Text area
Checkbox, Radio button, Select element.
3.2 Form events- Mouse event, key events.
3.3 Form objects and elements.
3.4 Changing attribute value dynamically.
3.5 Changing option list dynamically.
3.6 Evaluating checkbox selection.
3.7 Changing a label dynamically.
3.8 Manipulating form elements.
3.9 Intrinsic JavaScript functions, disabling elements, Read only elements.

Unit Outcomes (UO’s): -


3a. Write JavaScript to design a form to accept input values for the given problem.
3b. Use JavaScript to implement form events to solve the given problem.
3c. Develop JavaScript to dynamically assign specified attribute value to the given form
control.
3d. Use the given intrinsic function with specified parameters.

3.1 Building blocks of a Form:-


 There are few differences between a straight HTML form and a JavaScript-enhanced
form.
 The main one being that a JavaScript form relies on one or more event handlers, such
as onClick or onSubmit. These invoke a JavaScript action when the user does
something in the form, like clicking a button.
 The event handlers, which are placed with the rest of the attributes in the HTML form
tags, are invisible to a browser that doesn’t support JavaScript.
 Because of this trait, you can often use one form for both JavaScript and non-
JavaScript browsers.

Gramin Polytechnic, Vishnupuri, Nanded 62


Client Side Scripting Language (Elective) - 22519

 Typical form control objects -- also called "widgets" -- include the following:
 Text box for entering a line of text
 Push button for selecting an action
 Radio buttons for making one selection among a group of options
 Check boxes for selecting or deselecting a single, independent option

Syntax:-
<form>
//form elements
</form>

3.1.1 Properties and Methods of Form:-


Following are the properties of Form element:-
1. Name:- The Name property represents the name of the current <form> element as a
string.

Syntax:-
<form name=”form name”>
//form elements
</form>

2. Action:- The action property represents the action of the <form> element. The
action of a form is the program that is executed on the server when the form is
submitted. This property can be retrieved or set.
Syntax:-
<form action=”URL”>
//form elements
</form>

3. Method:- The method attribute specifies how to send form-data (the form-data is sent
to the page specified in the action attribute). The form-data can be sent as URL
variables (with method="get") or as HTTP post transaction (with method="post").
GET Method:
 Appends form-data into the URL in name/value pairs.

Gramin Polytechnic, Vishnupuri, Nanded 63


Client Side Scripting Language (Elective) - 22519

 The length of a URL is limited (about 3000 characters).


 Never use GET to send sensitive data! (Will be visible in the URL).
 Useful for form submissions where a user wants to bookmark the result.
 GET is better for non-secure data, like query strings in Google.
POST Method:
 Appends form-data inside the body of the HTTP request (data is not shown in
URL).
 Have no size limitations.
 Form submissions with POST cannot be bookmarked.

Syntax:-
<form action=”URL” method=”GET”>
//form elements
</form>

4. Target:- The <form> target Attribute in HTML is used to specify whether the
submitted result will open in the current window, a new tab or on a new frame.
Syntax:-
<form target="_blank|_self|_parent|_top|framename"\>
Where:-
 blank: It opens the link in a new window.
 _self: It opens the linked document in the same frame.
 _parent: It opens the linked document in the parent frameset.
 _top: It opens the linked document in the full body of the window.
 framename: It opens the linked document in the named frame.

Following are some of the elements of the Form:


1. The <input> Element :- The most important form element is the <input>
element. The <input> element can vary in many ways, depending on the type
attribute.

Syntax:-
<input type=”input field”>
Input field:- 1. Text 2. Password 3. Submit 4. Radio
5. Checkbox 6.button ,etc.

Gramin Polytechnic, Vishnupuri, Nanded 64


Client Side Scripting Language (Elective) - 22519

2. The textarea element: - The textarea element represents a field for multi-line
text input. The control associated to this field is a text box that allows users to
edit multiple lines of plain text. textarea controls are useful to collect or edit
long runs of text like messages, files' contents, lists, reviews, articles, etc.

Syntax:-
<textarea name=”name” rows=10 cols=10>
</textarea>

3. The button element: - The button element is used to perform particular action
specified by the user.
Syntax:-
<button type=”button”>
</button>

4. The label element: - A <label> is used to create a caption for a form control

Syntax:-
<label>
Some Description
</label>

Methods of Form element:-


1. reset ():- A reset () allows users to basically clear their web form. It wipes
values from all fields by "resetting" the form to its default appearance.
2. submit():- Submit () send form data to a back-end process or application. The
back-end process then verifies and processes the data, eventually passing the
information into some database application.

Example:- (JavaScript program to demonstrate onsubmit on Form)


<HTML>
<HEAD>
<TITLE>From Submit Example</TITLE>
<BODY>
<FORM NAME="myform" onsubmit="disp()">

Gramin Polytechnic, Vishnupuri, Nanded 65


Client Side Scripting Language (Elective) - 22519

Example cont…:-
<input type="Submit" value="Click me">
</FORM>
</BODY>
<SCRIPT type="text/JavaScript">
function disp()
{
alert("Form submitted");
}
</SCRIPT>
</HEAD>
</HTML>

3.1.2 Button:-
When we create a button, it acts like a generic button. That is, it will not perform any
action when we click on it unless some action has been explicitly written by the user.

Syntax:-
<input type="button" name="Name of the button" value="value of the object">

There are basically 3 types of button we can create that are as follows:-
1. Submit: - When this button is clicked, the form data is submitted to the server.
2. Reset: - When this button is clicked, the input is reset.
3. Button: - It creates simple button which will work when user performs some
action.
Attributes of Button Field:
1. Name: Specifies the name of the object through which it can be referenced.
2. Value: Specifies the value of the button field. This will be the text that is going to
be displayed on the button.

Example:- (JavaScript program to demonstrate Form element-Button)


<HTML>
<HEAD>
<TITLE>Button Example</TITLE>
<BODY>
<FORM NAME="myform" >

Gramin Polytechnic, Vishnupuri, Nanded 66


Client Side Scripting Language (Elective) - 22519

Example cont…:-
<input type="Button" name="bt" value="Click me">
<br>
<input type="Submit" name="sb" value="Submit">
<br>
<input type="Reset" name="rs" value="Reset">
</FORM>
</BODY>
</HEAD>
</HTML>

3.1.3 Text:-
Text fields are data entry fields which takes small amount of data from the user. This
is one of the most widely used controls of a Web Form.

Syntax:-
<input type="text" name="Name" value="default_value">

Attributes of Text Field:


1. Name: - This attribute specifies the name of the object through which it can be
referenced.
2. Value: - This is used to specify the value of the text field (optional).
3. Size : - Width of the text field (optional) .
4. Maxlength: - Used to specify the maximum number of characters that can be
entered into the textbox.

Example:- (JavaScript program to demonstrate Form element-Textfield)


<HTML>
<HEAD>
<TITLE>Text field Example</TITLE>
<BODY>
<FORM NAME="myform" >
<p> Enter your text here</p>
<input type="text" name="t1" size="20" maxlength="10">
</FORM> </BODY> </HEAD> </HTML>

Gramin Polytechnic, Vishnupuri, Nanded 67


Client Side Scripting Language (Elective) - 22519

3.1.4 TextArea:-
TextArea is mainly used when the user has to enter large amount of text. Also one can
enter multiline text in TextArea which is not available in Text.

Syntax:-
<TextArea name=”txtArea” rows="3" cols="50">TextArea Data</TextArea>

Attributes of TextArea:
1. Name: - This attribute specifies the name of the object through which it can be
referenced.
2. cols: - Specifies the width of the TextArea based on the number of visible
character widths.
3. rows: - Specifies the height of the TextArea based on the number of visible lines
of text. If there's more text than this allows, users can scroll using the TextArea's
scrollbars.
4. Wrap (hard/soft/off):- Specifies the text to be wrapped in TextArea. If hard
option is selected the text submitted is with line breaks. If soft option is selected
then the text submitted doesn’t contain line breaks.

Example:- (JavaScript program to demonstrate Form element-TextArea)


<HTML>
<HEAD>
<TITLE>TextArea Example</TITLE>
<BODY>
<FORM NAME="myform" >
<p> Enter your address here</p>
<textarea name="ta1" cols="50" rows="20" wrap="hard">

</textarea>
</FORM>
</BODY>
</HEAD>
</HTML>

Gramin Polytechnic, Vishnupuri, Nanded 68


Client Side Scripting Language (Elective) - 22519

3.1.5 Checkbox:-
Checkboxes are objects of a HTML form which behaves like a toggle switch. i.e., a
checkbox can be in one of the two states, either checked or unchecked. From a group of
checkbox’s user can select multiple options.
Syntax:-
<input type="checkbox" name="name" value="any_value" checked=”true”>

Attributes of Checkbox:
1. Name: - Specifies the name of the checkbox, through which it can be referenced.
2. Value: - Value of the checkbox. Each checkbox will have different values in a
group.
3. Checked: - Checkbox will be selected (by default). In a group of buttons more
than one can be selected.

Example:- (JavaScript program to demonstrate Form element-Checkbox)


<HTML>
<HEAD>
<TITLE>Checkbox Example</TITLE>
<BODY>
<FORM NAME="myform" >
Select Class<br>
<input type="checkbox" name="class" value="CO1I"> First Year
<input type="checkbox" name="class" value="CO3I"> Second Year
<input type="checkbox" name="class" value="CO5I" checked="true"> Third Year
</FORM>
</BODY>
</HEAD>
</HTML>

3.1.6 Radio button:-


Radio buttons are mainly used when the user has to select only one among a group of
options. Radio button has two states and can toggle between them. Several radio buttons can
be grouped together so that only one radio button can be selected at any given time. We can
group radio buttons by giving same name to all the radio buttons.

Gramin Polytechnic, Vishnupuri, Nanded 69


Client Side Scripting Language (Elective) - 22519

Syntax:-
<input type="radio" name="radio group name" value="value of the object"
checked=”true”>

Attributes of Radio button:


1. Name: - Specifies the group name of the radio button. One group of radio button
will have same name through which it can be referenced.
2. Value: - Value of the radio button. Each radio button will have different values in
a group.
3. Checked: - Radio button will be selected. In a group of buttons one can be
selected.

Example:- (JavaScript program to demonstrate Form element-Radio Button)


<HTML>
<HEAD>
<TITLE>Radio button Example</TITLE>
<BODY>
<FORM NAME="myform" >
Select your choice<br>
<input type="radio" name="class" value="no"> First Year
<input type="radio" name="class" value="no"> Second Year
<input type="radio" name="class" value="no"> Third Year
</FORM>
</BODY>
</HEAD>
</HTML>

3.1.7 Select Element:-


The select form control is a container for a series of option elements that display in the
browser as a pull-down menu (that is, a drop-down list). Unless you use the multiple
attribute, the control will allow the user to pick just one item from the list of options

Syntax:-
<select name=”name of select list”>
<option value=”item1”> Item1</option>
<option value=”item N”> ItemN</option>
</select>

Gramin Polytechnic, Vishnupuri, Nanded 70


Client Side Scripting Language (Elective) - 22519

Attributes of Select element:


1. Name: - Defines a name for the drop down menu. It can be used to access the data
of the form after it has been sent or to link to JavaScript element.
2. size: - Indicated the count of the options in drop down list. If the value of "size"
attribute is bigger than 1 and smaller than the total number of the options in the
list, the browser will automatically add a scroll to indicate that there are more
options to view.
3. multiple: - Indicates that more than one option can be chosen. The method of
choosing more than one option depends on the operating system. In Windows, you
need to keep CTRL button.
Option Element:- The HTML <option> element is used to define an item contained
in a <select> element. As such, <option> can represent menu items in popups and
other lists of items in an HTML document.
Attributes of Option element:
1. value: - The content of this attribute represents the value to be submitted with the
form, should this option be selected.
2. selected: - item which is selected at the initial state.

Example:- (JavaScript program to demonstrate Form element-Select)


<HTML>
<HEAD>
<TITLE>Select Example</TITLE>
<BODY>
<FORM NAME="myform" >
Select your choice<br>
<select name="hobbies" size="3">
<option value="Cricket">Cricket</option>
<option value="Singing">Singing</option>
<option value="Dancing">Dancing</option>
</select>
</FORM>
</BODY>
</HEAD> </HTML>

Gramin Polytechnic, Vishnupuri, Nanded 71


Client Side Scripting Language (Elective) - 22519

3.2 Form Events:-


There are following attributes which can be used to trigger any JavaScript code when
there is any event occurs on form level.
1. onchange: - Script runs when the element changes.
2. onsubmit:- Script runs when the form is submitted.
3. onreset:- Script runs when the form is reset.
4. onselect:- Script runs when the element is selected.
5. onblur:- Script runs when the element loses focus.
6. onfocus:- Script runs when the element gets focus.

Example:- (JavaScript program to demonstrate Form events)


<HTML>
<HEAD>
<TITLE>From Event Example</TITLE>
<BODY>
<FORM NAME="myform" >
Name: <input type="text" name="t1">
<br>
Phone: <input type="text" name="t2" onfocus="msg()">
</FORM>
<script type="text/JavaScript">
function msg()
{
alert("Enter only numeric value");
}
</script>
</BODY>
</HEAD>
</HTML>

3.2.1 Mouse Events:-


The MouseEvent interface represents events that occur due to the user interacting
with a mouse. Following are the events associative with mouse:

Gramin Polytechnic, Vishnupuri, Nanded 72


Client Side Scripting Language (Elective) - 22519

1. onclick:- Script runs when a mouse click.


2. ondblclick:- Script runs when a mouse double-click.
3. onmousedown:- Script runs when mouse button is pressed.
4. onmousemove:- Script runs when mouse pointer moves.
5. onmouseout:- Script runs when mouse pointer moves out of an element.
6. onmouseover:- Script runs when mouse pointer moves over an element.
7. onmouseup:- Script runs when mouse button is released.

Example:- (JavaScript program to demonstrate Mouse events)


<HTML>
<HEAD>
<TITLE>Mouse Event Example</TITLE>
<BODY>
<FORM NAME="myform" >
Name: <input type="text" name="t1">
<br>
<input type="button" name="bt1" value="Click me" onclick="msg()">
</FORM>
<script type="text/JavaScript">
function msg()
{
alert("Button clicked");
}
</script>
</BODY>
</HEAD>
</HTML>

3.2.2 Key Events:-


Key Event objects describe a user interaction with the keyboard; each event describes
a single interaction between the user and a key (or combination of a key with modifier keys)
on the keyboard. Following are the events associative keyboard:-
1. onkeydown:- Script runs when key is pressed.
2. onkeypress:- Script runs when key is pressed and released.

Gramin Polytechnic, Vishnupuri, Nanded 73


Client Side Scripting Language (Elective) - 22519

3. onkeyup:- Script runs when key is released.

Example:- (JavaScript program to demonstrate Keyboard events)


<HTML>
<HEAD>
<TITLE>Keyboard Event Example</TITLE>
<BODY>
<FORM NAME="myform" >
<input type="text" onkeydown="disp()">
</FORM>
<script type="text/JavaScript">
function disp()
{
alert("key pressed");
}
</script>
</BODY>
</HEAD>
</HTML>

3.3 Form Objects and Events:-


 The Document Object Model (DOM) is a programming interface for HTML and
documents.
 It defines the logical structure of documents and the way a document is accessed
and manipulated.
 It is called as a Logical structure because DOM doesn’t specify any relationship
between objects.
 DOM is a way to represent the webpage in the structured hierarchical way so that it
will become easier for programmers and users to glide through the document.
 With DOM, we can easily access and manipulate tags, IDs, classes, Attributes or
Elements using commands or methods provided by Document object.
 DOM can be thought of as Tree. The term structure model is sometimes used to
describe the tree-like representation of a document.

Gramin Polytechnic, Vishnupuri, Nanded 74


Client Side Scripting Language (Elective) - 22519

1. Window Object: Window Object is at always at top of hierarchy.


2. Document object: When HTML document is loaded into a window, it becomes a
document object.
3. Form Object: It is represented by form tags.
4. Link Objects: It is represented by link tags.
5. Anchor Objects: It is represented by a href tags.
6. Form Control Elements:: Form can have many control elements such as text fields,
buttons, radio buttons, and checkboxes, etc.
Methods of Document Object:
1. write(“string”): writes the given string on the document.
2. getElementById(): returns the element having the given id value.
3. getElementsByName(): returns all the elements having the given name value.
4. getElementsByTagName(): returns all the elements having the given tag name.
5. getElementsByClassName(): returns all the elements having the given class name.

Syntax:-
1. document.write(“string”);
2. document.getElementById(elementID);
3. document.getElementsByName(name);
4. document.getElementsByTagName(tagname);
5. document.getElementsByClassName(classname);

Gramin Polytechnic, Vishnupuri, Nanded 75


Client Side Scripting Language (Elective) - 22519

Example 1:- (JavaScript program to demonstrate document.getElementById )


<html>
<body>
<p id="demo">Change content</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>

Example 2:- (JavaScript program to demonstrate document.getElementsByName)


<html>
<body>
First Name: <input name="fname" type="text" value="Gramin"><br>
First Name: <input name="fname" type="text" value="Poly">
p>Click the button to get the value of the first element in the document that has a name
attribute with the value "fname".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction() {
var x = document.getElementsByName("fname")[0].value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 76


Client Side Scripting Language (Elective) - 22519

Example 3:- (JavaScript program for document.getElementsByTagName)


<html>
<body>
<p>An unordered list:</p>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<p>Click the button to display the innerHTML of the second li element (index 1).</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction() {
var x = document.getElementsByTagName("LI");
document.getElementById("demo").innerHTML = x[0].innerHTML;
}
</script>
</body>
</html>
Example 4:- (JavaScript program for document.getElementsByClassName
<html>
<body>
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<p>Click the button to change the text of the first div element with class="example"
(index 1).</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction() {
var x = document.getElementsByClassName("example");
x[1].innerHTML = "Hello World!"; } </script> </body> </html>
type="text/javascript">

Gramin Polytechnic, Vishnupuri, Nanded 77


Client Side Scripting Language (Elective) - 22519

innerHTML:-
The innerHTML property can be used to write the dynamic html on the html
document. It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.

Syntax:-
1. Object.innerHTML - It returns the innerHTML Property.
2. Object.innerHTML = value - It is used to set the innerHTML property.

Example :- (JavaScript program to demonstrate innerHTML)


<html>
<body>
<p id="demo">Change content</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>

3.4 Changing attribute value dynamically:-


The attributes are special words used inside the start tag of an HTML element to
control the tag's behavior or provides additional information about the tag.
JavaScript provides several methods for adding, removing or changing an HTML
element's attribute. Some of the methods are as follows:-
1. getAttribute():- This method is used to get the current value of a attribute on
the element.
2. setAttribute():-This method is used to set an attribute on the specified
element. If the attribute already exists on the element, the value is updated;
otherwise a new attribute is added with the specified name and value.

Gramin Polytechnic, Vishnupuri, Nanded 78


Client Side Scripting Language (Elective) - 22519

3. removeAttribute():-This method is used to remove an attribute from the


specified element.

Example :- (JavaScript program to demonstrate dynamically changing attribute


value)
<html>
<input type="button" value="Before Change" id="myBtn">
<script language="javascript">
// Selecting the element
var btn = document.getElementById("myBtn");
// Setting new attributes
btn.setAttribute("value", "After Change");
btn.setAttribute("disabled", "");
</script>
</html>

3.5 Changing Option List dynamically:-

Example :- (JavaScript program to demonstrate dynamically changing option list)


<html>
<select id="food1" name="food1" onchange="populate(this.id,'food2')">
<option value="">
<option value="Veg">Veg</option>
<option value="Fruit">Fruit</option>
</select>
</hr>
<select id="food2" name="food2">
</select>
</hr>
<script language="javascript">
function populate(f1,f2)
{
var f1=document.getElementById(f1);
var f2=document.getElementById(f2);
f2.innerHTML="";

Gramin Polytechnic, Vishnupuri, Nanded 79


Client Side Scripting Language (Elective) - 22519

Example cont..:-
if(f1.value=="Veg")
{
var newOption=document.createElement("option");
newOption.innerHTML="Spinach";
f2.options.add(newOption);
}
if(f1.value=="Fruit")
{
var newOption=document.createElement("option");
newOption.innerHTML="Mango";
f2.options.add(newOption);
}
}
</script>
</html>

3.6 Evaluating Checkbox Selection:-


Example :- (JavaScript program to demonstrate evaluating checkbox selection)
<html>
<form name="myform" action="" method="get">
<p><input type="checkbox" id="ch1" name="Cricket""> Cricket</p>
<p><input type="checkbox" id="ch2" name="Football"> Football</p>
<p><input type="submit" value="click" onclick="disp()"></p>
</form>
<script language="javascript">
function disp()
{
if (myform.ch1.checked && myform.ch2.checked)
{
alert(myform.ch1.name+" "+myform.ch2.name);
}
else if (myform.ch1.checked)
{

Gramin Polytechnic, Vishnupuri, Nanded 80


Client Side Scripting Language (Elective) - 22519

Example cont... :-
alert(myform.ch1.name);
}
else if (myform.ch2.checked)
{
alert(myform.ch2.name);
}
}
</script>
</html>

3.7 Changing a Label Dynamically:-


Example :- (JavaScript program to demonstrate dynamically changing option list)
<html>
<head>
<title> How to change the text of a label using JavaScript ?
</title>
</head>
<label id = "lb1">
Before Changing Label text
</label>
<br>
<button onclick="myChng()">
Click Here!
</button>
<script type="text/javascript">
function myChng() {
document.getElementById("lb1").innerHTML = "After Changing Label text";
}
</script>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 81


Client Side Scripting Language (Elective) - 22519

3.8 Manipulating Form Elements:-


 Sometimes it is mandatory to manipulate the form elements after button click or
before form is being submitted to an application.
 To validate whether each field on the form is filled with data or not using JavaScript
and we can call such function on events like on submit, onclick, etc.
 Many times in a form some fields are hidden and at the time of form submission these
fields assigned with hidden values should be submitted.
 HTML hidden filed elements are similar to other HTML elements which is not visible
on the screen but it has name and attribute which has to be used by the application.

Example:- (Program for demonstrating Hidden field)


<html>
<body>
<script type="text/javascript">
function printIt(){
alert(document.getElementById('abcId').value);
alert(document.formName.elements['abcName'].value);
}
</script>
<h1>Access Hidden value in JavaScript</h1>
<form name="formName">
<input type=hidden id="abcId" name="abcName" value="Gramin Polytechnic
Nanded"/>
<input type=button value="Get Value" onclick="printIt()" />
</form>
</body>
</html>

3.9 Intrinsic JavaScript Function:-


 JavaScript provides some special set of built in function known as Intrinsic
functions.
 These are the functions to achieve actions of submit and reset buttons.
 Intrinsic functions are defined by JavaScript.

Gramin Polytechnic, Vishnupuri, Nanded 82


Client Side Scripting Language (Elective) - 22519

Example:- (Program for demonstrating Intrinsic functions in JavaScript)


<html>
<h1>Intrinsic Function</h1>
<body>
<form name="f1" action="" method="get">
<p> College Name <input type="text" name=t1"/><br>
<img src="D:\Desert.jpg" height="40" width="50"
onclick="javascript:document.forms.f1.submit()"/>
</form>
</body>
</html>

3.10 Disabling Elements:-


 A disabled element is unusable and un-clickable.
 Disabled elements are usually rendered in gray by default in browsers.HTML form
elements have an attribute called disabled that can be set using JavaScript.
 If you are setting it in HTML you can use disabled="disabled" but if you are using
JavaScript you can simply set the property to true or false.
 The following elements support the disabled attribute: BUTTON, INPUT,
OPTGROUP, OPTION, SELECT, and TEXTAREA.
Example :- (Program for demonstrating disabling form elements)
<html>
<body>
<button id="myBtn">My Button</button> <br><br>
<button onclick="disableBtn()">Disable "My Button"</button>
<button onclick="enableBtn()">Enable "My Button"</button>
<script type=”text/javascript”>
function disableBtn() {
document.getElementById("myBtn").disabled = true;
}
function enableBtn() {
document.getElementById("myBtn").disabled = false;
} </script> </body> </html>

Gramin Polytechnic, Vishnupuri, Nanded 83


Client Side Scripting Language (Elective) - 22519

3.11 Read Only Elements:-


The readonly attribute is a boolean attribute.When present; it specifies that an input
field is read-only. A read-only input field cannot be modified (however, a user can tab to it,
highlight it, and copy the text from it).The readonly attribute can be set to keep a user from
changing the value until some other conditions have been met (like selecting a checkbox,
etc.). Then, a JavaScript can remove the readonly value, and make the input field editable.

Example :- (Program for demonstrating read only form elements)


<html>
<body>
Name: <input type="text" id="myText">
<p>Click the button to set the text field to read-only.</p>
<p><strong>Tip:</strong> To see the effect, try to type something in the text field
before and after clicking the button.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction() {
document.getElementById("myText").readOnly = true;
}
</script>
</body>
</html>

Question Bank:-
Remember Level:-
1. What is form? Give the uses of form.
2. What is Event? List various form events.
3. What is the meaning of onfocus and onblur methods?
Understand Level:-
1. Explain building blocks of form.
2. Explain form tag with all its attributes.
3. Explain Button element with example.

Gramin Polytechnic, Vishnupuri, Nanded 84


Client Side Scripting Language (Elective) - 22519

4. Explain Text element with example.


5. Explain TextArea element with example.
6. Explain Checkbox element with example.
7. Explain Radio button element with example.
8. Explain Select element with example.
9. Explain various Mouse events with example.
10. Explain various keyboard events with example.
11. Explain Form objects and elements.
12. Explain how to manipulate form elements with an example.
13. Explain JavaScript intrinsic functions with an example.
14. How to disable elements on the form explain with an example.
15. Explain readOnly elements in JavaScript with an example.
Apply Level:-
1. Write a JavaScript program to implement onsubmit event.
2. Write a JavaScript program to implement onreset event.
3. Write a JavaScript program to create different types of buttons.
4. Write a JavaScript program to demonstrate text element with different attributes.
5. Write a JavaScript program to demonstrate textarea element.
6. Write a JavaScript program to demonstrate checkbox element.
7. Write a JavaScript program to demonstrate radio button element.
8. Write a JavaScript program to demonstrate select element.
9. Write a JavaScript program to demonstrate onfocus and onblur method.
10. Write a JavaScript program to access value from element of form.
11. Write a JavaScript program to demonstrate getElementById(),getElementsByName,
getElementsByTagName, getElementsByClassName method.
12. Write a JavaScript program to demonstrate innerHTML property.
13. Write a JavaScript program to change attribute value dynamically.
14. Write a JavaScript program to change option list according to user’s choice.
15. Write a JavaScript program to evaluate checkbox selected by user.
16. Write a JavaScript program to change the label of form dynamically.

Gramin Polytechnic, Vishnupuri, Nanded 85


Client Side Scripting Language (Elective) - 22519

Unit 4
Cookies and Browser Data – [06 hours]
[08 Marks- R = 02, U = 02, A = 04]
Syllabus: -
4.1 Cookies – Basic of cookies, Reading a cookie value, Writing a cookie value, Creating
a cookies, Deleting a cookies, Setting the expiration date of cookie.
4.2 Browser – Opening a window, Giving the new window focus, Window position,
Changing the content of window, Closing a window, Scrolling a web page, Multiple windows
at once, Creating a web page in new window, JavaScript, in URLs, JavaScript security,
Timers, Browser location and History.

Unit Outcomes (UO’s): -


4a. Create cookies based on the given problem.
4b. Develop JavaScript to manage a cookie in the given manner.
4c. Write JavaScript to manipulate the specified attributes of window object in the given
manner.
4d. Write JavaScript to create browser history of the given object.

4.1 Cookies:-
4.1.1 Basic of cookies:-
 A cookie is an amount of information that persists between a server-side and a client-
side. A web browser stores this information at the time of browsing.
 A cookie contains the information as a string generally in the form of a name-value
pair separated by semi-colons.
 It maintains the state of a user and remembers the user's information among all the
web pages.
 When a user sends a request to the server, then each of that request is treated as a new
request sent by the different user.
 So, to recognize the old user, we need to add the cookie with the response from the
server browser at the client-side.
 Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.

Gramin Polytechnic, Vishnupuri, Nanded 86


Client Side Scripting Language (Elective) - 22519

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


1. Expires − The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
2. Domain − The domain name of your site.
3. Path − The path to the directory or web page that set the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
4. Secure − If this field contains the word "secure", then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
5. Name=Value − Cookies are set and retrieved in the form of key-value
pairs.
4.1.2 Reading a cookie value:-
 Reading a cookie is just as simple as writing one, because the value of the
document.cookie object is the cookie.
 So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons,
where name is the name of a cookie and value is its string value.
 You can use strings' split() function to break a string into key and values.
Example :- (JavaScript program to demonstrate reading cookie value)
<html>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script type=”text/javascript”>

Gramin Polytechnic, Vishnupuri, Nanded 87


Client Side Scripting Language (Elective) - 22519

Example cont…:-
function setCookie()
{
document.cookie="username=Gramin Poly";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>

4.1.3 Writing a cookie value:-


We can write a value to cookie by using document.cookie. But it’s not a data
property, it’s an accessor (getter/setter). An assignment to it is treated specially.
A write operation to document.cookie updates only cookies mentioned in it, but
doesn’t touch other cookies.
Example :-
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies

4.1.4 Creating a cookie:-


The simplest way to create a cookie is to assign a string value to the document.cookie
object.

Gramin Polytechnic, Vishnupuri, Nanded 88


Client Side Scripting Language (Elective) - 22519

Syntax :-
document.cookie = "key1 = value1;key2 = value2;expires = date";

Here the expires attribute is optional. If you provide this attribute with a valid date or
time, then the cookie will expire on a given date or time and thereafter, the cookies' value will
not be accessible.

Example :- (JavaScript program to demonstrate creating a cookie)


<html>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script type=”text/javascript”>
function setCookie()
{
document.cookie="username=Gramin Poly";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 89


Client Side Scripting Language (Elective) - 22519

4.1.5 Deleting a cookie:-


JavaScript cookies can be deleted by using 3 ways:
 By using expires attribute.
 By using max-age attribute.
 Directly, by using the web browser.

Example :- (JavaScript program to demonstrate deleting cookie value)


<html>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<input type="button" value="Delete Cookie1" onclick="delCookie1()">
<input type="button" value="Delete Cookie2" onclick="delCookie2()">
<input type="button" value="Delete Cookie3" onclick="delCookie3()">
<script type="text/javascript">
function setCookie()
{
document.cookie="name=Gramin Poly";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not avaliable");
}
}
function delCookie1()
{
document.cookie="name=Gramin Poly; expires=Wednesday, August 07,2019 10:00
AM";

Gramin Polytechnic, Vishnupuri, Nanded 90


Client Side Scripting Language (Elective) - 22519

Example cont… :-
alert("Expiry set");
}
function delCookie2()
{
document.cookie="name=Gramin Poly;max-age=0";
alert("Max Age Set to 0");
}
function delCookie3()
{
document.cookie="name=";
alert("Directly deleted cookie");
}
</script>
</body>
</html>

4.1.5 Setting the expiration date of cookie:-


 Cookies are usually temporary, so you might want to set a precise expiry date.
 Use Expires and set a fixed expiration date.
 The date uses the HTTP date format: <day-name>, <day> <month> <year>
<hour>:<minute>:<second> GMT.

Example :-
const setCookieExpiry = new Date(2020, 8, 17);
document.cookie = “name=Gramin; expires =”+ setCookieExpiry.toUTCString() + ';';

 Use toUTCString() for converting Date() method to string.


 This function does not take any parameter. It is just used along with a Date object
created using Date() constructor whose contents are converted into a string.
 It returns the converted string according to universal time zone UTC.

Gramin Polytechnic, Vishnupuri, Nanded 91


Client Side Scripting Language (Elective) - 22519

4.2 Browser:-
 The Browser Object Model (BOM) is a browser-specific convention referring to all
the objects exposed by the web browser.
 The BOM allows JavaScript to “interact with” the browser.
 The object of window represents a browser window and all its corresponding features.
 A window object is created automatically by the browser itself.
 Java Script’s window. Screen object contains information about the user’s screen.
 It can also be written without the window prefix.
Properties one can have with browser object are as follows:
 screen.width
 screen.height
 screen.availWidth
 screen.availHeight
 screen.colorDepth
 screen.pixelDepth
4.2.1 Opening a Window:-
Window.open():-The Window interface's open() method loads the specified resource into the
new or existing browsing context (window, <iframe> or tab) with the specified name. If the
name doesn't exist, then a new browsing context is opened in a new tab or a new window,
and the specified resource is loaded into it..

Syntax:-
window.open(URL, name, specs, replace);
Parameter:-
1. URL :- Optional. Specifies the URL of the page to open. If no URL is specified,
a new window/tab with about:blank is opened.
2. name :- Optional. Specifies the target attribute or the name of the window. The
following values are supported:
 _blank - URL is loaded into a new window, or tab. This is default
 _parent - URL is loaded into the parent frame
 _self - URL replaces the current page
 _top - URL replaces any framesets that may be loaded
 name - The name of the window (Note: the name does not specify the title of the
new window)

Gramin Polytechnic, Vishnupuri, Nanded 92


Client Side Scripting Language (Elective) - 22519

Syntax cont…:-
4. specs :- Optional. A comma-separated list of items, no whitespaces. The
following values are supported:
 fullscreen=yes|no|1|0 :- Whether or not to display the browser in full-
screen mode.
 menubar=yes|no|1|0 :- Whether or not to display the menu bar.
 resizable=yes|no|1|0 :- Whether or not the window is resizable.
 scrollbars=yes|no|1|0 :- Whether or not to display scroll bars.
 status=yes|no|1|0 :- Whether or not to add a status bar.
 titlebar=yes|no|1|0 :- Whether or not to display the title bar.
 toolbar=yes|no|1|0 :- Whether or not to display the browser toolbar.
 height=pixels :- The height of the window.
 left=pixels :- The left position of the window.
 top=pixels :- The top position of the window.
 width=pixels :- The width of the window. Min. value is 100
5. replace :- Optional. Specifies whether the URL creates a new entry or replaces
the current entry in the history list. The following values are supported:
 true - URL replaces the current document in the history list.
 false - URL creates a new entry in the history list.

Example :- (JavaScript program to demonstrate Open a new window)


<html>
<head>
<title>Window Open Example</title>
</head>
<body>
<P><input type="button" value="Click Me" onclick="showPopup()" />
<script type="text/javascript">
function showPopup()
{
var oNewWin = window.open("", "_blank",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
}</script></body></html>

Gramin Polytechnic, Vishnupuri, Nanded 93


Client Side Scripting Language (Elective) - 22519

4.2.2 Giving the new window focus:-


JavaScript focus method is used to give focus to a html element. It sets the element
as the active element in the current document. It can be applied to one html element at a
single time in a current document.

Example :- (JavaScript program to demonstrate focusing on new window)


<html>
<head>
<title>Window focusing Example</title>
</head>
<body>
<P><input type="button" value="Click Me" onclick="showPopup()" />
<script type="text/javascript">
function showPopup()
{
var oNewWin = window.open("", "_blank",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
this.focus();
}
</script>
</body>
</html>

4.2.3 Window position:-


The left and top attribute of window object is used to set the position of the window
on the screen.
Example :- (JavaScript program to demonstrate set window position)
<html>
<head>
<title>Window Open Example</title>
</head>
<body>
<P><input type="button" value="Click Me" onclick="showPopup()" />
<script type="text/javascript">
function showPopup()
{
Gramin Polytechnic, Vishnupuri, Nanded 94
Client Side Scripting Language (Elective) - 22519

Example cont…:-
{
var oNewWin = window.open("", "_blank",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
this.focus();
}
</script>
</body>
</html>

4.2.4 Changing the content of window:-


There are following ways of changing the content of window:-
1. Changing the whole content of a window by using document.write().
2. Changing the content of specific element by document.getElementById().
3. Opening a new window in the same window using “_self” attribute of
window.open().

Example :- (JavaScript program to demonstrate changing window content)


<html>
<head><p id="para">This is old Window contents</p></head><br>
<input type="button" value="document.write()" onclick="showPopup1()" />
<br>
<input type="button" value="document.getElementById()" onclick="showPopup2()" />
<br>
<input type="button" value="window.open()" onclick="showPopup3()" />
<script type="text/javascript">
function showPopup1()
{
document.write("This is new content by first option");
}
function showPopup2()
{
document.getElementById("para").innerHTML="This is new content by second option";
}

Gramin Polytechnic, Vishnupuri, Nanded 95


Client Side Scripting Language (Elective) - 22519

Example cont…:-
function showPopup3()
{
var oNewWin = window.open("", "_self",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
oNewWin.document.open();
oNewWin.document.write("<html><head><title>New Window</title></head>");
oNewWin.document.write("<body>This is a new content by third option!
</body></html>");
}
</script>
</body>
</html>

4.2.5 Closing the window:-


close() method closes the current window, or the window on which it was called. This
method can only be called on windows that were opened by a script using the Window.
open() method.

Example :- (JavaScript program to demonstrate closing a window)


<html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script type=”text/javascript”>
var myWindow;
function openWin() {
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin() {
myWindow.close();
} </script> </body> </html>

Gramin Polytechnic, Vishnupuri, Nanded 96


Client Side Scripting Language (Elective) - 22519

4.2.6 Scrolling a webpage:-


There are basically two functions for scrolling horizontally or vertically on a webpage that
are:-
1. scrollTo():-The Window.scrollTo() method is used to scroll to a particular set of
coordinates in the document.

Syntax :-
window.scrollTo(x-coord, y-coord);

Parameters
 x-coord: It is the pixel along the horizontal axis of the document that is
displayed in the upper left. It is the required field.
 y-coord: It is the pixel along the vertical axis of the document that is displayed in
the upper left. It is the required field.

Example :- (JavaScript program to demonstrate scrolling on window)


<html>
<head>
<style>
body {
width: 5000px;
}
</style>
</head>
<body>
<p>Click the button to scroll the document window horizontally and vertically.</p>
<button onclick="scrollWin()">Click me to scroll horizontally!</button><br><br>
<script type=”text/javascript”>
function scrollWin() {
window.scrollTo(500, 700);
}
</script>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 97


Client Side Scripting Language (Elective) - 22519

2. scrollBy():-The window.scrollBy() method is used to scroll the document by given


number of pixels.

Syntax :-
window.scrollBy( xcoordinate, ycoordinate );

Parameters
 x-coordinate: It is the horizontal pixel value which indicates how much you
want to scroll the document (in terms of px).
 y-coordinate: It is the vertical pixel value which indicates how much you want
to scroll the document (in terms of px).

Example :- (JavaScript program to demonstrate scrollBy())


<html>
<head>
<style>
body {
width: 5000px;
}
</style>
</head>
<body>
<p>Click the button to scroll the document window by horizontally and vertically.</p>
<button onclick="scrollWin()">Click me to scroll horizontally!</button><br><br>
<script type=”text/javascript”>
function scrollWin() {
window.scrollBy(100, 200);
}
</script>
</body>
</html>

4.2.7 Multiple windows at once:-


We can open multiple windows by using multiple time window.open() and using
looping.

Gramin Polytechnic, Vishnupuri, Nanded 98


Client Side Scripting Language (Elective) - 22519

Example :- (JavaScript program to demonstrate opening multiple windows at once)


<html>
<body>
<P><input type="button" value="window.open()" onclick="showPopup()" />
<br><input type="button" value="looping" onclick="showPopup1()" />
<script type="text/javascript">
function showPopup() {
var oNewWin = window.open("", "_blank",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
var oNewWin1 = window.open("", "_blank",
"height=150,width=300,top=500,left=100,resizable=yes,menubar=yes");
}
function showPopup1() {
for(i=0;i<=2;i++)
{
var oNewWin = window.open("", "_blank",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
}
}
</script>
</body>
</html>

4.2.8 Creating a web page in new window:-


One can create a web page in new window by using document.write() of the window
object. Here instead of writing any string we have to pass the tags of HTML which we want
to use on the new window. The write function automatically converts HTML tags passed
within the document.write().

Example :- (JavaScript program to demonstrate creating a webpage on new


window)
<html>
<head>
<title>Document Open/Close Example</title>
</head>

Gramin Polytechnic, Vishnupuri, Nanded 99


Client Side Scripting Language (Elective) - 22519

Example cont…:-
<body>
<P><input type="button" value="Click Me" onclick="showPopup()" />
<script type="text/javascript">
function showPopup() {
var oNewWin = window.open("", "_blank",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
oNewWin.document.open();
oNewWin.document.write("<html><head><title>New Window</title></head>");
oNewWin.document.write("<body>This is a new window!</body></html>");
}
</script>
</body>
</html>

4.2.9 JavaScript in URLs:-


 JavaScript code can be included on the client side is in a URL following the
javascript: pseudo-protocol specifier.
 This special protocol type specifies that the body of the URL is arbitrary JavaScript
code to be interpreted by the JavaScript interpreter.
 If the JavaScript code in a javascript: URL contains multiple statements, the
statements must be separated from one another by semicolons.
 Such a URL might look like the following:
javascript:var now = new Date(); " <h1>The time is “</h1>”+now
 When the browser "loads" one of these JavaScript URLs, it executes the JavaScript
code contained in the URL and displays the "document" referred to by the URL.
 This "document" is the string value of the last JavaScript statement in the URL. This
string will be formatted and displayed just like any other document loaded into the
browser.
 In some contexts, the javascript: URL is essentially a substitute for an event-handler.
Event handlers and javascript: URLs can often be used essentially interchangeably,
and which you choose is basically a stylistic matter. There are a few circumstances
where a javascript: URL can be used with objects that do not support event handlers.

Gramin Polytechnic, Vishnupuri, Nanded 100


Client Side Scripting Language (Elective) - 22519

4.2.10 JavaScript security:-


JavaScript vulnerabilities can be both client-side problems and server-side as well as
hackers are able to steal server-side data and infect the users with malware. Hackers can
potentially harm your business by taking various paths through your application. These
threats need to be evaluated and dealt with, one way or the other. Some of the Security
Vulnerabilities with JavaScript are as follows:-
1. Cross –Site Scripting (XSS):- One of the most common application vulnerability
in a web application is cross-site scripting (XSS). XSS issues occur when an
application takes unreliable data and pass it to the browser without apt validation.
This allows attacker to run malicious scripts in the browser of the host. XSS attacks
have the potential to cause serious hazard to company and its accounts. This may
result in identity and data theft. Execution of XSS attacks, can cause spreading of
viruses throughout company network, accessing clipboard data, browsing histories
and even gain remote control of browsers which causes other vulnerabilities and XSS
attacks.
2. Cross-Site Request Forgery (CSFR) :- Cross-Site Request Forgery (CSRF) which
is pronounced as ‘sea- surf’ allows logging into victim’s browser to make a forged
HTTP request. Also, it allows victim’s session cookie (alongwith other automatically
included access information) available to a vulnerable-web-application. This gives the
hacker the permission to force the victim’s browser to generate requests; next, the-
vulnerable-application believes it as a legal request arising from victim’s end. But
actually it is not. The risks which are associated with CSRF attacks includes
modification of application data by using victim’s credentials and permissions,
launching organized attacks against all of the application’s users imitation and
identity riding, framing someone innocent, misuse of vulnerable DSL routers and
much more.
3. Client-side Logic and Data Storage:- In the beginning, JavaScript performance
and capabilities were largely restricted. Since JS engines are faster with iterations of
browser release it is very much possible to perform considerable processing on the
client-side. This tempts developers to place/perform sensitive operations to the client-
side. Since this is sometimes unavoidable in some situations, this may be intended to
unload processing to the client-side in order to save bandwidth and server-time.

Gramin Polytechnic, Vishnupuri, Nanded 101


Client Side Scripting Language (Elective) - 22519

4. Server-side JavaScript Injection (SSJI):- Well, as client-side XSS is definitely a


problem, therefore, server-side JavaScript injection is also a much more dangerous
problem in an application. SSJI is among one of the most crippling web application
vulnerabilities on the web today.

4.2.11 Timers:-
A timer is a function that enables us to execute a function at a particular time. Using timers
you can delay the execution of code so that it does not get done at the exact moment an event
is triggered or the page is loaded. For example, you can use timers to change the
advertisement banners on your website at regular intervals, or display a real-time clock, etc.
There are two timer functions in JavaScript:
1. setTimeout():-
 The setTimeout() function is used to execute a function or specified piece of code just
once after a certain period of time.
 Its basic syntax is setTimeout(function, time).
 This function accepts two parameters: a function, which is the function to execute,
and an optional delay time parameter, which is the number of milliseconds
representing the amount of time to wait before executing the function (1 second =
1000 milliseconds).
Example:- (JavaScript program to demonstrate setTimeout())
<html>
<input type="button" value="click me" onclick="myFunction()">
<script type="text/javascript">
function myFunction()
{
setTimeout(dispFunction, 2000);
}
function dispFunction()
{
alert(“Hello World!”);
}
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 102


Client Side Scripting Language (Elective) - 22519

2. setInterval():-
 The setInterval() function is used to execute a function or specified piece of code
repeatedly at fixed time intervals.
 Its basic syntax is setInterval(function, time).
 This function also accepts two parameters: a function, which is the function to
execute, and interval, which is the number of milliseconds representing the amount of
time to wait before executing the function (1 second = 1000 milliseconds).

Example:- (JavaScript program to demonstrate sInterval())


<html>
<input type="button" value="click me" onclick="myFunction()">
<p id="p1"></p>
<script type="text/javascript">
function myFunction()
{
setInterval(dispFunction, 1000);
}
function dispFunction()
{
document.getElementById("p1").innerHTML+="<br>Hello World!";
}
</script>
</html>

• Both setTimeout() and setInterval() method return an unique ID (a positive integer


value, called timer identifier) which identifies the timer created by the these methods.
• This ID can be used to disable or clear the timer and stop the execution of code
beforehand. Clearing a timer can be done using two functions: clearTimeout() and
clearInterval().
4.2.12 Browser Location and History:-
Location Object:-
 The location object in JavaScript helps in storing the information of current URL of
the window object. It is a child object of the window object.

Gramin Polytechnic, Vishnupuri, Nanded 103


Client Side Scripting Language (Elective) - 22519

 Properties associated with location object are as follows:-


Property Description Example

Window.location.protocol represents a string at the http: or https:


beginning of a URL up to the
first colon (:), which specifies
the method of access to the
URL
Window.location.host represents a string consisting of google.com:80
the hostname and port strings
Window.location.hostname represents the server name, google.com
subdomain, and domain name
of a URL
Window.location.port represents a string specifying 80
the communications port that
the server uses
Window.location.pathname represents a string portion of a abc.php
URL specifying how a
particular resource can be
accessed
Windows.location.href represents a string specifying http://google.com:80?abc.
the entire URL php?id=1#start

 Methods associated with location object are as follows:-


Method Description

assign() Loads a new document in the browser


reload() reloads the current document that is contained in the location.href
property
replace() replaces the current document with the specified new one, you cannot
navigate back to the previous document using the browser's Back
button

Gramin Polytechnic, Vishnupuri, Nanded 104


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate location object of window)


<html>
<input type="button" value="click me" onclick="myFunction()">
<script type="text/javascript">
function myFunction()
{
document.write("<br>Protocol "+window.location.protocol);
document.write("<br>Host "+window.location.host);
document.write("<br>Hostname "+window.location.hostname);
document.write("<br>Port "+window.location.port);
document.write("<br>Pathname "+window.location.pathname);
document.write("<br>Href "+window.location.href);
}
</script>
</html>

History Object:-
 The History object is a predefined object in JavaScript that consists of an array of
URLs, which are visited by a user in the browser.
 Properties associated with history object are as follows:-
Properties Description

Window.history.length specifies the number of elements contained in the object


Window.history.current specifies the URL of the current entry in the object
Window.history.next specifies the URL of the next element in the History list
Window.history.previous specifies the URL of the previous element in the History list

 Methods associated with location object are as follows:-


Methods Description

back() specifies a method that loads the previous URL from the history list
forward() specifies a method that loads the next URL from the history list
go() specifies a method that loads a specific URL from the history list

Gramin Polytechnic, Vishnupuri, Nanded 105


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate history object of window)


<html>
<head>
<title>JavaScript History Object</title>
<script type="text/javascript">
function dispCount()
{
var historyCount = history.length;
alert("Hi, you have visited " + historyCount + " web pages so far.");
}
</script>
</head>
<body>
<h3>JavaScript History Object Example</h3>
<form>
<input type="button" name="history" value="My History" onclick="dispCount()">
</form>
</body>
</html>

Question Bank:-
Remember Level:-
1. What is a cookie?
2. Enlist the JavaScript security issues. Explain any 1 of them.
3. What are timers in JavaScript?
4. Enlist and describe the properties of window location.
Understand Level:-
1. How to create cookie. Explain with an example.
2. How to delete a cookie. Explain with an example.
3. How to set expiration date to a cookie. Explain with an example.
4. How to open a window? Describe various styles of window.

Gramin Polytechnic, Vishnupuri, Nanded 106


Client Side Scripting Language (Elective) - 22519

5. How to change the content of a window? Explain with an example.


6. How to scroll a window? Explain with an example.
7. How to create a webpage in new window? Explain with an example.
8. How JavaScript’s is used in URLs?
9. Write the syntax of and explain use of following methods of JavaScript Timing Event
with an example. a). setTimeout() b). setInterval()
10. Explain the History object with an example.
Apply Level:-
1. Write a JavaScript program to read a cookie value.
2. Write a JavaScript program to write a cookie value.
3. Write a JavaScript program to open a new window.
4. Write a JavaScript program to the focus to a window.
5. Write a JavaScript program to set position of a window.
6. Write a JavaScript program to close a window.
7. Write a JavaScript program to open multiple windows.
8. Write a JavaScript program to get Pathname, Hostname& Protocol.

Gramin Polytechnic, Vishnupuri, Nanded 107


Client Side Scripting Language (Elective) - 22519

Unit 5
Regular Expression, Rollover and Frames – [08 hours]
[14 Marks- R = 02, U = 06, A = 06]
Syllabus: -
5.1 Regular Expression: Language of regular expression, Finding non-matching
characters, Entering range of characters, Matching digits and non-digits, Matching
punctuations and symbols, Matching words, Replacing a text using regular expression,
Returning the matched characters, Regular expression and object properties.
5.2 Frames: Create a frame, Invisible borders of frame, Calling a child windows,
Changing the content and focus of child window, Accessing elements of another child
window.
5.3 Rollover: Creating rollover, Text rollover, Multiple actions for rollover, More
efficient rollover.

Unit Outcomes (UO’s): -


5a. Compose relevant regular expression for the given character pattern search.
5b. Develop JavaScript to implement validation using the given regular expression.
5c. Create frames based on the given problem.
5d. Create window object as per the given problem.
5e. Develop JavaScript for creating rollover effect for the given situation.

5.1 Regular Expression:-


A regular expression is a sequence of characters that forms a search pattern. The
search pattern can be used for text search and text replace operations. A regular expression
can be a single character, or a more complicated pattern. Regular expressions can be used to
perform all types of text search and text replace operations.
Syntax :-
/pattern/modifiers;
Parameters
 pattern − A string that specifies the pattern of the regular expression or another
regular expression.
 modifiers − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multi-line matches, respectively.

Gramin Polytechnic, Vishnupuri, Nanded 108


Client Side Scripting Language (Elective) - 22519

Example :- (JavaScript program to demonstrate regular expression)


<html>
<input type="text" id="tx1"><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{
var str=tx1.value;
var chkPtrn=/poly/i;
if(chkPtrn.test(str))
{
alert("String contains the given pattern");
}
else
{
alert("String does not contains the given pattern");
}
}
</script>
</html>

5.1.1 Language of Regular Expression:-


When we create a set of word by using the different patterns of the regular expression
in JavaScript it is known as language of regular expression. Following are some of the
patterns available:
1. Brackets:-
Brackets ([]) have a special meaning when used in the context of regular expressions.
They are used to find a range of characters.
Expression Description

[...] Any one character between the brackets.


[^...] Any one character not between the brackets.

Gramin Polytechnic, Vishnupuri, Nanded 109


Client Side Scripting Language (Elective) - 22519

[0-9] It matches any decimal digit from 0 through 9.


[a-z] It matches any character from lowercase a through lowercase z.
[A-Z] It matches any character from uppercase A through uppercase Z.
[a-Z] It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any
decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character
ranging from b through v.
2. Qualifiers:-
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character has a specific connotation. The +, *, ?,
and $ flags all follow a character sequence.
Expression Description

p+ It matches any string containing one or more p's


p* It matches any string containing zero or more p's.
p? It matches any string containing at most one p.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.

3. Metacharacters:-
 A metacharacter is simply an alphabetical character preceded by a backslash that acts
to give the combination a special meaning.
 For instance, you can search for a large sum of money using the '\d' metacharacter:
/([\d]+)000/, Here \d will search for any string of numerical character.
Expression Description

. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
\d a digit (0-9)

Gramin Polytechnic, Vishnupuri, Nanded 110


Client Side Scripting Language (Elective) - 22519

\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[\b] a literal backspace (special case).
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given set
\t a tab character
\n a newline character
\v a vertical tab

Properties of Regular expression:-


Property Description
constructor Specifies the function that creates an object's prototype.
global Specifies if the "g" modifier is set.

ignoreCase Specifies if the "i" modifier is set.

lastIndex The index at which to start the next match.


multiline Specifies if the "m" modifier is set.
source Returns the text of the pattern.

Methods of Regular Expression:-


Method Description
exec() Executes a search for a match in a string. It returns an array of information or
null on a mismatch.

test() Tests for a match in a string. It returns true or false.


match() Returns an array containing all of the matches, including capturing groups, or
null if no match is found.

matchAll() Returns an iterator containing all of the matches, including capturing groups.
search() Tests for a match in a string. It returns the index of the match, or -1 if the
search fails.
replace() Executes a search for a match in a string, and replaces the matched substring
with a replacement substring.

Gramin Polytechnic, Vishnupuri, Nanded 111


Client Side Scripting Language (Elective) - 22519

split() Uses a regular expression or a fixed string to break a string into an array of
substrings.
In JavaScript, a caret (^) may be used to indicate the beginning of the string, while a
dollar sign ($) is used to mark the end.
5.1.2 Finding Non-matching characters:-
Example :- (JavaScript program to demonstrate finding non-matching characters)
<html>
<input type="text" id="tx1"><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{
var str=tx1.value;
var chkPtrn=/[^xyz]/;
if(chkPtrn.test(str))
{
alert("String contains character other than x,y,z");
}
else
{
alert("String does not contains character other than x,y,z");
}
}
</script>
</html>

5.1.3 Entering the range of characters:-


Example :- (JavaScript program to demonstrate checking range of character)
<html>
<input type="text" id="tx1"><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{

Gramin Polytechnic, Vishnupuri, Nanded 112


Client Side Scripting Language (Elective) - 22519

Example cont…:-
var str=tx1.value;
var chkPtrn=/[a-z]/;
if(chkPtrn.test(str))
{
alert("String contains character in the range");
}
else
{
alert("String doesn’t contains character in the range");
}
}
</script>
</html>

5.1.4 Matching Digits and Non-digits:-


Example:- (JavaScript program to demonstrate matching digits and non-digits)
<html>
<input type="text" id="tx1"><br>
<input type="button" value="chkDigit" onclick="check()">
<br>
<input type="button" value="chkNonDigit" onclick="check1()">
<script type="text/javascript">
function check() //function for Digit
{
var str=tx1.value;
var chkPtrn=/\d/;
if(chkPtrn.test(str))
{
alert("Entered value id a digit");
}
else
{
alert("Entered value is non digit");
Gramin Polytechnic, Vishnupuri, Nanded 113
Client Side Scripting Language (Elective) - 22519

Example cont…:-
alert("Entered value is non-digit");
}
}
function check1() //function for Non-digit
{
var str=tx1.value;
var chkPtrn=/\D/;
if(chkPtrn.test(str))
{
alert("Entered value is non-digit");
}
else
{
alert("Entered value id a digit");
}
}
</script>
</html>

5.1.5 Matching Punctuations and Symbols:-


Regular expression patterns include the use of letters, digits, punctuation marks, etc.,
plus a set of special regular expression characters.
The characters that are given special meaning within a regular expression, are:
. * ? + [ ] ( ) { } ^ $ | \. You will need to backslash these characters whenever you want to use

them literally. For example, if you want to match ".", you'd have to write \.. All other
characters automatically assume their literal meanings.
Example:- (JavaScript program to demonstrate matching punctuations and
symbols)
<html>
<input type="text" name="tx1">
<input type="submit" value="check" onclick="check()">
<script type="text/javascript">

Gramin Polytechnic, Vishnupuri, Nanded 114


Client Side Scripting Language (Elective) - 22519

Example cont…:-
function check()
var email=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-z])+$/;
if(tx1.value.match(email))
{
alert("valid mail id");
}
else
{
alert("invalid mail id");
}
}
</script>
</html>
5.1.6 Matching Words:-
match() is an inbuilt function in JavaScript which is used to search a string for a
match against a any regular expression and if the match will found then this will return the
match as an array. Parameters: Here the parameter is “regExp” i.e, regular expression which
will compare with the given string.

Example: - (JavaScript program to demonstrate matching words)


<html>
<input type="text" id="tx1"><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{
var str=tx1.value;
var chkPtrn=/poly/i;
if(str.match(chkPtrn))
{
alert("String contains the given pattern");
}

Gramin Polytechnic, Vishnupuri, Nanded 115


Client Side Scripting Language (Elective) - 22519

Example cont…:-
else
{
alert("String does not contains the given pattern");
}
}
</script>
</html>

5.1.7 Replacing a Text Using Regular Expression:-


The replace() method searches a string for a specified value, or a regular
expression, and returns a new string where the specified values are replaced. Note: If you
are replacing a value (and not a regular expression), only the first instance of the value will
be replaced.

Example:- (JavaScript program to demonstrate replacing text)


<html>
<input type="text" id="tx1" value="Gramin Poly Nanded"><br><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{
a=tx1.value;
b=a.replace("Poly","Engg");
tx1.value=b;
}
</script>
</html>

5.1.8 Returning a matched character:-


1. The string.match() is an inbuilt function in JavaScript which is used to search a
string for a match against an any regular expression and if the match will found then this will
return the match as an array.

Gramin Polytechnic, Vishnupuri, Nanded 116


Client Side Scripting Language (Elective) - 22519

2. The search() method uses an expression to search for a match, and returns the
position of the match.

Example: - (JavaScript program to demonstrate returning matching character –


search())
<html>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{
a="Gramin Poly Nanded";
alert(a);
b=a.search("Poly");
alert(b);
}
</script>
</html>
3. The exec() method executes a search for a match in a specified string. Returns a result
array, or null.

Example:- (JavaScript program to demonstrate returning matching character-


exec())
<html>
<input type="text" id="tx1" value="Gramin Poly Nanded"><br><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{
a=tx1.value;
var patt = new RegExp("Poly");
var res = patt.exec(a);
alert(res);
}
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 117


Client Side Scripting Language (Elective) - 22519

5.1.9 Regular Expression and Object Properties:-


A regular expression is a sequence of characters that forms a search pattern. The
search pattern can be used for text search and texts replace operations. A regular expression
can be a single character, or a more complicated pattern. Regular expressions can be used to
perform all types of text search and texts replace operations.
Syntax :-
/pattern/modifiers;
Parameters
 pattern − A string that specifies the pattern of the regular expression or another
regular expression.
 modifiers − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multi-line matches, respectively.

Properties of Regular expression:-


Property Description
constructor Specifies the function that creates an object's prototype.
global Specifies if the "g" modifier is set.

ignoreCase Specifies if the "i" modifier is set.

lastIndex The index at which to start the next match.


multiline Specifies if the "m" modifier is set.
source Returns the text of the pattern.

Example:- (JavaScript program to demonstrate properties of regular expression)


<html>
<head>
<title>JavaScript RegExp constructor Property</title>
</head>
<body>
<script type = "text/javascript">
var re = new RegExp( "string" );
document.write("re.constructor is:" + re.constructor);
</script>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 118


Client Side Scripting Language (Elective) - 22519

5.2 Frames:-
 Frames are a special case in JavaScript — each frame behaving like the separate
document that it is.
 This means that to modify anything in another frame, you first need to gain control of
this frame by working with something called the frame tree.
 The frame element allows authors to insert more than one HTML document into a
browser window. It must be within a frameset element.
 When a window contains multiple frames, each frame is represented in JavaScript by
a frame object.
 This object is equivalent to a window object, but it is used for dealing with that frame.
The frame object's name is the same as the NAME attribute you give it in the <frame>
tag.
5.2.1 Create a Frame:-
To use frames on a page we use <frameset> tag instead of <body> tag. The
<frameset> tag defines how to divide the window into frames. The rows attribute of
<frameset> tag defines horizontal frames and cols attribute defines vertical frames. Each
frame is indicated by <frame> tag and it defines which HTML document shall open into the
frame.
Attributes of Frameset tag:
Attribute Description Example
cols The cols attribute is used to create 1. Use absolute value in pixel
<frameset cols = "300, 400, 300">
vertical frames in web browser. This
2. Use percentage value
attribute is basically used to define the
<frameset cols = "30%, 40%,
no of columns and its size inside the
30%">
frameset tag.
3.Use wild card values:
<frameset cols = "30%, *, 30%">
rows The rows attribute is used to create 1. Use absolute value in pixel
<frameset rows = "300, 400,
horizontal frames in web browser. This
300">
attribute is used to define no of rows and
2. Use percentage value
its size inside the frameset tag.
<frameset rows = "30%, 40%,
30%">

Gramin Polytechnic, Vishnupuri, Nanded 119


Client Side Scripting Language (Elective) - 22519

3.Use wild card values:


<frameset rows = "30%, *, 30%">
border This attribute of frameset tag defines the <frameset border="4" frameset>
width of border of each frame in pixels.
Zero value is used for no border.
framespacing This attribute of frameset tag is used to <framespacing="20">
specify the amount of spacing between
It means there will be 20 pixel
the frames in a frameset. This can take
spacing between the frames
any integer value as an parameter which
basically denotes the value in pixel.

Attributes of Frame tag


Attribute Description Example
name This attribute is used to give names to <frame name = "top" src =
the frame. It differentiates one frame "C:/Users/abc/Desktop/attr1.png"
from another. It is also used to indicate />
which frame a document should loaded
into.
src This attribute in frame tag is basically <frame name = "left" src =
used to define the source file that should "/html/left.htm" />
be loaded into the frame. The value of
src can be any url.
marginwidth This attribute in frame tag is used to <frame marginwidth="20">
specify width of the spaces in pixels
between the border and contents of left
and right frame.
marginheight This attribute in frame tag is used to <frame marginheight="20">
specify height of the spaces in pixels
between the border and contents of top
and bottom frame.
scrollbar To control the appearance of scroll bar <frame scrollbar="no">
in frame use scrollbar attribute in frame
tag. This is basically used to control the

Gramin Polytechnic, Vishnupuri, Nanded 120


Client Side Scripting Language (Elective) - 22519

appearance of scrollbar. The value of


this attribute can be yes, no, auto.
Where the value no denotes there will
be no appearance of scroll bar.
frameborder This attribute of frameset tag is used to < frameborder=1>
specify whether the three-dimensional
border should be displayed between the
frames or not for this use two values 0
and 1, where 0 defines for no border
and value 1 signifies for yes there will
be border.

Example:- (JavaScript program to demonstrate frames)


<html>
<frameset cols = "30%,40%,30%" frameborder="1">
<frame name = "top" src = "D:\Example\arrayByConstructor.html" />
<frame name = "main" src = "D:\Example\checkBox.html" />
<frame name = "bottom" src = "D:\Example\demo1.html" />
</frameset>
</html>

5.2.2 Invisible Borders of Frame:-


frameborder attribute of frameset tag is used to specify whether the three-
dimensional border should be displayed between the frames or not for this use two values 0
and 1, where 0 defines for no border and value 1 signifies for yes there will be border.

Example:- (JavaScript program to demonstrate invisible borders of frames)


<html>
<frameset cols = "30%,40%,30%" >
<frame name = "top" frameborder="0"/>
<frame name = "main" frameborder="0"/>
<frame name = "bottom" frameborder="0"/>
</frameset>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 121


Client Side Scripting Language (Elective) - 22519

5.2.3 Calling a Child Window:-


 Frame is partition of window into many windows. It is useful when we want to keep
things separate from other windows.
 Frame helps us to include header or footer or menu navigator in left or right side.
 We need to interact with other frames with JavaScript function.
 Every frame is parent or child of parent. Every frame has own id and frame name
which differentiate one frame to other frames.
 We denote frame as child or parent. This makes it easy to access other frame from
frame to frame.

Example:- (Parent Frame)


<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset>
</html>

Example: - (Child Frame1)


<html>
<body>
<input type="button" value="click" onclick="parent.frame2.disp()"/>
</body>
</html>

Example: - (Child Frame2)


<html>
<script type="text/javascript">
function disp()
{
document.write("This function is called from Frame1");
}
</script>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 122


Client Side Scripting Language (Elective) - 22519

5.2.4 Changing the Content and Focus of Child Window:-


The content and focus of child window can be changed from another child window.
This can be done by changing the source file for the particular by using JavaScript.

Example:- (Parent Frame)


<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset>
</html>

Example:- (Child Frame1)


<html>
<body>
<input type="button" value="click" onclick="disp()"/>
<script type="text/javascript">
function disp()
{
parent.frame2.location.href="d:\\ child3.html";
}
</script>
</body>
</html>

Example:- (Child Frame2)


<html>
<h1>Frame2</h2>
</html>

Example:- (Child Frame3)


<html>
<h1>Content & focus changed from child2 to child3</h2>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 123


Client Side Scripting Language (Elective) - 22519

5.2.5 Accessing the Elements of other Child Window:-


One can change access the elements of one child window from another by getting the
ID of the element used.

Example:- (Parent Frame)


<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset>
</html>

Example:- (Child Frame1)


<html>
<body>
<input type="button" value="click" onclick="disp()"/>
<script type="text/javascript">
function disp()
{
parent.frame2.document.getElementById("p1").innerHTML="Element is accessed by
frame 2";
}
</script>
</body>
</html>

Example:- (Child Frame2)


<html>
<h1>Frame2</h2>
<p id="p1"> Frame 2 contents</p>
</html>

5.3 Rollover:-
 Rollover is a JavaScript technique used by Web developers to produce an effect in
which the appearance of a graphical image changes when the user rolls the mouse
pointer over it.

Gramin Polytechnic, Vishnupuri, Nanded 124


Client Side Scripting Language (Elective) - 22519

 Rollover also refers to a button on a Web page that allows interactivity between the
user and the Web page. It causes the button to react by either replacing the source
image at the button with another image or redirecting it to a different Web page.
 Rollover is triggered when the mouse moves over the primary image, causing the
secondary image to appear. The primary image reappears when the mouse is moved
away.
 Occasionally, rollover is referred to as synonym for mouseover.
 Rollover can be accomplished using text, buttons or images, which can be made to
appear when the mouse is rolled over an image. The user needs two images/buttons to
perform rollover action.
5.3.1 Creating Rollover:-
 The keyword that is used to create rollover is the <onmousover> event.
 “Rollover means a webpage changes when the user moves his or her mouse over an
object on the page” when the user moves his or her mouse away.

Example:- (JavaScript program to demonstrate rollover)


<html>
<body>
<img src="D:\Tulips.jpg" boarder="0px" width="300px" height="200px"
onmouseover="this.src='D:\Desert.jpg';" onmouseout="this.src='D:\Penguins.jpg';" />
</body>
</html>

5.3.2 Text Rollover:-


 The keyword that is used to create rollover is the <onmousover> event.
 For example, we want to create a rollover text that appears in a text area. The text
“What is rollover?” appears when the user place his or her mouse over the text area
and the rollover text changes to “Rollover means a webpage changes when the user
moves his or her mouse over an object on the page” when the user moves his or her
mouse away from the text area.

Example:- (JavaScript program to demonstrate Text rollover)


<html>
<body>
<textarea rows="2" cols="50" name=rollovertext" onmouseover="this.value='What is

Gramin Polytechnic, Vishnupuri, Nanded 125


Client Side Scripting Language (Elective) - 22519

Example cont.…:-
text rollover?';" onmouseout="this.value='Rollover means changes when the user moves
the mouse on the page';"></textarea>
</body></html>

5.3.3 Multiple actions for Rollover:-


One can perform multiple actions on the rollover event of mouse like displaying
image and displaying text for that image.
Example:- (JavaScript program to demonstrate multiple actions on rollover)
<html>
<body>
<a href="" onmouseover="disp()"> Tulip</a>
<br><br>
<img src="" name="im1" width="200" height="200">
<br><br>
<p id="p1">Description of Flower</p>
<script type="text/javascript">
function disp()
{
document.im1.src="D:\Tulips.jpg";
document.getElementById("p1").innerHTML="This is Tulip Flower";
}
</script>
</body>
</html>

5.3.4 More efficient Rollover:-


 An event is an important part of JavaScript. A web page respond according to an
event occurred. Some events are user generated and some are generated by API’s.
 An event listener is a procedure in JavaScript that waits for an event to occur. The
simple example of an event is a user clicking the mouse or pressing a key on the
keyboard.
 The addEventListener() is an inbuilt function in JavaScript which takes the event to
listen for, and a second argument to be called whenever the described event gets fired.

Gramin Polytechnic, Vishnupuri, Nanded 126


Client Side Scripting Language (Elective) - 22519

Any number of event handlers can be added to a single element without overwriting
existing event handlers.

Syntax:-
element.addEventListener(event, listener);

Parameters:
 event : event can be any valid JavaScript event.Events are used without “on”
prefix like use “click” instead of “onclick” or “mousedown” instead of
“onmousedown”.
 listener(handler function) : It can be a JavaScript function which respond to the
event occur

Example:- (JavaScript program to demonstrate event listener)


<html>
<body>
<p id="p1">More rollover example</p>
<br><br>
<button id="bt1">Click</button>
<script type="text/javascript">
document.getElementById("bt1").addEventListener("click",disp);
function disp()
{
document.getElementById("p1").innerHTML="Event generated by event listener";
}
</script>
</body>
</html>

Question Bank:-
Remember Level:-
1. What is regular expression?
2. Write down procedure of returning a matched character in JavaScript.
3. Enlist and explain the regular expression and object properties.

Gramin Polytechnic, Vishnupuri, Nanded 127


Client Side Scripting Language (Elective) - 22519

4. What is Frame?
5. What is rollover?
6. What is text rollover?
Understand Level:-
1. Explain the language of regular expression.
2. How to find non-matching characters in a given text? Explain with an example.
3. How to match digits and non-match digits? Explain with an example.
4. How to match punctuations and symbols? Explain with an example.
5. How to match words? Explain with an example.
6. How to create frames also explain the attributes of Frameset and Frame tag.
7. How to set the border of the frame invisible? Explain with an example.
8. How to call a child window? Explain with an example.
9. How to change the content and focus of child window? Explain with an example.
10. How to access the elements of child window from another child window? Explain
with an example.
11. How to perform multiple actions by using rollover? Explain with example.
Apply Level:-
1. Write a JavaScript program to check whether the string contains the give pattern or
not.
2. Write a JavaScript program to match a character in a range of characters.
3. Write a JavaScript program to replace a text using regular expression.
4. Write a JavaScript program to use constructor property of RegExp object.
5. Write a JavaScript program to create a Frame using cols 20%,50%, 30%.
6. Write a JavaScript program to create a Frame using rows 20%,50%, 30%.
7. Write a JavaScript program to create multiple frames in a webpage in matrix form.
8. Write a JavaScript program to load webpages in each frame.
9. Write a JavaScript program to create rollover.
10. Write a JavaScript program to create text rollover.
11. Write a JavaScript program to perform more efficient rollover operation.

Gramin Polytechnic, Vishnupuri, Nanded 128


Client Side Scripting Language (Elective) - 22519

Unit 6
Menus Navigation and Web Page Protection – [08 hours]
[12 Marks- R = 02, U = 04, A = 06]
Syllabus: -
6.1 Status Bar: Builds a static message, Changing the message using rollover, Moving the
message along the status bar.
6.2 Banner: Loading and displaying banner advertisement, Linking a banner
advertisement to URL.
6.3 Slide Show: Creating a slide show.
6.4 Menus: Creating a pull down menu, Dynamically changing the menu, Validating a
menu selection, Floating menu, Chain select menu, Tab menu, Sliding menu, Highlighted
menu, Folding a tree menu, Context menu, Scrollable menu, Side bar menu.
6.5 Protecting web page: Hiding your code, Disabling the right mouse button, JavaScript,
Concealing email address.
6.6 Framework of JavaScript and its application.
Unit Outcomes (UO’s): -
6a. Develop JavaScript to manage the given status bar.
6b. Develop JavaScript to create the given banner.
6c. Develop JavaScript to create the given slide show.
6d. Develop JavaScript to create the given Menu.
6e. Write JavaScript to protect a webpage in the specified manner.

6.1 Status Bar:-


A status bar is located at the bottom of Internet browser windows and many
application windows and displays the current state of the web page or application being
displayed. For example, in early versions of Internet Explorer, it showed whether the page
was secure, its certificate, what was currently being loaded on the page, and the web address.
6.1.1 Build Static Message:-
In JavaScript a static message is built with the status property of window object.
Example:- (JavaScript program to demonstrate build static mesage)
<html>
<body>
<h3>Static message example</h3> <br><br>
<button id="bt1">Click</button>
Gramin Polytechnic, Vishnupuri, Nanded 129
Client Side Scripting Language (Elective) - 22519

Example cont…:-
<script type="text/javascript">
window.status="This is status bar example";
</script>
</body>
</html>

This property is not supported by modern browsers so it will now display static message.

6.1.2 Changing the message using Rollover:-


We will use onMouseOver and onMouseOut events of a hyper link to display or
manage the messages.
Example: - (JavaScript program to demonstrate changing message using rollover)
<html>
<head>
<title>JavaScript Status Bar</title></head>
<body>
<a ref="http://www.google.com" onMouseOver="window.status='HTMLcenter';return
true" onMouseOut="window.status='';return true">
HTML center
</a>
</body>
</html>

6.1.3 Moving the message along the Status Bar:-


We can move a message in status bar by assigning the spaces and the message to the
status bar in time interval. If we set the messages with increasing spaces in start of message,
and assigning the message in time interval after some milliseconds, then it looks like the
message is moving along the status bar.

Gramin Polytechnic, Vishnupuri, Nanded 130


Client Side Scripting Language (Elective) - 22519

Example: - (JavaScript program to demonstrate moving message along the status


bar)
<html>
<head>
<script>
var scrollPos=0;
var maxScroll=100;
var blanks=””;
function scrollText(text,milliseconds)
{
window.setInterval(“displayText(“’+text+’”)”,milliseconds);
}
function displayText(text)
{
window.defaultStatus=blanks+text;
++scrollPos;
blanks+=””;
if(scrollPos>maxScroll)
{
scrollPos=0;
blanks=””;
}
}
</script>
</head>
<body onload=”scrollText(‘Welcome to JavaScript’,300)”>
<p> Watch the text scroll at the bottom of this window</p>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 131


Client Side Scripting Language (Elective) - 22519

6.2. Banner:-
Rotating banners ads comprises several banner images that constantly rotate on a
webpage at a fix time interval. You can create these banner images using standard graphics
tools. Let’s create four banner images and name them as banner1.jpg, banner2.jpg,
banner3.jpg and banner4.jpg
6.2.1. Loading and Displaying the Banner Advertisement:-
The JavaScript starts by declaring an array to store the banner images using the new Array
keywords, as follows:
MyBanners=new Array(‘banner1.jpg’,’banner2.jpg’,’banner3.jpg’,’banner4.jpg’);
Each element in the array is assigned with an index, starting from 0. In our example,
banner1.jpg is assigned with index 0, banner2.jpg is assigned with index 1, banner3.jpg is
assigned with index 2 and banner3.jpg is assigned with index 3.

Example: - (JavaScript program to demonstrate banner)


<html>
<head>
<script language="Javascript">
MyBanners=new
Array('D:\\Images\\Chrysanthemum.jpg','D:\\Images\\Hydrangeas.jpg');
banner=0;
function ShowBanners()
{
if (document.images)
{
banner++;
if (banner==MyBanners.length)
{
banner=0;
}
document.ChangeBanner.src=MyBanners[banner];
setTimeout("ShowBanners()",1000);
}
}
</script>

Gramin Polytechnic, Vishnupuri, Nanded 132


Client Side Scripting Language (Elective) - 22519

Example cont…:-
</script>
<body onload="ShowBanners()">
<center>
<img src="D:\Images\Desert.jpg" width="900" height="120" name="ChangeBanner"/>
</center>
</body>
</html>

6.2.2. Linking a Banner Advertisement to URL:-


 Creating rotating banner images will provide the visitor to your webpage with some
basic information. However, if you want the visitor to get more information
by clicking on the banner images, you need to create rotating banner ads that contain
URL links.
 The JavaScript is basically the same as the previous one but we need to add another
array that comprises the links, as follows:
MyBannerLinks=new Array('URL1','URL2','URL3/','URL4/')
 You need to make sure that the arrangement of the links is in corresponding order
with the banner images in the first array. Next, we create the ShowLinks function to
link the current banner image to the relevant URL and then assign the URL to the href
attribute of the anchor tag.
 To load the banner images with URL links, we insert an anchor tag within the
<body></body> section before the <img> tag that displays the current banner image.
The anchor tag's attribute href is used to call the ShowLinks( ) function when the
visitor clicks on the banner.
Example:- (JavaScript program to demonstrate linking banner URLs)
<html>
<head>
<script language="Javascript">
MyBanners=new Array('D:\\Images\\Desert.jpg','D:\\Images\\Hydrangeas.jpg');
MyBannerLinks=new Array('http://www.vbtutor.net/','http://www.excelvbatutor.com/');
banner=0;

Gramin Polytechnic, Vishnupuri, Nanded 133


Client Side Scripting Language (Elective) - 22519

Example cont..:-
function ShowLinks()
{
document.location.href=MyBannerLinks[banner];
}
function ShowBanners()
{
if (document.images)
{
banner++;
if (banner==MyBanners.length)
{
banner=0;
}
document.ChangeBanner.src=MyBanners[banner];
setTimeout("ShowBanners()",1000);
}
}
</script>
<body onload="ShowBanners()">
<center>
<a href="javascript: ShowLinks()">
<img src="D:\Images\Chrysanthemum.jpg" width="900" height="120"
name="ChangeBanner"/></a>
</center>
</body>
</html>

6.3. Slide Show:-


6.3.1 Creating a Slide Show:-
 To create the JavaScript slideshow, first of all, you need to create a few banner
images using some graphics tools, or you can snap some photos with your digital
camera or your smartphone.

Gramin Polytechnic, Vishnupuri, Nanded 134


Client Side Scripting Language (Elective) - 22519

 In the slideshow JavaScript code, we create an array MySlides to store the banner
images using the following statement:
MySlides=new Array(‘banner1.jpg’,’banner2.jpg’,’banner3.jpg’,’banner4.jpg’)
 We use the variable Slide to indicate the index of the above array, where 0 represents
the index of the first slide, 1 represents the index of the second slide and so on. We
also created the function ShowSlides(SlideNumber) with the argument SlideNumber.

Example:- (JavaScript program to demonstrate slide show)


<html>
<script type="text/javascript">
MySlides=new
Array('D:\\Images\\Desert.jpg','D:\\Images\\Hydrangeas.jpg','D:\\Images\\Jellyfish.jpg');
banner=0;
function change()
{
banner++;
if (banner>MyBanners.length-1)
{
banner=0;
}
document.getElementById("textimg").src=MyBanners[banner];
}
</script>
<body>
<img id="textimg" src="D:\Images\Chrysanthemum.jpg" width="100" height="100">
<input type="button" name="bt1" value="clickme" onclick="change()">
</body>
</html>

6.4. Menus:-
6.4.1. Creating Pull down Menu:-
Drop down menus in a website are an important element when it comes to affective
navigation of Webpages. It is an encapsulation of many links, which allow the users to

Gramin Polytechnic, Vishnupuri, Nanded 135


Client Side Scripting Language (Elective) - 22519

browse the many pages and contents of a website. Using style sheets one can create drop
down menu in JavaScript.

Example:- (JavaScript program to demonstrate pull down menu)


<html>
<body>
<form>
<select id="mySelect" onchange="myFunction()">
<option>C</option>
<option>C++</option>
<option>Java</option>
<option>JavaScript</option>
</select>
</form>
<p id="demo"></p>
<script language="javascript">
function myFunction()
{
var x = document.getElementById("mySelect");
var i = x.selectedIndex;
alert(x.options[i].text);
}
</script>
</body>
</html>

6.4.2. Dynamically changing the Menu:-


The item of the menu can be changed dynamically depending upon action takes place.
There are two pull-down menus, so on the selection of first menu the other menu item is
changed dynamically
Example:- (JavaScript program to demonstrate dynamically changing pull down
menu)
<html>
<select id="cl1" name="cl1" onchange="populate(this.id,'cl2')">

Gramin Polytechnic, Vishnupuri, Nanded 136


Client Side Scripting Language (Elective) - 22519

Example cont.….:-
<option value="Class">Class</option>
<option value="FY">First</option>
<option value="SY">Second</option>
</select></hr>
<select id="cl2" name="cl2">
</select> </hr>
<script language="javascript">
function populate(f1,f2)
{
var f1=document.getElementById(f1);
var f2=document.getElementById(f2);
f2.innerHTML="";
if(f1.value=="FY")
{
var newOption=document.createElement("option");
newOption.innerHTML="C";
f2.options.add(newOption);
}
if(f1.value=="SY")
{
var newOption=document.createElement("option");
newOption.innerHTML="RDM";
f2.options.add(newOption);
}
}
</script>
</html>

6.4.3. Validating Menu selection:-


Validation refers to check whether the information if filled correctly. In this case if
the user doesn’t select any option then it prompt user to select appropriate option and
proceed.

Gramin Polytechnic, Vishnupuri, Nanded 137


Client Side Scripting Language (Elective) - 22519

Example:- (JavaScript program to demonstrate validating menu selection)


<html>
<body>
<form>
<select id="mySelect" onchange="myFunction()">
<option value="sel">Select Subject</option>
<option>C</option>
<option>OOP</option>
<option>JavaScript</option>
</select>
</form>
<p id="demo"></p>
<script language="javascript">
function myFunction()
{
var x = document.getElementById("mySelect");
var i = x.selectedIndex;
if (i==0)
{
alert("Please select subject");
}
else
{
alert(x.options[i].text);
}
}
</script>
</body>
</html>

Gramin Polytechnic, Vishnupuri, Nanded 138


Client Side Scripting Language (Elective) - 22519

6.4.4. Floating Menu:-


Many web pages are too long to fit on most users' screens. The visitors have to scroll
to read the article on the page; however such scrolling hides the navigation menus (or a
shopping cart contents) usually located at the top of the page. The JavaScript allows creating
dynamic menus which move along with scrolling. Such floating menu will be always visible
on screen. A floating menu can be created by setting the style position of that menu “sticky”.
Example:- (JavaScript program to demonstrate floating menu)
<html>
<body>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br>
<form>
<select id="mySelect" style="position:sticky">
<option value="sel">Select Subject</option>
<option>C</option>
<option>OOP</option>
<option>JavaScript</option>
</select>
</form>
<p id="demo"></p>
</body>
</html

6.4.5. Chain Select Menu:-


Dependent or chained dropdown list is a special field that relies on a previously
selected field so to display a list of filtered options. Chain select menu is a type of dynamic
menu in which there is more than one select menu present. The option selected from first
menu decides the options of second menu and option selected from second menu decides the
option of third menu. A common use case is on the selection of state/province and cities,
where you first pick the state, and then based on the state, the application displays a list of
cities located in the state.

Gramin Polytechnic, Vishnupuri, Nanded 139


Client Side Scripting Language (Elective) - 22519

6.4.6. Tab Menu:-


Tab menu contain one or more tab-head like a button. Each tab contains separate
content to display. If we click on a tab-head then the content related to that tab will be
displayed. If we like to have more than one page like content which will replace the previous
content on tab-head click then this type of menu is best choice.

6.4.7. Popup Menu:-


Popup menu is nothing but a hover able dropdown menu. The drop down menu
display the sub menu on mouse over is known as popup menu. It contains the submenu which
will display or popup below the menu in the form of list.

Gramin Polytechnic, Vishnupuri, Nanded 140


Client Side Scripting Language (Elective) - 22519

6.4.8. Sliding Menu:-


Sliding menu is not present on the screen. When we want it we should click on the
button or menu icon then it will slide in the screen.

6.4.9. Highlighted Menu:-


Sometimes there is a need to highlight a particular menu item. You can highlight a
menu by adding a different background color, text color etc. to the particular menu item using
custom CSS when we put mouse over the menu item.

6.4.10. Folding a Tree Menu:-

Gramin Polytechnic, Vishnupuri, Nanded 141


Client Side Scripting Language (Elective) - 22519

It lets you define a collapsible tree with support for arbitrary number of levels, plus
the ability to make any node a link with it.

6.4.11. Context Menu:-


When the user click right mouse button on the webpage then the context menu is
displayed and the position of menu is depend on the location where the mouse is clicked.

6.4.12. Scrollable Menu:-


The menu in which items can be scrolled to display limited item on screen is called
scrollable menu. If there are many menu need to be displayed on screen, but all menus are not
fit on the screen then we can use the scrollable menu.

Home | About us | Product | Service

Gramin Polytechnic, Vishnupuri, Nanded 142


Client Side Scripting Language (Elective) - 22519

6.4.13. Side Bar Menu:-


In side bar menu, the sub menu of a menu item will be displayed on right side of the
menu. When we click on the menu item, the sub menu of that menu will be displayed on right
side of the menu.

6.5. Protecting the Webpage:-


Following are some of the ways for protecting the webpage:-
1. Keep software up to date:- It may seem obvious, but ensuring you keep all software
up to date is vital in keeping your site secure. This applies to both the server operating system
and any software you may be running on your website such as a CMS or forum. When
website security holes are found in software, hackers are quick to attempt to abuse them.
2. Watch out for SQL injection:-SQL injection attacks are when an attacker uses a
web form field or URL parameter to gain access to or manipulate your database. When you
use standard Transact SQL it is easy to unknowingly insert rogue code into your query that
could be used to change tables, get information and delete data.
3. Protect against XSS attacks: - Cross-site scripting (XSS) attacks inject malicious
JavaScript into your pages, which then runs in the browsers of your users, and can change
page content, or steal information to send back to the attacker.

4. Beware of error messages: - Be careful with how much information you give away
in your error messages. Provide only minimal errors to your users, to ensure they don't leak
secrets present on your server (e.g. API keys or database passwords). Don't provide full
exception details either, as these can make complex attacks like SQL injection far easier.

Gramin Polytechnic, Vishnupuri, Nanded 143


Client Side Scripting Language (Elective) - 22519

5. Validate on both sides:-Validation should always be done both on the browser and

server side. The browser can catch simple failures like mandatory fields that are empty and
when you enter text into a numbers only field.

6. Check your passwords: - Everyone knows they should use complex passwords, but
that doesn’t mean they always do. It is crucial to use strong passwords to your server and
website admin area, but equally also important to insist on good password practices for your
users to protect the security of their accounts.

7. Avoid file uploads:- Allowing users to upload files to your website can be a big

website security risk, even if it’s simply to change their avatar. The risk is that any file
uploaded, however innocent it may look, could contain a script that when executed on your
server, completely opens up your website.

8. Use HTTPS:-HTTPS is a protocol used to provide security over the Internet. HTTPS

guarantees that users are talking to the server they expect, and that nobody else can intercept
or change the content they're seeing in transit.

9. Get website security tools: - Once you think you have done all you can then it's

time to test your website security. The most effective way of doing this is via the use of some
website security tools, often referred to as penetration testing or pen testing for short.
10. Disable right click: - Source code of the webpage of some websites can be viewed by
right clicking and click on view source option. By disabling the right click one can hide the
source code from the other users.
Example:- (JavaScript program to demonstrate disabling double click)
<html>
<script type="text/javascript">
document.onmousedown=disableclick;
function disableclick(e)
{
if(event.button==2)
{
return false;
}
}
</script> </html>

Gramin Polytechnic, Vishnupuri, Nanded 144


Client Side Scripting Language (Elective) - 22519

6.6. Framework of JavaScript and its Application:-


JavaScript Frameworks are popular among developers for such benefits like efficiency,
safety, and cost. The variety of frameworks for each development platform is huge.
Following are some of the frameworks used in JavaScript:-
1. Angular.js :- Generally, Angular.js it is one of the most beloved and used JavaScript
frameworks for building single page applications. It is available as an open source
solution and is supported by Google. The latter is a convincing argument in favor of
Angular to become a front-end solution for a web app. Angular JS is highly preferred
for hybrid mobile application development. Featured with components like overlays,
sidebars, switches and absolute positioned navigation bars, this framework
incorporates dynamic functionality to the application.
2. Backbone.js :- Backbone is amongst some of the most popular web development
frameworks for JavaScript developers, and partly for two reasons — it’s easy to
understand usability modules, as well as the very straightforward learning curve.
Backbone creates single-page applications using the most traditional web
development libraries. It is built with the idea in mind that all server-side functions
should flow through an API, minimizing the amount of code that needs to be
composed in order to achieve the same complex functionality of more sophisticated
web frameworks.
3. React.js:- React.js was created by the team of Facebook developers and came out in
2013. Being pretty new in comparison with other JavaScript frameworks it
confidently wins its niche. If you like the user interface of Facebook and Instagram
then you might like React.js too. This very framework is behind the front-end scenes
of the two social giants. There are other companies that benefit from using it:
Atlassian, BBC, Coursera, Dropbox, Flipboard, Netflix, Paypal, WhatsApp.
4. Embre.js:- Introduced in 2011 this open-source JavaScript framework was declared
as the best JavaScript framework for web application development in 2015. Its closest
competitors are Angular and React. Ember could be a good solution for a startup or
for a business looking to build complex web apps. It has a huge online community,
regular updates and wide application of JavaScript that is meant to offer an engaging
user experience. The framework is widely accepted for creating feature-rich web
applications. The most common websites that have been designed using the
framework are LinkedIn, Kickstarter, Blue Apron, and many others.

Gramin Polytechnic, Vishnupuri, Nanded 145


Client Side Scripting Language (Elective) - 22519

5. Aurelia.js:- Being a self-proclaimed web development framework, Aurelia makes the


process of site development a creative process. Designed with the latest JS standard,
ES6, Aurelia has the ability to function on all modern browsers. Designed on a
module-like framework, Aurelia has various small and huge libraries that can be used
either in combination or individually, depending upon the kind of application being
designed.
6. Meteor.js:- With a variety of features for backend, frontend development and
database management, Meteor rank as the most popular JavaScript frameworks. Since
its inception in the year 2012, this framework has grown in terms of performance, UI
design and so on. MeteorJS covers all the phases of software development cycle and
takes care of such glooming processes as linking, files concatenation and others. It is
of current usage in real-time application development for business companies like
Mazda, IKEA, Honeywell and many others.
7. Vue.js:- Introduced back in 2016, Vue has a learning curve that is easier. The
framework delivers two-way data binding, server-side rendering, Vue-CLI and
optional JSX support. Vue.js is one the fastest emerging frameworks and is a
preferable choice for quick cross-platform solutions. It gains more traction every
month, and there are obvious reasons for that comprehensively explained in a Vue.js
development guide.
8. Polymer: - Polymer is another JavaScript framework from Google. With its material
web design and modern outlook, Polymer is one stupefying JavaScript framework that
comes with the ability to create and reuse web components. It is featured with
Polymer App Toolbox that allows you to create and deliver cutting-edge progressive
web applications. The framework is fully interoperable, built for speed and offers
support on all modern day browsers.
9. Socket: - Socket’s gained lots of momentum in the real-time developer community.
With Socket you can enjoy a fully functional real-time communication between the
client and the server. Socket is divided into two different parts — the first part is a
client-library that runs from the browser, whereas the server-library is built on top of
Node.js. Both libraries share a very similar API, and Socket is also event driven;
much like Node.js is. With Socket you can implement real-time streaming of binary,
instant messaging platforms, interactive document collaboration, real-time stats for
your apps and projects (analytics), and so much more.

Gramin Polytechnic, Vishnupuri, Nanded 146


Client Side Scripting Language (Elective) - 22519

Question Bank:-
Remember Level:-
1. What is slide show?
2. What is menu in JavaScript? List and explain various types of menus available.
3. What is Tab menu?
4. What is Popup menu?
5. What is Sliding menu?
6. What is Highlighted menu?
7. What is folding a Tree menu?
8. What is Context menu?
9. What is Scrollable menu?
10. What is Side bar menu?
11. Enlist JavaScript framework. Explain one of them.
Understand Level:-
1. How to build a static message in status bar? Explain with example.
2. How to change the message of status bar using rollover? Explain with example.
3. How to load and display the banner advertisement? Explain with example.
4. How to link a banner advertisement with URL? Explain with example.
5. How to create dynamically changing menu? Explain with example.
6. How to validate menu selection? Explain with example.
7. How to create chain select menu?
8. How to protect the webpage?
Apply Level:-
1. Write a JavaScript program to display the moving message on status bar.
2. Write a JavaScript program ton change images in banner.
3. Write a JavaScript program to link all the images in banner to URLs.
4. Write a JavaScript program to create a slide show.
5. Write a JavaScript program to create a pull-down menu.
6. Write a JavaScript program to create floating menu.
7. Write a JavaScript program to disable right mouse button.

Gramin Polytechnic, Vishnupuri, Nanded 147


Client Side Scripting Language (Elective) - 22519

QUESTION PAPER
MSBTE EXAMINATION
WINTER 2019

Gramin Polytechnic, Vishnupuri, Nanded 148


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 149


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 150


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 151


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 152


Client Side Scripting Language (Elective) - 22519

MODEL ANSWER
MSBTE EXAMINATION
WINTER 2019

Gramin Polytechnic, Vishnupuri, Nanded 153


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 154


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 155


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 156


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 157


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 158


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 159


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 160


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 161


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 162


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 163


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 164


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 165


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 166


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 167


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 168


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 169


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 170


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 171


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 172


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 173


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 174


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 175


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 176


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 177


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 178


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 179


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 180


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 181


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 182


Client Side Scripting Language (Elective) - 22519

Gramin Polytechnic, Vishnupuri, Nanded 183

You might also like