0% found this document useful (0 votes)
50 views

Css Notes of All Unit

Uploaded by

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

Css Notes of All Unit

Uploaded by

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

CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.

KADAM

UNIT:1 Basics Of JavaScript


[12 Mark]
_________________________________________________________________________________

Contents:

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, expression,
function definition 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.
________________________________________________________________________________
Course Outcome: Create interactive web pages using program flow control structure.

Reference:
1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
2. https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web/JavaScript_basics
3. https://www.w3schools.com/js/
4. https://www.geeksforgeeks.org/introduction-to-javascript/amp

1
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

UNIT:1 BASICS OF JAVASCRIPT

What is Scripting?
Script is a sequence of commands written as plain text and run by a interpreter.
Scripting language is a language which is used to write script.

Eg:
Javascript
Python
Ruby

Scripting languages helps to make the web pages more dynamic than its traditional static
pages

Static and Dynamic Web pages:

Static: content on static website is stable and doesn’t change. Content on static website is
stored directly on the server and pulled as it is.
Dynamic: Dynamic website can change according to how you want it to behave and what
you want specific user to use. Content on a dynamic website stored in a database or collection
and delivered according to how it is organized or filtered.

Client side and server side Scripting:


Client side means that the Javascript code is run on client machine which is the browser.
Eg: Javascript, VBScript and JQuery.
Server side scripting that the code is run on the server which is serving web pages .
Eg: php,python,NoteJs,C#

Javascript is a text based programming language that allow you to make you web pages
interactive.
Jvascript gives web pages interactive elements that engage a user.
It is light weight and open source client side scripting language supported by all browser.

Uses of Javascript:
 Web Development.
 Web Applications.
 Web Server
 Mobile Application

2
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

 Games Development
Features of Java script

Q. List any four features of Java script.

Features of Javascript :

1. JavaScript is a object-based scripting language.


2. Giving the user more control over the browser.
3. It Handling dates and time.
4. It Detecting the user's browser and OS
5. It is light weighted.
6. Client – Side Technology
7. JavaScript is a scripting language and it is not java.
8. JavaScript is interpreter based scripting language.
9. JavaScript is case sensitive.
10. JavaScript is object based language as it provides predefined objects.
11. Every statement in javascript must be terminated with semicolon (;).
12. Most of the javascript control statements syntax is same as syntax of control statements in
C language.
13. An important part of JavaScript is the ability to create new functions within scripts.
Declare a function in JavaScript using function keyword.

How to Write a Javascript:


<script>……….</script> tag is used to add script in HTML.
The <script> tag can be placed either in the <head> section of your HTML or in the <body>
section.

1.

<html>
<head>
<script>
………
………
……….
……….
</script>
</head>
<body>

</body>
</html>

3
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

2.

<html>
<head>
</head>
<body>
<script>
………
………
……….
……….
</script>

</body>
</html>

1.2 Object Name, Property, Method, Dot syntax and Main Event:
Javascript is an object oriented programming language means everything is in the
foms of an object. A javascript object is a collection of named values and these named values
are properties of object.

Object Name:
Every web page contains various objects. Each object should be uniquely identified by a
name or IDs in a web page to distingwish between them. Javascript support various objects
like document, form, button, window etc.

In Javascript, object can be created with curly brackets { } with an optional list of properties.

<html>
<head>
<script language="javascript" type="text/javascript">
var person={
firstname:"sampada",
lastname:"kadam"
};
</script>
</head>
<body>
</body>
</html>

4
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

1.2.2 Property:
A property is a value associated with an object. Each object has it’s own set of properties.
For eg: width, height, name, age etc.

Property has a Key:Value pair.


Key:It is a property name is always a string
Value:It is a property value can be any data type like string,number,Boolean

Eg:
firstname=”sampada”;

To access the properties of objects by following ways:

Person.firstname;

Data types in Javascript:


JavaScript Datatypes

1. String
2. Number
3. Boolean
4. Undefined
5. Null

The Object Datatype

The object data type can contain:

1. An object
2. An array

1.3 Values and Variables:


Var keyword is used to specify the data type. It can hold any types of values such as
numbers, strings etc.

Following are the values used by javascript:

-Number: A number is a numeric value.


Eg: var a =30;

-String: A string is a sequence of characters that is enclosed within quotation marks.


Eg: var name =”Sampada”;

-Boolean: A Boolean is a value either false or true


Eg: var b =true;

5
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

-Null: Null value means no value at all.


Eg: var a =null;

-Object: An object is a instance through which we can access members


Eg: var person={
First name=”sampada”,
Lastname=”kadam”,
};

 Program: Write a javascript code to demonstrate use of variables and datatypes.

<html>
<head>
<title>Logical Operation</title>
<script language="javascript" type="text/javascript">
var a=10;
var name="sampada";
var b=true;
document.write("Entered number : "+a);
document.write("<br>");
document.write("Entered name : "+name);
document.write("<br>");
document.write("Entered boolean value : "+b);
</script>
</head>
<body>

</body>
</html>

Output:

6
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

1.4 Operators and Expressions:


Javascript includes following categories of operators:

1. Arithmetic operators
2. Comparison operators
3. Logical operators
4. Assignment operators
5. Ternary operators

1. Arithmetic operators:

Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (Division Remainder)

++ Increment (increment operands value by one)

-- Decrement (decrement operands value by one)

Program: Write javascript code to perform arithmetic operations


<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=20
var b=10;
document.write("Addition is : "+(a+b));
document.write("<br>");
document.write("Substration is : "+(a-b));
document.write("<br>");
document.write("Multiplication is : "+(a*b));
document.write("<br>");
document.write("Division is : "+(a/b));
</script>

7
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

</body>
</html>

Output:

Program:Write a Javascript code to print average of three numbers.

<html>
<head>
<title>Average of three number</title>
<script language="javascript" type="text/javascript">
var a=10;
var b=20;
var c=30;
var avg=(a+b+c)/3;
document.write("Average of three numbers= "+avg);
</script></head><body></body></html>

Output:

8
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

2. Comparison operators

Operator Description

== Compares the quality of two operands without considering types

=== Compares the quality of two operands with types

!= Compare inequality of two operands

> greater than

< less than

>= greater than or equal to

<= less than or equal to

Program:Write a javascript to demonstrate comparison operator


<html>
<head>
<title>Comparison Operation</title>
<script language="javascript" type="text/javascript">
var a=10,b=5,c="10";
document.write("value of a : "+a);
document.write("<br>");
document.write("value of b : "+b);
document.write("<br>");
document.write("value of c : "+c);
document.write("<br>");
document.write("a is equal to c without considering type : "+(a==c));
document.write("<br>");
document.write("a is equal to c with type : "+(a===c));
document.write("<br>");
document.write("a is not equal to b : "+(a!=b));
document.write("<br>");
document.write("a is greater than b : "+(a>b));
document.write("<br>");
document.write("a is less than b : "+(a<b));
document.write("<br>");
document.write("a is greater than or equal to b : "+(a>=b));
document.write("<br>");
document.write("a is less than or equal to b : "+(a<=b));
</script></head><body></body></html>

Output:
9
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

3.Logical Operators:

Operator Description
logical AND. It check whether two operands are non-zero. If yes then returns
&&
1 otherwise 0.
|| logical OR. It check whether any one of the two operands is non-zero.

! logical NOT.It reverse the Boolean result of the operand

Program:Write a javascript code to demonstrate logical operator

<html>
<head>
<title>Logical Operation</title>
<script language="javascript" type="text/javascript">
var a=10,b=5,
document.write("value of a : "+a);
document.write("<br>");
document.write("value of b : "+b);
document.write("<br>");
document.write((a>b)&&(a!=b)); // (10>5) && (10!=5) i.e.true
document.write("<br>");
document.write((a<b)||(a!=b)); // (10<5) && (10!=5) i.e.true
document.write("<br>");
document.write(!(a<b)); // (!(10<5)) i.e true
</script>
</head>
<body>
</body></html>

10
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Output:

4.Assignment Operators:
Assignment operators assign values to JavaScript variables.

Operator Example Same As


= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= A*=b a=a*b
/= A/=b a=a/b
%= a%=b a=a%b

Program: Write a javascript code to demonstrate assignment operator

<html>
<head>
<script language="javascript" type="text/javascript">
var a=10;
var b=20;
a=b;
document.write("a=b is "+a);
a+=1;
document.write("<br>a+=b is "+a);
a-=1;
document.write("<br>a-=b is "+a);
a*=5;
document.write("<br>a*=b is "+a);
a/=2;
document.write("<br>a/=b is "+a);
a%=2;
document.write("<br>a%=b is "+a);
</script>
</head>
<body>
</body>

11
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

</html>

Output:

5.Ternary Operator:

Syntax:
<condition> ? <value1>:<value2>

Ternary operator starts with conditional expression followed by ? operator. Second part
(after ? and before : operator) will be executed if condition turns out to be true. If condition
becomes false then third part (after :) will be executed.

Program: Write a javascript code to illustrate the use of ternary operator.


<html>
<head>
<script language="javascript" type="text/javascript">
var a=10;
var b=20;
var c=(a>b)?a:b;
document.write(c);
</script>
</head>
<body>
</body>
</html>

Output:

12
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

1.5 Conditional Statement:


Conditional statements are used to perform different actions based on different conditions.
In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use if else to specify a block of code to be executed, if the same condition is false
 Use if else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

1.5.1 if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax:
if (condition) {
// block of code to be executed if the condition is true
}

Program: Write a javascript code to demonstrate if statement.


<html>
<head>
<script language="javascript" type="text/javascript">
var age=28;
if(age>18)
{
document.write("Your age is greater than 18");
}
</script>
</head>
<body>
</body></html>

Output:

13
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

1.5.2 if-else statement:


syntax: Use the if statement to specify a block of JavaScript code to be executed if a
condition is true. Use the else statement to specify a block of code to be executed if the
condition is false.

Syntax:

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Program:Write a javascript code to demonstrate if-else statement.

<html>
<head>
<title>Average of three number</title>
<script language="javascript" type="text/javascript">
var a=10;
var b=20;
if(a>b)
{
document.write("a is greater than than b");
}
else
{
document.write("b is greater than than a");
}
</script></head><body></body></html>

Output:

14
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

1.5.3 Nested if statement

A nested if is an if statement that is the target of another if or else. if statement inside an


if statement. Javascript allows us to nest if statement within if statement i.e. we can
place an if statement inside another if statement.

Syntax:
if (condition1)
{
// block of code to be executed if condition1 is true
} else if (condition2)

{
// block of code to be executed if the condition1 is false and condition2 is true
} else

{
// block of code to be executed if the condition1 is false and condition2 is false
}

Program: Write a javascript program which compute the average of five


subjects, then determine corresponding grade.
<html>
<head>
<script language="javascript" type="text/javascript">
var subject1=74;
var subject2=56;
var subject3=80;
var subject4=79;
var subject5=89;
var avg=(subject1+subject2+subject3+subject4+subject5)/5;
document.write("Your Percentage is = "+avg);
document.write("<br>");
if(avg>75)
{
document.write("Your grade is = Distinction");
}
else if((avg>=60)&&(avg<75))
{
document.write("Your grade is = First Class");
}
else if((avg>=40)&&(avg<60))
{
document.write("Your grade is = Second Class");
}
else if((avg>=35)&&(avg<40))
{
document.write("Your grade is = Pass");

15
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

}
else
{
document.write("Your grade is :Fail");
}
</script>
</head>
<body>

</body>
</html>

Output:

1.6 Switch Case Statement

The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many code blocks to be executed.

Syntax:

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

How Switch Case Statement Works:


 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.

16
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Program: Write a javascript code to demonstrate Switch Case statement


<html>
<head>
<script language="javascript" type="text/javascript">
var a=prompt("Enter number from 1 to 4");
switch(a)
{
case "1":
document.write("perform Addition");
break;
case "2":
document.write("Perform substraction");
break;
case "3":
document.write("Perform Multiplication");
break;
case "4":
document.write("Perform Division");
break;
default:
document.write("Number sholud be in between 1 to 4");
}
</script>
</head>
<body>

</body>
</html>

Output:

17
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Program:Write a simple calculator program using switch case in


javascript.
OR
Write a javascript to perform arithmetic operations by using switch case
<html>
<head>
<script>
var first_no,second_no,result,operation;
var first_no=parseFloat(prompt("Enter First Number"));
var second_no=parseFloat(prompt("Enter Second Number"));
var operation=prompt("Enter Your choice either +,-,* or /");
switch (operation)
{
case '+':
result=first_no+second_no;
document.write("Addition is :"+result);
break;

case '-':
result=first_no-second_no;
document.write("Substraction is :"+result);
break;

case '*':
result=first_no*second_no;
document.write("Multiplication is :"+result);
break;

case '/':
result=first_no/second_no;
document.write("Division is :"+result);
break;

default:
document.write("Enter correct choice");
break;

}
</script>
</head>
<body>

</body>
</html>

Output:

18
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

1.7 Loop Statement

Loops can execute a block of code a number of times.


JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

1.7.1 for loop:

Syntax:
For (initial condition; terminating condition; stepping condition)
{
// line of code to be executed
}

Program:Write a javascript code to print “welcome student” 10 times by


using for..loop.
<html>
<head>
<script language="javascript" type="text/javascript">
var a;
for(a=0;a<10;a++)
{
document.write("Welcome student<br>");
}
</script>
</head>
<body>

</body>
</html>

19
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Output:

Program:Write a javascript code to print even numbers from 1 to 100 by


using for loop.
<html>
<head>
<script language="javascript" type="text/javascript">
var a;
for(a=2;a<=100;a=a+2)
{
document.write(a+"<br>");
}
</script>
</head>
<body></body></html>

Output:

1.7.2 for In loop:


20
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

For…in loop iterate(loop) over the properties of an object. The code block inside the loop is
executed once for each property.
Syntax:

for (key in object) {


// code block to be executed
}

 let keyword is used to declare variables in Javscript. The var keyword can also be
used to declare variables, but the key difference between them lies in their scopes.
 var is function scoped while let is block scoped.
Program:Write a javascript to demonstrate for… In loop.
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var person={
name:"sampada",
age:30,
classname:"TYCM"
};
for(let x in person)
{
document.write(person[x]);
document.write("<br>");
}
</script>
</body>
</html>

Output:

Program: Write a javascript to demonstrate for In loop.

21
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

<html>
<head>
<script language="javascript" type="text/javascript">
var person={
name:"sampada",
age:30,
dept:"comp"
};
var txt="";
for(let x in person)
{

txt=txt+person[x]+" ";
}
document.write(txt);
</script>
</head>
<body>

</body>
</html>

Output:

1.7.3 while Loop:

22
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

The while loop loops through a block of code as long as a specified condition is true.

Syntax:

while (condition) {
// code block to be executed
}

Program: Write a javascript code to print 1 to 10 numbers by using while loop.

<html>
<head>
<script language="javascript" type="text/javascript">
var i=1;
while(i<=10)
{
document.write(i+"<br>");
i++;
}
</script>
</head>
<body>

</body>
</html>

Output:

1.7.4: Do…While Loop

23
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

The do...while statements combo defines a code block to be executed once, and repeated as long as
a condition is true.

The do...while is used when you want to run a code block at least one time.

Syntax:

do {
code block to be executed
}
while (condition);

Program: Write a javascript code to print 1 to 10 by using do…while loop

<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=1;
do
{
document.write(a+"<br>");
a=a+1;
}while(a<=10)
</script>
</body>
</html>

Output:

1.8
1.8.1 Querying and Setting properties:
24
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

The dot (.) operator or square bracket ( [] ) are used to obtained values of properties.
To get properties from student object:
var name=student.name;
var rollno=student.rollno;

if using square brackets, the value within the brackets must be an expression that evaluates to
a string that contains the desired property name.

To get properties from student object:


var name=student[name];
avr rollno=student[rollno];

To set properties of student object:


student.name=”sampada”;
student.rollno=30;
OR
Student[“name”]=”sampada”;
Student[“rollno”]=30;

1.8.2: Deleting Properties:


The delete keyword is used to delete both the value of the property and property itself.
Eg:
delete student.name;
OR
delete student[“name”];

Program: Write a javascript to delete property of object


<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var student={
name:"sampada",
rollno:30,
};
document.write("Name: "+student.name);
delete student.name;
document.write("Name: "+student.name);
</script>
</body>
</html>

Output:

25
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Program: Write a javascript to create person object with properties


firstname, lastname, age, eyecolor. Delete eye color property and display
remaining properties of person object.

<html>
<head>
<script language="javascript" type="text/javascript">
var person={
firstname:"sampada",
lastname:"kadam",
age:30,
eyecolor:"black"
};
delete person.eyecolor;
document.write("Your First Name is :"+person.firstname);
document.write("<br>Your Second Name is :"+person.lastname);
document.write("<br>Your Age is :"+person.age);
document.write("<br>Your eyecolor is :"+person.eyecolor);
</script>
</head>
<body></body></html>

Output:

1.8.3 Property Getters and Setters:

26
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Getters and setters allow you to define Object Accessors (Computed Properties).

get- a function without arguments, that works when a property is read.

Program:Write a javascript code to illustrate the use of getter method.


<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var student={
name:"sampada",
rollno:30,
get getname(){
return this.name;
}
};
document.write("Student Name is : "+student.getname);
</script>
</body>
</html>

Output:

When a value is set, the setter is called and passed the value that was set.
Set – a function with one argument that is called when the property is set.

27
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Program:Write a javascript code to illustrate the use of setter method.


<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var student={
name:"sampada",
rollno:30,
set setname(value)
{
this.name=value;
}
};
student.setname="shourya";
document.write("Student Name is : "+student.name);
</script>
</body>
</html>

Output:

Program:Write a javascript code to illustrate the use of getter and setter


method.
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var student={

28
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

name:"sampada",
rollno:30,
get getname(){
return this.name;
},
set setname(value){
this.name=value;
}
};
document.write("Student Name is : "+student.getname);
student.setname="shourya";
document.write("<br>Student Name is : "+student.getname);
</script>
</body>
</html>

Output:

Program: Write a javascript program that will display current date in


DD/MM/YYYY format. (4 marks)

Program:
<html>
<head>
<script>
var today=new Date();
var dd=today.getDate();
var mm=today.getMonth()+1;
var yy=today.getFullYear();

29
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

if(dd<10)
{
dd='0'+dd;
}
if(mm<10)
{
mm='0'+mm;
}
document.write(dd+' / '+mm+' / '+yy);
</script>
</head>
<body>
</body>
</html>

Output:

Question: State the use of method in javascript with the help of suitable
example (2 marks)

Answer:
Method is a set of instructions that perform a task. The difference between method and
function is that, method associated with an object, while a function is not.

<html>
<head>
<script>
var str="Computer Technology Dept";
var str1=str.toLowerCase();
var str2=str.toUpperCase();

30
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

document.write(str2);
</script>
</head>
<body>

</body>
</html>

In above program, str store the string “Computer Technology Dept”. The .toLowerCase()
and .toUpperCase() methods in the example above are called on str.

1. .toLowerCase():This method is called on str variable, which return the lower case
string “computer technology dept”.
2. .toUpperCase(): This method is called on str variable, which return the upper case
string “COMPUTER TECHNOLOGY DEPT”.

Q. Explain prompt() and confirm() method of Java script with syntax and
example.
Answer:
prompt(): The prompt () method displays a dialog box that prompts the visitor for input. The
prompt () method returns the input value if the user clicks "OK". If the user clicks "cancel"
the method returns null.

Syntax: window.prompt (text, defaultText)

<html>
<head>
<script>
function msg()
{
var a=prompt("Enter Number");
document.write("Entered Number is :"+a);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="msg()"/>
</body>
</html>

confirm() : It displays the confirm dialog box. It has message with ok and cancel buttons.
Returns Boolean indicating which button was pressed

Syntax: window.confirm("sometext");

<html>
<head>
<script>
function msg()

31
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

{
var a=confirm("Are you sure?");
if(a==true)
{
document.write("ok");
}
else
{
document.write("cancel");
}
}
</script>
</head>
<body>
<input type="button" value="click" onclick="msg()"/>
</body>
</html>

Program:Write a Javascript code to find out factorial of entered number.


<html>
<head>
<script language="javascript" type="text/javascript">
var i=parseInt(prompt("Enter Number"));
var a;
var fact=1;
for (a=1; a<=i; a++)
{
fact=fact*a;
}
document.write("Factorial: "+fact);
</script>
</head>
<body>

</body>
</html>

Program: Write a javascript code to check entered number is Prime


number or not.
<html>
<head>
<script language="javascript" type="text/javascript">
var num=parseInt(prompt("Enter Number"));
var i;
var isprime=true;
for(i=2;i<num;i++)
{

32
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

if(num%i==0)
{

isprime=false;
break;
}
}

if(isprime)
{
document.write("Number is prime");
}
else
{
document.write("Number is not prime");
}
</script>
</head>
<body>
</body>
</html>

Javascript program on Fibonacci Series


<html>
<head>
<script language="javascript" type="text/javascript">
var num=parseInt(prompt("Enter Number"));
var n1=0;
var n2=1;
var nextnum;
document.write("Fibonacci Series:");

var i;
for(i=1; i<=num; i++)
{
document.write(n1+ " ");
nextnum=n1+n2;
n1=n2;
n2=nextnum;
}

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

33
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

Exam-Winter 2023
Q.State meaning of each token of the following statement and describe it:
(i) ++a;
(ii) document.bgcolor;
Ans:
(i) ++ is the increment operator and a is the operand, hence a++ will increment the
value of a by 1 .
(ii) The bgcolor Property specifies the background color of HTML document.

Q. Write and explain syntax of prompt() method in JavaScript.


 prompt() method is used to display a dialogue box to the user to prompt them to an
input.
 It has two buttons “OK” and “CANCEL”, if the user click on the “OK” buttonthen it
will return the inputed value , if the user clicks on the "CANCEL” buttonthen it will
return a null value
 Syntax: prompt(text)
 Example:
<script>
var name = prompt ("Enter a name");
document. Write(name);
</script>

Q. List various assignment operators supported by JavaScript, explain


any two with the help of suitable example.
assignment operators supported by JavaScript

Example:
<script> // = is used to assign a value to a variable
var num = 10;
document.write(num); // num 10
/* += first add the value to the existing value of the variable then assign it the new added
value */

num +=10;

34
CLIENT SIDE SCRIPETING (CSS) -22519 ( UNIT-I ) MRS. S.S.KADAM

document.write(num); // num 20
</script>

Q.Write an HTML script that accepts Amount, Rate of Interest and Period
from user. When user submits the information a JavaScript function must
calculate and display simple interest in a message box. (Use formula S.I. =
PNR/100) [4Marks]

<html>
<head>
<script>
var p=parseInt(prompt("Enter principal Amount"));
var n=parseInt(prompt("Enter period"));
var r=parseInt(prompt("Enter Rate of Interest"));
var si=(p*n*r)/100;
alert("Simple Inerest is :"+si);
</script>
</head>
</html>

Q. Write a JavaScript that accepts user’s first name and domain name of
organization from user. The JavaScript then forms email address as
<firstname@domain name> and displays the results in the browser
window. [4 Marks]

<html>
<head>
<script>
var fName=prompt("Enter your First Name");
var domainName=prompt("Enter domain Name");
var emailid=fName + "@" + domainName;
document.write("Email Id is :" + emailid);
//alert("Email Id is :" + emailid);
</script>
</head>
</html>

35
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

UNIT:2
Array, Function and String
[14 Mark]

Contents:

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 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 given position,
retrieving a position of character in a string, dividing text, copying a sub string, converting
string to number and numbers to string, changing the case of string, finding a Unicode of a
character-charCodeAt(), fromCharCode().

Course Outcome:
Implement Arrays and functions in Java script.

Reference:
1. https://www.w3schools.com/js/js_arrays.asp

2. https://www.w3schools.com/js/js_string_methods.asp

3. https://stackoverflow.com/questions/9423693/javascript-function-definition-
syntax

4. https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/function

1
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

UNIT:2
Array, Function and String
__________________________________________________
• Array:
▪ An Array is an object that can store a collection of items. Array is useful when
you need to store large amount of data.
▪ You can access the items in an array by referring to its index numbers and index
of the first element of an array is zero.
▪ An array in JavaScript can hold different elements. We can store numbers,
Strings, character and Boolean in a single value

2.1 Declaring an Array


There are two ways to declare an array
1.By array Literal
2.By creating instance an Array

1.By array Literal


Syntax:
var array_name=[value1,value2,value3…….,valueN];
<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=["a","b","c"];
document.write(arr1);
</script>
</head>
<body>
</body>
</html>

Output:
a, b, c

2
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
• Basic Array program [With Numeric values] :
<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=[1,2,4,12,45,10];
document.write(arr1);
</script>
</head>
<body>
</body>
</html>
Output:
1,2,4,12,45,10

• Basic Array program [With Numeric values,character and String] :


<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=[1,”a”,4,”abcde”,45,10];
document.write(arr1);
</script>
</head>
<body>
</body>
</html>
Output:
1,”a”,4,”abcde”,45,10

3
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2. By Creating instance of Array:
▪ New keyword is used instance of array
Syntax:
Var array_name=new Array();

Program:Write a Javascript code to create an Array and print its length.


<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array(3);
document.write("Lenght of Array :"+arr1.length);
</script>
</head>
<body>

</body>
</html>

4
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.1.2 Initializing an Array:
Initialization is the process of assigning values to an array. While initializing an array,
all elements should be placed in parenthesis and separated by commas.

Program: write a JavaScript code to create and initialize an element in Array.


<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array("C","C++","Java","VB");
document.write(arr1);
</script>
</head>
<body>

</body>
</html>

2.1.3 Defining an Array Elements:


Array contains a list of element, each element in the array is identified by its index.
The first element is an array stores at 0th position, second element at 1st position,
third element at 3rd position and so on.

5
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program:Write a Javascript code to create and print an element in Array.
<html>
<head>

<script language="javascript" type="text/javascript">

var arr1=new Array(3);


arr1[0]="C";
arr1[1]="C++";
arr1[2]="Java";
arr1[3]="VB";
document.write("<br> Element of 0th Place: "+arr1[0]);
document.write("<br> Element of 1st Place: "+arr1[1]);
document.write("<br> Element of 2nd Place: "+arr1[2]);
document.write("<br> Element of 3rd Place: "+arr1[3]);

</script>

</head>
<body>
</body>
</html>

2.1.4 Looping an Array


In javascript, for loop iterate over each item in an array. Array are zero based,which means
the first item is referenced with an index of 0.Elements in an Array are access by a numeric
index,starting at zero and ending with the array length minus 1.

6
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
<html>
<head>

<script language="javascript" type="text/javascript">

var arr1=new Array(3);


arr1[0]="C";
arr1[1]="C++";
arr1[2]="Java";
arr1[3]="VB";

for(var a=0;a<arr1.length;a++)
{
document.write("<br>Element= "+arr1[a]);
}

</script>

</head>
<body>

</body>
</html>

2.1.5 Adding an Array Element


Following are two ways to add elements in an array:

1.By using push() method


2.By using unshift() method

1.By using push() method:


Push() method adds one or more elements at the end of array.

7
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Syntax:
Array_name.push(element1,element2,……,elementN);

Program: Write a Javascript code to implement push method of Array.

<html>
<head>

<script language="javascript" type="text/javascript">


var arr1=new Array(2);
arr1[0]="C";
arr1[1]="C++";
document.write("Original Array Length :"+arr1.length);
document.write("<br>Origional Array Element : "+arr1+"<br>");

arr1.push("Java");
arr1.push("VB","Python");
document.write("<br>Array length after adding new Element : "+arr1.length);
document.write("<br> Array after Adding element : "+arr1+"<br>");
</script>

</head>
<body>

</body>
</html>

2.By using unshift() method:


unshift() method adds one or more elements in the beginning of an array. It returns the
updated array with change in length.

Syntax:
Array_name.unshift(element1);

Array_name.unshift(element1,element2,……..,elementN);

8
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array(2);
arr1[0]="C";
arr1[1]="C++";
document.write("Original Array Length :"+arr1.length);
document.write("<br>Origional Array Element : "+arr1+"<br>");

arr1.unshift("Java");
document.write("<br>Array length after adding new Element :
"+arr1.length);
document.write("<br> Array after Adding element : "+arr1+"<br>");

</script>

</head>
<body>
</body>
</html>

2.1.6 Sorting an Array Element


Sort() method sorts the elements of an array in place and returns the sorted array. When
sort() without argument is called. It will sort elements in alphabetical order.

Syntax:
Array_name.sort();

9
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write javascript code to print number array element by using sort
method

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=[8,6,9,4,2];
document.write("Array element before sorting.....");
document.write(arr1+"<br>");
arr1.sort();
document.write("Array element after sorting.....");
document.write(arr1);
</script>

</head>
<body>

</body>
</html>

10
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program:Write javascript code to print array element (string) by using sort
method

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=["xyz","pqr","abc"];
document.write("Array element before sorting.....");
document.write(arr1+"<br>");
arr1.sort();
document.write("Array element after sorting.....");
document.write(arr1);
</script>

</head>
<body>

</body>
</html>

11
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write javascript code to print array element (all types) by using sort
method

<html>
<head>

<script language="javascript" type="text/javascript">


var arr1=[9,"pqr","Abc",8,"abc",2,"PQR"];
document.write("Array element before sorting.....<br>");
document.write(arr1+"<br><br>");
arr1.sort();
document.write("Array element after sorting.....<br>");
document.write(arr1);
</script>

</head>
<body>

</body>
</html>

12
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
• The sort() function is used to sort the array in place in a given order
according to the compare() function. The only argument to this function
that is used to sort the elements according to different attributes and in
the different order.
Syntax:
Array_name.sort(CompareFunction);

CompareFunction(a,b)<0 Then a comes before b in the answer


CompareFunction(a,b)>0 Then b comes before a in the answer
CompareFunction(a,b)=0 Then the order of a and b remain unchanged

Program: Write javascript code to sort array element in ascending order.


<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array(9,23,34,8,10,2,45);
document.write("Array element before sorting:<br> "+arr1);
function compare(a,b)
{
return a-b;
}
arr1.sort(compare);
document.write("<br>Array element after sorting: <br>"+arr1);
</script>
</head>
<body>

</body>
</html>

Output:

13
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write javascript code to sort array element in descending order.

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array(9,23,34,8,10,2,45);
document.write("Array element before sorting:<br> "+arr1);
function compare(a,b)
{
return b-a;
}
arr1.sort(compare);
document.write("<br>Array element after sorting: <br>"+arr1);
</script>
</head>
<body>

</body>
</html>

Output:

14
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

Reverse() Method:
Reverse() method is used to display sorted list in reverse manner i.e.in
descending order. It will return the reversed single value of the array.

Syntax: array.reverse();

Program:Write a javascript code to sort array elements in descending order by


using reverse order.

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array(9,2,3,8,1,7,5);
document.write("Array element before sorting:<br> "+arr1);
var a=arr1.sort();
a.reverse();
document.write("<br>Array element after sorting: <br>"+a);
</script>

</head>
<body>

</body>
</html>

Output:

15
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.1.7 Combining an Array Elements into strings:
In javascript an array can be combined into string using following two
function:
1.Join() method
2.Concat() method

1.Join() method:
This function joins all elements of an array into a string

Syntax:
Array.join(seperator);
Here,separator is alike /,_,* etc to separate to each element of the array. If
seperatoris not mentioned,it will display list with comma as separator.This
fuction returns a string after joining all elements together.

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array("C","C++","Java",);
document.write("Array element before sorting:<br> "+arr1);
var a=arr1.join();

document.write("<br>Array element after Joining: <br>"+a);


</script>

</head>
<body>
</body>
</html>

16
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

2.Concat() method:
This function is used to join two or more array together in JavaScript.
This function returns a new string which is combination of different string
passed to it as arguments.

Syntax:
String.concat(string1,string2,string3,……);

Program: Write a Javascript code to implement concat method of array.

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array("C","C++","Java",);
document.write("Array element before concat method:<br> "+arr1);
var a=arr1.concat("VB");
document.write("<br>Array element after concat method: <br>"+a);
var a1=arr1.concat("PHP",".NET");
document.write("<br>Array element after concat method: <br>"+a1);
</script>

</head>
<body>

</body>
</html>

Output:

17
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.1.8: Changing Elements of an array:
1.Shift()
2.Pop()
3. Unshift()
4.Push()

1.Shift()
This method is used to remove first element from an array and returns the
removed single value of an array.
Syntax:
Array.shift();

Program:Write a javascript code to implement shift method of array.

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=new Array(1,2,3,4,5);
document.write("Array element before shift method: "+arr1);
var a=arr1.shift();
document.write("<br> Removed element after Shift method: "+a);
document.write("<br>Array Element after shift method: ",arr1);
</script>

</head>
<body>

</body>
</html>

Output:

18
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.Pop Method:
This method is used to remove last element and return the removed
element from an array.

Syntax:
Array.pop()

Program: Write a Javascript code to implement pop() method of array.

<html>
<head>

<script language="javascript" type="text/javascript">


var arr1=new Array(1,2,3,4,5);
document.write("Array element before pop method: "+arr1);
var a=arr1.pop();
document.write("<br> Removed element after pop method: "+a);
document.write("<br>Array Element after pop method: ",arr1);
</script>

</head>
<body>

</body>
</html>

Output:

19
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
3.Splice method:
This method is used to add or remove the elements to or from the existing
array. It returns the removed elements from an array. This method also modifies
the original array.

Syntax:
Array.splice(start, delete, element1, element2, ….., elementn);
Start:It represents the index from where the method start to extract the
element.
Delete:It is optional.It represents the number of elements to be removed.
element1, element2, ….. , elementn : It is optional. It represent the elements to
be inserted.

Program: Write a javascript code to add element in array using splice method

<html>
<head>

<script language="javascript" type="text/javascript">


var arr1=new Array("C","C++","V","VB.NET");
document.write("Origional array: "+arr1);
arr1.splice(1,0,"C#");
document.write("<br>array after splice method : "+arr1);
</script>

</head>
<body>

</body>
</html>

Output:

20
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

Program: Write a javascript code to remove element in array using splice


method

<html>
<head>

<script language="javascript" type="text/javascript">


var arr1=new Array("C","C++","V","VB.NET");
document.write("Origional array: "+arr1);
arr1.splice(3);
document.write("<br>array after splice method_Remove element : "+arr1);
</script>

</head>
<body>

</body>
</html>

Output:

21
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

In below example splice method start remove operation from 2nd index position
till end.

<html>
<head>

<script language="javascript" type="text/javascript">


var arr1=new Array("C","C++","V","VB.NET","Java");
document.write("Origional array: "+arr1);
arr1.splice(2);
document.write("<br>array after splice method_Remove element : "+arr1);
</script>

</head>
<body>

</body>
</html>

Output:

22
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write a javascript code to add as well as remove elements in array
using splice method.

<html>
<head>

<script language="javascript" type="text/javascript">


var arr1=new Array("C","C++","VB","Python","Java");
document.write("Origional array: "+arr1);
arr1.splice(2,1,"PHP","C#");
document.write("<br>array after splice method : "+arr1);
</script>

</head>
<body>

</body>
</html>

Ouput:

23
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.1.9 Objects as Associative Array:
Associative array are dynamic objects that the user redefines as needed. When you assign
values to keys in a variable of type array, the array is transformed into an object, and it loses
the attributes and methods of array. We can create it by assigning a literal to a variable.

Syntax:
var arrayname={key1:’value1’,key2:’value2’};

Example:
var a={“name”:”sampada”,”rollno”:30};

Program1:

<html>
<body>
<script language="javascript" type="text/javascript">
var a={"name":"sampada","rollno":30,"class":"TYCM"};
document.write("<br>Name : "+a["name"]);
document.write("<br>Roll Number : "+a["rollno"]);
document.write("<br>Class : "+a["class"]);
</script>
</body>
</html>

Output:

24
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

We can create an associative array with the object reserved word, then assign key and values.

Program 2:

<html>
<body>

<script language="javascript" type="text/javascript">


var student=new Object();
student["name"]="sampada";
student["rollnumber"]=30;
student["class"]="TYCM";
document.write("Name : "+student["name"]);
document.write("<br>Roll Number : "+student["rollnumber"]);
document.write("<br>Class : "+student["class"]);
</script>

</body>
</html>

Output:

25
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
FUNCTION
2.2 Function
A function is a subprogram designed to perform a particular task. Functions are executed
when they are called. This is known as invoking a function. Values can passed into functions
and used within in the function. Function always return a value. In javascript ,if no return
value is specified, the function will return undefined.

2.2.1 Defining a function


The function defines by using function keyword with name of function.
A list of parameters names enclosed in parentheses. return keyword is optional.

Syntax:
Function function_name(parameter)
{
Statement
}

2.2.2 Writing a function:


Program:
<html>
<body>
<script language="javascript" type="text/javascript">
function show()
{
document.write("In Show Function");
}
</script>
</body>
</html>

2.2.3 Adding an Arguments


When one or more variables that are declared within the parentheses of a function definition
is known as arguments. These arguments are used to hold data to perform some task.
Program: Write a Javascript code to pass arguments to user define function
<html>
<body>
<script language="javascript" type="text/javascript">
function show(name,rollno)
{
document.write("Student Information is :"+name+rollno);

26
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
}
</script>
</body>
</html>

2.2.4 Scope of Variables and Argument


1.Global Scope: All the variables that you declare, is by default defiend in global scope.
When a variables is declared outside a function with a var keyword then that variable is a
global variable because it is available through all part of script.

2.Local Scope: All variables which are declared using var keyword within function then
those variables are known as local variables and are accessible within function only.

Q: Explain scope of variable declared in function with example

<html>
<body>
<script language="javascript" type="text/javascript">
var a="Hello"; //global variable
function show()
{
var b="Student"; //local variable
document.write("Global variable : "+a);
document.write("<br>Local variable : "+b);
}
show();
</script>
</body>
</html>
Output:

27
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.3 Calling a Function:
2.3.1 Calling a Function with or without Argument
a) Calling a Function without Argument
In Javascript function calling is by using name of function followed by paranthsis.
<html>
<body>
<script language="javascript" type="text/javascript">
function area()
{
var l=10;
var b=20;
document.write("Area of Rectangle : "+(l*b));
}
area();
</script>
</body>
</html>

Output:

b) Calling a Function with Argument


If the function has arguments (parameters) then values for each argument in placed within
parenthesis separated by commas.
<html>
<body>
<script language="javascript" type="text/javascript">
function area(l,b)
{
document.write("Area of Rectangle : "+(l*b));
}
area(10,20);
</script>

28
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
</body>
</html>

Output:

2.3.2 Calling Function from HTML:


In Javascript functions can be called from HTML code in response of any particular event like
page load, unload, button click etc.

Program:
<html>
<body>
<script language="javascript" type="text/javascript">
function show()
{
alert("In show function.....");
}
</script>
<button onclick="show()">Click</button>
</body>
</html>
Output:

29
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.3.3 Function Calling another Function:
In Javascript we can call one function inside another function.
<html>
<body>
<script language="javascript" type="text/javascript">
function insert()
{
document.write("In insert Function......");
}
function show()
{
insert();
}
show();
</script>
</body></html>

Output:

30
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.3.4 Returning a Value from Function:
The return keyword stops the execution of function and the value is return from function to
the function caller.
Syntax:
return value;

Program:Write a Javascript code to return a value from function.


<html>
<body>
<script language="javascript" type="text/javascript">
function addition()
{
var a =10;
var b=20;
return(a+b);
}
var result=addition();
document.write("Addition of two number is : "+ result);
</script>
</body>
</html>

Output:

31
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Intrinsic JavaScript Functions

• An intrinsic function (or built-in function) is a function (subroutine) available for use in a
given programming language whose implementation is handled specially by the compiler.

• JavaScript provides intrinsic (or “built-in”) objects.

Eg. Array, Boolean, Date, Error, Function, Global, JSON, Math, Number, Object, RegExp,
and String objects.

• If an object attribute consists of function, then it is a method of that object, or if an


object attribute consists of values, then it is a property of that object.
document.write("Hello World");

write() is a method of the document object that writes the content “Hello World” on the web
page.

• JavaScript Built-in objects such as

1. Number

2. String

3. RegExp

4. Array

5. Math

6. Date

7. Boolean

Each of the above objects hold several built-in functions to perform object related
functionality.

Number()

• Number() method takes an object as an argument and converts it to the corresponding


number value.

• Return Nan (Not a Number) if the object passed cannot be converted to a number

32
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
• For example
var obj1=new String("123");
var obj2=new Boolean("false");
var obj3=new Boolean("true");
var obj4=new Date();
var obj5=new String("9191 9999");document.write(Number(obj1)); // 123
document.write(Number(obj2)); // 0
document.write(Number(obj3)); // 1
document.write(Number(obj4)); // 1342720050291
document.write(Number(obj5)); // NaN

String()

• String() function converts the object argument passed to it to a string value.

• For example
document.write(new Boolean(0)); // false
document.write(new Boolean(1)); // true
document.write(new Date()); // Tue Jan 05 2021 13:28:00 GMT+0530

parseInt()

• parseInt() function takes string as a parameter and converts it to integer.

• For example
document.write(parseInt("45")); // 45
document.write(parseInt("85 days")); // 85
document.write(parseInt("this is 9")); // NaN

• An optional radix parameter can also be used to specify the number system to be used
to parse the string argument.

• For example,
document.write(parseInt(“10”,16)); //16

parseFloat()

• parseFloat() function takes a string as parameter and parses it to a floating point


number.

• For example
document.write(parseFloat("15.26")); // 15.26
document.write(parseFloat("15 48 65")); // 15

33
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
document.write(parseFloat("this is 29")); // NaN
document.write(pareFloat(" 54 ")); // 54

• An intrinsic function is often used to replace the Submit button and the Reset button
with your own graphical images, which are displayed on a form in place of these
buttons.
<html>
<head>
<title>Using Intrinsic JavaScript Functions</title>
</head>
<body>
<FORM name="contact" action="#" method="post">
<P>
First Name: <INPUT type="text" name="Fname"/> <BR>
Last Name: <INPUT type="text" name="Lname"/><BR>
Email: <INPUT type="text" name="Email"/><BR>
<img src="submit.jpg"
onclick="javascript:document.forms.contact.submit()"/>
<img src="reset.jpg"
onclick="javascript:document.forms.contact.reset()"/>
</P>
</FORM>
</body>
</html>

34
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

2.4 String:
In javascript, string is used for storing and manipulating text. A JavaScript string is zero or
more characters written inside quotes.
Eg: var a=”student”;
String can also be defined as objects with new keyword.
Eg: var a=new String(“student”);
Program: Write a javascript code to declare a string
<html>
<body>

<script type="text/javascript">
var a="student";
document.write("Declare String by Literal Way : "+a);
var b=new String("Computer Technology");
document.write("<br>Declare String as object with new Keyword : "+b);
</script>

</body>
</html>

Output:

35
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
String Length:

To find the length of a string, use the built-in length property.

Program: Write a javascript code to print length of string.

<html>
<body>
<script type="text/javascript">
var a="student";
document.write("String Length : "+a.length);
</script>
</body>
</html>

2.4.1 Manipulate a String:

String manipulation means operations on string like-concatenation, extraction of sub string,


finding length, changing case of string characters, finding position of characters, changing
case of string character etc.

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.

search() It searches a specified regular expression in a given string and returns its
position if a match occurs.

match() It searches a specified regular expression in a given string and returns that
regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis of the specified
starting position and length.

36
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
substring() It is used to fetch the part of the given string on the basis of the specified
index.

slice() It is used to fetch the part of the given string. It allows us to assign positive
as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s
current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s
current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly created array.

trim() It trims the white space from the left and right side of the string.

2.4.2 Joining a String:


String concatenation means joining two strings to create a new string by placing the copy of
second string behind a copy of first string.

i) Using concatenation(+) operartor


var=string1+string2;
In this method,concatenation(+) operator is used to joining two strings.

<html>
<body>
<script type="text/javascript">
var string1="Welcome";
var string2=" Student";
document.write("String Concatenation : "+(string1+string2));
</script>
</body>
</html>

37
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Output:

ii)Using concat()

This method combines one or more strings into the existing one and returns the combined
string. Original string not modified.

The concat() method joins two or more strings.

The concat() method does not change the existing strings.

The concat() method returns a new string.

Syntax
string.concat(string1, string2, ..., stringX)

38
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write Javascript code to implement string concatenation using
concat() of string
<html>
<body>
<script type="text/javascript">
var string1="Welcome";
var a=string1.concat(" Student");
document.write(a);
</script>
</body>
</html>

Output:

39
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.4.3 Retrieving a Character from given Position
i) charAt(): It provides the char value present at the specified index.

Syntax:

string.charAt(index)

Program: Write a Javascript code to retrieve character at specified position


from string.

<html>
<body>
<script type="text/javascript">
var string1="Student";
document.write(string1.charAt(3));
</script>
</body>
</html>

Output:

2.4.4 Retrieving a Position of Character in a String


i) indexOf() : This function searches and returns the index number of the character of
substring within the string.

• The indexOf() method returns the position of the first occurrence of a value in a
string.
• The indexOf() method returns -1 if the value is not found.
• The indexOf() method is case sensitive.

40
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Syntax:
string.indexOf(searchvalue, start)

Parameters
Searchvalue: Required. The string of search for.
Start: optional. The position to startfrom (default is 0)

<html>
<body>
<script type="text/javascript">
var s1="Student";
document.write("indexOf() Method : "+s1.indexOf("d"));
</script>
</body>
</html>
Output:

Program 2:
<html>
<body>
<script type="text/javascript">
var s1="Welcome to computer Technology Department ";
document.write("indexOf() Method : "+s1.indexOf("c" ,6));
</script>
</body>
</html>

41
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Output:

ii) lastIndexOf() : This method searches and returns the index number of last occurance of
the character/substring within the string. Searches the string from end to beginning.

• The lastIndexOf() method returns the index (position) of the last occurrence of a
specified value in a string.
• The lastIndexOf() method searches the string from the end to the beginning.
• The lastIndexOf() method returns the index from the beginning (position 0).
• The lastIndexOf() method returns -1 if the value is not found.
• The lastIndexOf() method is case sensitive.

Syntax
string.lastIndexOf(searchvalue, start)
searchvalue: Required. The string to search for.
Start: Optional. The position where to start. Default value is string length.

Program:
<html>
<body>
<script type="text/javascript">
var s1="Welcome to computer Technology Department ";
document.write("Origional String : "+s1);
document.write("<br>lastIndexOf() Method : "+s1.lastIndexOf("c"));
</script>
</body>
</html>

42
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

Output:

iii)search() : This method searches a string for a specified value and returns the
position of the match.
Syntax
stringName.search(word)

Program: Write a Javascript code to impelement search() method of string.


<html>
<body>
<script type="text/javascript">
var s1="Welcome to computer Technology Department ";
document.write("Origional String : "+s1);
document.write("<br>lastIndexOf() Method : "+s1.search("computer"));
</script>
</body>
</html>

Output:

43
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

2.4.5 Diving Text

i) Split():
• The split() method splits a string into an array of substrings.

• The split() method returns the new array.


• The split() method does not change the original string.
• If (" ") is used as separator, the string is split between words.

Syntax
string.split(separator, limit)
separator : Optional.A string or regular expression to use for splitting. If omitted, an array
with the original string is returned.
Limit: Optional.An integer that limits the number of splits.Items after the limit are excluded.

Program:
<html>
<body>
<script type="text/javascript">
var s1="Welcome to computer Technology Department ";
document.write("Origional String : "+s1);
document.write("<br>Split() Method : "+s1.split(" "));
</script>
</body>
</html>

44
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.4.6 Copying a Sub-String
i) substring(): Returns the character in a string between “from” and “to” indexes. ”To” is
optional and it is omitted then it will searches up to the end of the string.

Syntax:
String.substring(from,to);

Program: Write a javascript code to demonstrate the use of substring()


method of string.

<html>
<body>

<script language="javascript" type="text/javascript">


var a="Welcome to Computer Technology Deapartment";
document.write("Origional String : "+a);
document.write("<br>Substring() Method from index 5 : "+a.substring(5));
document.write("<br>Substring() Method from index 5 to 20 : "+a.substring(5,20));
</script>

</body>
</html>

Output:

ii)substr(): Returns the characters in a string beginning at “start” and through the specified
number of character, ”length”. ”Length” is optional, and if omitted ,up to the end of the string
is assumed.

Syntax:
String.substr(start,length);

45
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write a javascript code to implement substr() method of string.

<html>
<body>

<script language="javascript" type="text/javascript">


var a="Welcome to Computer Technology Deapartment";
document.write("Origional String : "+a);
document.write("<br>Substr() Method from index 5 : "+a.substr(5));
document.write("<br>Substring() Method from index 5 and length is 10: "+a.substr(5,10));
</script>

</body>
</html>

Output:

46
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.4.7 Converting String to Numbers and Numbers to String

i)parseInt(): The parseInt() parses a string() and returns a whole number.

Program:

<html>
<body>

<script language="javascript" type="text/javascript">


var a=45;
var b="34.23"
document.write("First Number is 45 : "+parseInt(a));
document.write("<br>Second Number 34.23 : "+parseInt(b));
</script>

</body>
</html>

Output:

47
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.4.8 Changing the case of string:
i)toUpperCase(): This function will returns the string with all of its character converted to
uppercase.
Syntax:
String.toUpperCase();

Program:
<html>
<body>
<script language="javascript" type="text/javascript">
var a="this is computer department";
document.write("String in Upper Case : "+a.toUpperCase());
</script>
</body>
</html>

Output:

48
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
ii) toLowerCase():This function will return the string with all of its characters converted
to lower case.

Syntax:
String.toLowerCase();

Program:
<html>
<body>

<script language="javascript" type="text/javascript">


var a="THIS IS COMPUTER DEPARTMENT";
document.write("String in Lower Case : "+a.toLowerCase());
</script>

</body>
</html>

Output:

49
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
2.4.9 Finding a Unicode of a Character:
i)charCodeAt(): This function returns the Unicode value of the character at specified
position.
Syntax:
String.charCodeAt(x);

Program:
<html>
<body>
<script language="javascript" type="text/javascript">
var a="THIS IS COMPUTER DEPARTMENT";
document.write("Unicode value of character : "+a.charCodeAt(3));
</script>
</body>
</html>

Output:

50
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
ii) fromCharCode():This method convert a given Unicode number into a character.

Syntax:
String.fromCharCode(n1,n2,n3….,nx)

Program:

<html>
<body>

<script language="javascript" type="text/javascript">


document.write("Uniode value : "+String.fromCharCode(83));
document.write("<br>Uniode value : "+String.fromCharCode(84,115,65));
</script>

</body>
</html>

Output:

51
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program:
Write a Javascript function to count the number of vowels in a given string.
<html>
<body>
<script language="javascript" type="text/javascript">
function vowelsCount()
{
var a=prompt("enter string");
var i,c,count=0;

for(i=0;i<a.length;i++)
{
c=a.charAt(i);

if(c=="a"||c=="A"||c=="e"||c=="E"||c=="i"||c=="I"||c=="o"||c=="O"||c=="u"||c=="U"
)
{
count++;
}
}
document.write("entered String is : "+a);
document.write("<br>Total vowels in the string is :"+count);
}
vowelsCount();
</script>
</body>
</html>

Output:

52
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write a Javascript code to find and display number of duplicate
values in an array.
<html>
<body>
<script language="javascript" type="text/javascript">
var array1=[12,23,12,34,45,34];
count=0;
document.write("Origional Array : "+array1);
for(var i=0;i<array1.length;i++)
{

for(var j=0;j<array1.length;j++)
{

if(i!==j)
{

if(array1[i]===array1[j])
{
document.write("<br> Duplicate entries :"+array1[i]);
count=count+1;

}
}
}

}
document.write("<br> Count : "+(count/2));

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

Output:

53
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
Program: Write a javascript to insert a string within a string at a particular
position.

<html>
<body>
<script language="javascript" type="text/javascript">
function addstr()
{
var Ostring="This is College";
var position=8;
var addstring="SVCP";
document.write("Origional String is : "+Ostring);
var newString=Ostring.slice(0,position)+addstring+Ostring.slice(position);
document.write("<br> after adding new string in existing string : "+newString);
}
addstr();
</script>
</body>
</html>

Output:

Program: Write a Java script that initializes an array called flowers with the
names of 3 flowers. The script then displays array elements.

54
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<script language="javascript" type="text/javascript">
var flowers=["Rose","Lotus","Jasmine"];
document.write(flowers);
</script>
</head>
<body>
</body>
</html>

Write Java script to call function from HTML

<html>
<head>
<script language="javascript" type="text/javascript">
function submit()
{
document.write("Call function from HTML......");
}
</script>
</head>
<body>
Name: <input type="text" name="text1">
<br><br>
<input type="button" name="b1" value="submit" onclick="submit()">
</body>
</html>

55
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

Program: Write a Java script code to display 5 elements of array in sorted


order.

<html>
<head>
<script language="javascript" type="text/javascript">
var arr1=[9,1,7,5,8,3,4];
document.write("Array before Sorting : "+arr1);
document.write("<br>");
document.write("Array after Sorting : "+arr1.sort());
</script>
</head>
<body>

</body>
</html>

Write a JavaScript that initializes an array called “Fruits” with names of five
fruits. The script then displays the array in a message box.
<html>
<head>
<script language="javascript" type="text/javascript">
var fruits=["mango","banana","kiwi","papaya","orange"];

56
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
alert("Array of fruits : "+fruits);

</script>
</head>
<body>

</body>
</html>

Write a Java script program which computes, the average marks of the following students
then, this average is used to determine the corresponding grade.
Student Name Marks
Sumit 80
Kalpesh 77
Amit 88
Tejas 93
Abhishek 65

The grades are computed as follows :

Range Grade
<60 E
<70 D
<80 C
<90 B
<100 A

<html>
<head>
<title>Compute the average marks and grade</title>
</head>
<body>

57
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
<script>
var students = [['Summit', 80], ['Kalpesh', 77], ['Amit', 88], ['Tejas', 93],
['Abhishek', 65]];
var Avgmarks = 0;
for (var i=0; i < students.length; i++) {
Avgmarks += students[i][1];
}
var avg = (Avgmarks/students.length);
document.write("Average grade: " + avg);
document.write("<br>");
if (avg < 60){
document.write("Grade : E");
}
else if (avg < 70) {
document.write("Grade : D");
}
else if (avg < 80) {
document.write("Grade : C");
} else if (avg < 90) {
document.write("Grade : B");
} else if (avg < 100) {
document.write("Grade : A");
}
</script>
</body>
</html>

Differentiate between concat () and join () methods of array object.

58
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

Program: Write a Java script that will replace following specified value with
another value in a string.
String = “ I will fail”
Replace “fail” by “pass”

<html>
<head>
<body>
<script>
var myStr = "I will fail";
var newStr = myStr.replace("fail", "pass");
document.write(newStr);
</script>
</body>
</head>
</html>

Program: Write a JavaScript function that checks whether a passed string is


palindrome or not.

<html>
<head>
<script language="javascript" type="text/javascript">
var newstr="";
var i;
var str=prompt("Enter String");
for(i=str.length-1;i>=0;i--)
{

59
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
newstr+=str[i];
}

if(str==newstr)
{
document.write(str+"String is palindrome ");
}
else
{
document.write(str+"String is not palindrome ");
}
</script>
</head>
<body>

</body>
</html>

Program: Write a function that prompts the user for a color and uses what they
select to set the background color of the new webpage opened.
<html>
<head>
<script language="javascript" type="text/javascript">
function setBackgroundColor() {

var color = prompt("Enter a color");

var newWindow = window.open();

newWindow.document.body.style.backgroundColor = color;

}
</script>
</head>
<body>
<input type="button" id="b1" value="select color" onclick="setBackgroundColor()"/>
</body>
</html>

Write a program to print sum of even numbers between 1 to 100 using for
loop.
<html>
<head>
<script language="javascript" type="text/javascript">
{

60
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
var a;
var sumeven=0;
for(a=2; a<=100; a=a+2)
{
sumeven+=a;
}
document.write("Sum of even number from 1 to 100 : "+sumeven);
}
</script>
</head>
<body>

</body>
</html>

write a javascript function to merge two array & remove all duplicate value
<html>
<head>
<script language="javascript" type="text/javascript">

function removeDuplicate()
{
var arr1=[2,7,9,6];
var arr2=[4,2,6,8,5];
document.write("First Array:"+arr1+"<br>");
document.write("Second Array:"+arr2+"<br>");
var a=arr1.concat(arr2);

document.write("Mearging of two array: "+a);


var arrAll=[];
for(let i of a) {
if(arrAll.indexOf(i) === -1) {
arrAll.push(i);
}
}
document.write("<br>");
document.write("Remove duplicate element and print array: "+arrAll);
}
removeDuplicate();
</script>
</head>
<body>

61
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------

</body>
</html>

Program: Write a javascript function that accepts a string as a parameter and


find the length of the string.
<html>
<head>
<script language="javascript" type="text/javascript">
var str=prompt("Enter string.....");
findLegth(str);
function findLegth(value)
{
document.write("Length of String: "+value.length);
}
</script>
</head>
<body>

</body>
</html>

Write a javascript function generate Fibonacci series till user defined limit.
<html>
<head>
<script language="javascript" type="text/javascript">
function fabonacci()
{

62
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 2 (ARRAY) MRS. S.S. KADAM
--------------------------------------------------------------------------------------------------------------------------------------
var num=parseInt(prompt("Enter limit"));
var n1=0;
var n2=1;
var nextnum;
document.write("Fibonacci Series:");

var i;
for(i=1; i<=num; i++)
{
document.write(n1+ " ");
nextnum=n1+n2;
n1=n2;
n2=nextnum;
}
}
fabonacci();
</script>
</head>
<body>
</body>
</html>

63
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

UNIT:3

Form and Event Handling


(10 Marks)

Contents:

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.

Course Outcome:
Create event based web forms using Java script.

Reference:
1. https://www.tutorialrepublic.com/javascript-tutorial/javascript-events

2. https://www.javatpoint.com/javascript-events

3. https://www.educba.com/javascript-form-events

1
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

UNIT:3
Form and Event Handling (10 Marks)

3.1 Building blocks of a form


HTML Form

An HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.

An HTML form facilitates the user to enter data that is to be sent to the server for processing
such as name, email address, password, phone number etc.

Why use HTML Form

HTML form is used to development of dynamic web application where user enters the input
and based on the user input server sends response to the client.

HTML forms are required if you want to collect some data from of the site visitor.

For example: If a user want to purchase some items on internet, he/she must fill the form
such as shipping address and credit/debit card details so that item can be sent to the given
address.

HTML Form Syntax

<form>
//input controls e.g. textfield, textarea, radiobutton, button
</form>

3.1.1 Properties and Methods of Form:

Attributes can be added to an HTML element to provide more information about how the
element should appear or behave.

Form element attributes are:

Attribute Description

action Specifies where to send the form-data when a form is submitted

method Specifies the HTTP method to use when sending form-data.

2
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

1.GET:by default form method is GET. In this, the form data is appended to
the URL when submitted.

2.POST:The form data is not appended to the URL

name Specifies the name of the form

target Specifies where to display the response that is received after submitting the
form

Values can be set to:

1. _black : the target url will open in new blank window

2._self : the target url will open in same window. Default target is _self

3._parent :the target url will open in parent frameset

4._top: the target url will open in full body of window

Notes on GET:
• Appends the form data to the URL, in name/value pairs
• NEVER use GET to send sensitive data! (the submitted form data is visible in the
URL!)
• The length of a URL is limited (2048 characters)
• Useful for form submissions where a user wants to bookmark the result
• GET is good for non-secure data, like query strings in Google

Notes on POST:
• Appends the form data inside the body of the HTTP request (the submitted form data
is not shown in the URL)
• POST has no size limitations, and can be used to send large amounts of data.
• Form submissions with POST cannot be bookmarked

The HTML form contains following four elements:


Tag Description

<input> It defines an input control.

<textarea> It defines a multi-line input control.

<label> It defines a label for an input element.

3
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

<select> It defines a drop-down list.

<option> It defines an option in a drop-down list.

<button> It defines a clickable button.

Form Object Methods:


1. reset() : The reset() method resets the values of all elements in a form
Event Name: onreset()
2. submit(): The submit() method submits the form
Event Name: onsubmit()

Program: Write a javascript code to implement onsrest event

<html>
<head>
<script language="javascript" type="text/javascript">
function clean()
{
alert("Reset......");
}
</script>
</head>
<body>
<form onreset="clean()">
User Name : <input type="text" name="name"><br>
<input type="reset" value="Reset">
</form>
</body>
</html>
Output:

4
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Program:Write a Javascript code to implement onsubmit event


<html>
<head>
<script language="javascript" type="text/javascript">
function submitdata()
{
alert("Submit......");
}
</script>
</head>
<body>
<form onsubmit="submitdata()">
User Name : <input type="text" name="name"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Output:

3.1.2 Button Element:


In HTML following are three types of button that we can create using <input> element:

1.Submit: submit button send form data to whatever action has been mentioned in the action
attribute of the <form> element. Set the type attribute of the<input> tag to “submit” in order
to place a submit button on a web page

2.Reset: A reset button allows users to clear their web form data. It wipes values from all field
by “reseting” the form to its default appearance.

3.Button:Button will create simple push buttons, which can be programmed to control
custom functionality anywhere on a webpage as required when assigned an event handler
function

5
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Attribute Values

Value Description

button The button is a clickable button

submit The button is a submit button (submits form-data)

reset The button is a reset button (resets the form-data to its initial
values)

Program : Write a HTML code to create types of button on from


<html>
<body>
<form name="form1">
<input type="submit" value="SUBMIT" name="s">
<input type="reset" value="RESET" name="r">
<input type="button" value="CLICK" name="c">
</form>
</body>
</html>
Output:

6
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

3.1.3 Text:
The input element defines an input field. A textbox is created by specifying the
type attribute to “text”.
The <input type="text"> defines a single-line text field.
The default width of the text field is 20 characters.

Attributes Description

Type=” ” It creates a textbox on form

Name=” “ The field name is used to identify the form field

Size=” “ The input field width is specified by the number of


character

Maxlength=” “ Specifies the maximum number of characters allowed


in the input field.
Value=” “ Speciifes the initial text displayed in the field

Program: Write a HTML code to demonstrate Text element with attributes

<html>
<body>
<form name="form1">
<p>Default<br>
<input type="text" name="text1"></p>
<p>Size : 12 and Maxlength : 3 <br>
<input type="text" name="text2" size="12" maxlength="3"></p>
<p>value Attribute : "text value"<br>
<input type="text" value="text value" name="text3"></p>
</form>
</body>
</html>
Output:

7
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

3.1.4 Textarea:

The <textarea> tag defines a multi-line text input control.

The <textarea> element is often used in a form, to collect user inputs like comments or
reviews.

A text area can hold an unlimited number of characters, and the text renders in a fixed-
width font (usually Courier).

The size of a text area is specified by the cols and rows attributes.

The name attribute is needed to reference the form data after the form is submitted.

Attribute Description

cols Specifies the visible width of a text area

name Specifies a name for a text area

rows Specifies the visible number of lines in a text area

wrap Specifies how the text in a text area is to be wrapped when


submitted in a form

Program:Write a HTML code to Textarea on from to accept address from user

<html>
<body>
<form name="form1">
Address<br>
<textarea name="address" cols="20" rows="5">
Enter your address here.....
</textarea>
</form>
</body>
</html>

8
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Output:

3.1.5 Checkbox:
• The INPUT element defines an input field. When you specify “checkbox” for the type
attributes of this element, a checkbox is created.
• The <input type="checkbox"> defines a checkbox.
• The checkbox is shown as a square box that is ticked (checked) when activated.
• Checkboxes are used to let a user select one or more options of a limited number of
choices.
Attributes:
Property Description

checked Sets or returns the checked state of a checkbox

name Sets or returns the value of the name attribute of a checkbox

type Returns which type of form element the checkbox is

value Sets or returns the value of the value attribute of a checkbox

Program:Write a HTML code to create checkbox to accept subject choice from user
<html>
<head>
</head>
<body>
<form name="form1">

9
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Select Subject:<br>
<input type="checkbox" name"subject" value="C" checked>C<br>
<input type="checkbox" name"subject" value="C++">C++<br>
<input type="checkbox" name"subject" value="Java">Java<br>
<input type="checkbox" name"subject" value="Python">Python<br>
</form>
</body>
</html>

Output:

3.1.6 Radio Button:

The HTML <input type=”radio”> is used to define a Radio Button. Radio Buttons are used
to let the user select exactly one option from a list of predefined options. Radio Button input
controls are created by using the “input” element with a type attribute having value as “radio”.
Syntax:
<input type="radio">
Attributes of Radio Button:
Name Description
Type Specifies the type of input, in this case set as ‘radio’.

Name Specifies the name of the control that is delivered to the server.
Value Specifies the value that will be sent to the server, if the radio button is checked.

Checked Defines a by default checked radio button.

Program:Write a HTML code to demonstrate Radio Button


<html>
<head>
</head>
<body>
<form name="form1">
Select Class:<br>
<input type="radio" name="class" value="TYCM-I" checked>TYCM-I<br>
<input type="radio" name="class" value="TYCM-II">TYCM-II<br>

10
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

<input type="radio" name="class" value="TYCM-III">TYCM-III<br>


</form>
</body>
</html>

Output:

3.1.7 Select Element:

Definition and Usage


The <select> element is used to create a drop-down list.
The <select> element is most often used in a form, to collect user input.
The name attribute is needed to reference the form data after the form is submitted (if you
omit the name attribute, no data from the drop-down list will be submitted).
The id attribute is needed to associate the drop-down list with a label.
The <option> tags inside the <select> element define the available options in the drop-down
list.

Attributes of <select> Tag:

Attribute Description

multiple Specifies that multiple options can be selected at once

name Defines a name for the drop-down list

11
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

size Defines the number of visible options in a drop-down list

The <option> tag defines an option in a select list.

<option> elements go inside a <select>, <optgroup>, or <datalist> element.

Attributes of <option> tag:

Attribute Description

value This value is submitted to the server when selected

selected That item is selected in the initial state

Program: Write a HTML code to create various options to select on form

<html>
<head>
</head>
<body>
<form name="form1">
Select Color :<br>
<select name="color" size="2" multiple>
<option value="White" selected>White</option>
<option value="Red" >Red</option>
<option value="BlacK">Black</option>
<option value="Green">Green</option>
<option value="Yellow">Yellow</option>
</select>
</form>
</body>
</html>

12
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Output:

3.2 Form Event:


Attribute Description

onblur Fires the moment that the element loses focus

onchange Fires the moment when the value of the element is


changed
onfocus Fires the moment when the element gets focus

onselect Fires after some text has been selected in an element

Program: Write a javascript code to implement onblur method<html>

<html>
<head>
<script language="javascript" type="text/javascript">
function check()
{
alert("Please enter Roll Number");
}
</script>

13
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</head>
<body>
<form name="form1">
Name <input type="text" name="text1" onblur="check()"><br><br>
Roll Number<input type="text" name="text2">
</form>
</body>
</html>

Output:

3.2.2 onfocus Event

Program:Write a javascript to change the color of textbox by using onfoucs


event.

<html>
<head>

<script language="javascript" type="text/javascript">


function color()
{
document.forms.frm1.text1.style.background="green";
}
</script>

</head>
<body>

<form name="frm1">
Name <input type="text" name="text1" onfocus="color()"><br><br>
Roll Number<input type="text" name="text2">
</form>

14
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</body>
</html>

Output:

3.2.3 onchange Event:

Program: Write a javascript code to demonstrate onchange event

<html>
<head>

<script language="javascript" type="text/javascript">


function check()
{
alert("subject is selected");
}
</script>

</head>
<body>

<form name="form1">
Subject :
<input type="checkbox" name="subject" value="c" onchange="check()">C<br><br>
</form>

</body>

15
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</html>

Output:

Onselect:
Program: Write a javascript code to demonstrate onselect event.
<html>
<head>
<script language="javascript" type="text/javascript">
function check()
{
alert("data is selected");
}
</script>
</head>
<body>
<form name="form1">
Enter Data : <input type="text" name="text2" onselect="check()">

16
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</form>
</body>
</html>

Output:

3.2.1 Mouse Event:


The object mouse has numerous events associated with it which depend up on the user’s
actions.
Following are 7 events which are generated by mouse when it comes in contact of any
HTML tag.

Event Description
onclick Javascript runs when a mouse click
ondblclick Javascript runs when a mouse double click
onmousedown Javascript runs when a mouse button is pressed
onmouseup Javascript runs when a mouse button is released
onmouseover Javascript runs when a mouse pointer moves over an element
onmouseout Javascript runs when a mouse pointer moves out of an element
onmousemove Javascript runs when a mouse pointer moves

1.onclick and ondblclick event:


The onclick event occurs when the user click on an element.

17
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Program: Write a Javascript to implement onclick Mouse Event.


<html>
<head>
<script language="javascript" type="text/javascript">
function check()
{
alert("On Click Event...........");
}
</script>
</head>
<body>
<form name="form1">

<input type="button" name="button1" value="On click Event" onclick="check()">


</form>
</body>
</html>

Output:

2.Ondblclick Event:

The ondblclick event occurs when the user double click on an element.

Program: Write a Javascript to implement ondblclick Mouse Event.


<html>
<head>
<script language="javascript" type="text/javascript">
function check()
{

18
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

alert("On Double Click Event...........");


}
</script>
</head>
<body>
<form name="form1">

<input type="button" name="button1" value="On click Event" ondblclick="check()">


</form>
</body>
</html>

Output:

3. Onmouseover and onmouseout event:


The onmouseover event triggers when you bring your mouse over any element. The
onmouseout event triggers when you move your mouse out from that element.
Program: Write a Javascript code to implement onmouseover and onmouseout Event.
<html>
<head>
<script language="javascript" type="text/javascript">
function out()
{
document.forms.form1.button1.value=" Mouse Out";
}
function over()
{
document.forms.form1.button1.value=" Mouse Over";
}
</script>
</head>
<body>
<form name="form1">
<input type="button" name="button1" value="Button" onmouseover="over()"
onmouseout="out()">

19
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</form>
</body>
</html>

Output:

4. Onmousedown and onmouseup event:


The onmousedown event triggers when you press a mouse button over any element.
Onmouseup event triggers when you release a mouse over an element.

Program:Write a javascript code to implement onmousedown and onmouseup Event.

<html>
<head>
<script language="javascript" type="text/javascript">
function down()
{
document.forms.form1.button1.value=" Mouse down";
}
function up()
{
document.forms.form1.button1.value=" Mouse up";
}
</script>
</head>
<body>
<form name="form1">
<input type="button" name="button1" value="Button" onmousedown="down()"
onmouseup="up()">

20
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</form>
</body>
</html>

Output:

5.onmousemove Event:
The onmousemove event triggers when the mouse pointer is moving within selected
element.
Program:Write a Javascript code to implement onmousemove Event.
<html>
<head>
<script language="javascript" type="text/javascript">
function move()
{
alert ("Mouse Moves....");
}
</script>
</head>
<body>
<form name="form1">
<input type="button" name="button1" value="Button" onmousemove="move()">
</form>
</body>
</html>
Output:

21
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

3.2.2 Key Event:


Following are the three events which are generated by keyboard.
Event Description
onkeydown Javascript runs this event when key is pressed
onkeypress Javascript runs this event when key is pressed and released
onkeyup Javascript runs this event when key is released

Onkeydown and onkeyup Event:


Program: Write javascript code to implement onkeyup and onkeydown event.
<html>
<head>
<script language="javascript" type="text/javascript">
function down()
{
document.forms.form1.button1.value="Key Down....";

22
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

}
function up()
{
document.forms.form1.button1.value="Key up....";
}
</script>
</head>
<body>
<form name="form1">
<input type="text" name="t1" onkeydown="down()" onkeyup="up()">
<input type="button" name="button1" value="Button">
</form>
</body>
</html>
Output:

Onkeypress event:

Program:Write a javasript code to implement onkeypress event

<html>
<head>
<script language="javascript" type="text/javascript">
function press()
{
document.forms.form1.button1.value="Key press....";
}

</script>
</head>
<body>
<form name="form1">
<input type="text" name="t1" onkeypress="press()">
<input type="button" name="button1" value="Button">

23
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</form>
</body>
</html>

Output:

3.2 Form Object and Elements:

24
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Program: Write a javascript code to acess all elements of form using


elements array

<html>
<head>
<script language="javascript" type="text/javascript">
function display()
{
alert("Name: "+document.forms.form1.elements[0].value);
alert("Roll Number: "+document.forms.form1.elements[1].value);
alert("Class: "+document.forms.form1.elements[2].value);
}
</script>
</head>
<body>

25
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

<form name="form1">
Student Name: <input type="text" name="name"><br><br>
Roll Number: <input type="text" name="rollno"><br><br>
Class :<input type="text" name="class1"><br><br>
<input type="button" name="button1" value="Click" onclick="display()">
</form>
</body>
</html>

Output:

getElementsById(“ID”):

This DOM(Document Object Model) method is used for accessing any element
on the page via its ID attribute.

Program: Write a Javascript code to demonstrate getElementById() method.


<html>
<head>
<script language="javascript" type="text/javascript">
function check()
{
var i=document.getElementById("name");
if(i.value!=0)
{
alert("You entered :"+i.value);
}
else
{
alert("Please enter name");
}

26
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

}
</script>
</head>
<body>
<form name="form1">
Student Name: <input type="text" id="name"><br><br>
<input type="button" name="button1" value="Click" onclick="check()">
</form>
</body>
</html>

InnerHTML:
Each HTML element has an innerHTML property that defines both the HTML code and text
that occurs between that elements opening and closing tag. By changing an element’s
innerhtml after some user interaction, you can make such more interactive pages.
However using innerHTML requires some preparation if you want to be able to use it easily
and reliably. First you must give the element you wish to change an id. with that id in place
you will be able to use to the getElementById function, which works on all browsers. After
you have that set up you can now manipulate the text of an element. To start off,lets try
changing the text inside a bold tag.

Program: Write a Javascript code to implement innerHTML property.


<html>
<head>
<script language="javascript" type="text/javascript">
function display()
{
document.getElementById("h").innerHTML="Computer Department";

27
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

}
</script>
</head>
<body>
<h4 id="h">Sou.Venutai Chavan POlytechnic</h4>
<form name="form1">
<input type="button" name="button1" value="Click" onclick="display()">
</form>
</body>
</html>
Output:

3.4 Changing Attribute value dynamically:


In javascript we can change the value of any form elements dynamically.We can change an
attribute of an element by assigning a new value to that attribute in a javascript function and
function can be called when an appropriate event occurs.

Program:Write a javascript to change attribute value dynamically.

<html>
<head>
<script language="javascript" type="text/javascript">
function change(Element)
{
Element.style.color='red';
Element.style.backgroundColor='green';
}

28
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</script>
</head>
<body>
<form name="form1">
Subject :
<input type="text" name="t1" value="CSS" onchange="change(this)"><br>
<input type="button" name"b1" value="Click">
</form>
</body>
</html>

Output:

3.5 Changing Option List Dynamically:


In javascript we can change the value at runtime according to the choice or input from user.
Option list is used to show list of items to user can the select one or more elements. However
you can change the values of option list according to choice or input from user using
javascript functions.

Program:Write a javascript code to change

<script language="javascript" type="text/javascript">


function Display(Elementvalue)
{
with(document.forms.form1)
{
if(Elementvalue==1)
{
option1[0].text="PIC"
option1[0].value=1
option1[1].text="MATHS"

29
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

option1[1].value=2
option1[2].text="WPD"
option1[2].value=2
}
if(Elementvalue==2)
{
option1[0].text="DCC"
option1[0].value=1
option1[1].text="SEN"
option1[1].value=2
option1[2].text="JPR"
option1[2].value=2
}
}
}

</script>
</head>
<body>
<form name="form1">
Subject :
<select name="option1">
<option value="1">DCC</option>
<option value="2">SEN</option>
<option value="3">JPR</option>
</select>
<input type="radio" name="SY" value="1" onclick="Display(this.value)">First Year
<input type="radio" name="SY" value="2" onclick="Display(this.value)">Second Year
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>

Output:

30
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

3.6 Evaluating Checkbox Selection:


Checkbox is used to select one or more items from the set of choices. We can write a
javascript function to evaluate whether checkbox is selected or not and processes the result
as per need of application.
Program: write a javascript code to evaluate checkbox selected by user

<html>
<head>
<script language="javascript" type="text/javascript">
function show()
{
with(document.forms.form1)
{
if(c1.checked==true)
{
alert("C");
}

if(p1.checked==true)
{
alert("PHP");
}

if(c2.checked==true)
{
alert("C++");
}
if(j1.checked==true)
{
alert("Java");
}
}
}

</script>
</head>
<body>
<form name="form1">
Subject :<br>
<input type="checkbox" name="c1" value="C">C<br>
<input type="checkbox" name="p1" value="php">PHP<br>
<input type="checkbox" name="c2" value="C++">C++<br>
<input type="checkbox" name="j1" value="java">Java <br>
<input type="button" value="click" name="button" onclick="show()">
</form>
</body>

31
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

</html>

Output:

3.7 Changing a Label Dynamically


We can change the label of form element using a javascript function to achieve reusability of
an element. Relabeling an element when the purpose of that element is ready been served.

Program: Write a javascript code to change the label of form element


dynamically.

<html>
<head>
<script language="javascript" type="text/javascript">
function show(c)
{
with(document.forms.form1)
{
if(c=='TY')
{
b1.value='SY'
op1[0].text='CSS'
op1[0].value="1"
op1[1].text='STE'
op1[1].value="2"
op1[2].text='OSY'
op1[2].value="3"
}
if(c=='SY')
{
b1.value='TY'
op1[0].text='DCC'

32
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

op1[0].value="1"
op1[1].text='SEN'
op1[1].value="2"
op1[2].text='JPR'
op1[2].value="3"
}
}
}
</script>
</head>
<body>
<form name="form1">
Subject :<br>
<select name="op1" size="3">
<option value="1">DCC</option>
<option value="2">SEN</option>
<option value="3">JPR</option>
</select>
<br><br>
<input type="submit" value="submit" name="submit">
<input type="reset" value="SY" name="b1" onclick="show(this.value)">
</form>
</body>
</html>

Output:

33
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

3.8 Manipulating Form Elements:

we can manipulate the form elements before submitting it to the server.


For that purpose we can keep some of the fields hidden & at the time of submitting the form,
the desired value to the hidden field so that the assigned value for the hidden field can be
submitted.

Program: The user enter roll number and name. The registration id for the student can be
of formed by taking first two character of name followed by the roll number.Initially
registration id field kept hidden and at the time of submitting the form this value is
assigned to registration field

<html>
<head>
<script language="javascript" type="text/javascript">
function show()
{
with(document.forms.form1)
{
if((name.value.length>0)&&(rollno.value.length>0))
{
regid.value=name.value.charAt(0)+name.value.charAt(1)+rollno.value;
var a=regid.value;
alert(a);
}
}
}
</script>
</head>
<body>
<form name="form1">
Name:<input type="text" name="name"><br>
Roll Number: <input type="text" name="rollno"><br>
Registration Id:<input type="hidden" name="regid">
<br><br>
<input type="submit" value="submit" name="submit" onclick="show()">

</form>
</body>
</html>

34
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Output:

3.9 Intrinsic Javascript Functions:


Javascript provides some special set of built in function known as intrinsic functions. There
are some functions to achieve actions of submit and reset button. Intrinsic functions are defined
by javascript hence you can call these functions in your way. Intrinsic functions are used to
replace submit and reset button with some other images.

Program: Write a code to implement intrinsic Javascript function.


<html>
<head>
</head>
<body>
<form name="form1">
Name: <input type="text" name="t1"/>
Age: <input type="text" name="t2"/><br>
<img src="F:\CSS\submit1.png" height="40" width="50" onclick="javascript:document.forms.form1.submit()">
<img src="F:\CSS\reset.png" height="40" width="50" onclick="javascript:document.forms.form1.reset()">
</form>
</body>
</html>

Output:

35
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

3.9.1 Disabling Elements:


Sometimes we need to enable and disable input element like text box, radio button or
checkbox, but everytime we make a change we need to reload the HTML page.An element
can be disabled in HTML by setting disable property to true and enabled again by setting
disabled=false.
In Javascript we can disable some elements to restrict data entry into some elements. Such
disabled elements will be displayed on form but user are notable to enter information in these
elements.Javascript allows writing functions to disable and enable elements on form.

Program:Write a Javascript code to disable form element


<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
fucntion disable()
{
document. forms.form1.t1.disabled=true;
}
function enable()
{
Document .forms.form1.t1.disabled=false;
}
</script>
<form name="form1">
Student Name: <input type="text" name="t1"/><br>
<input type="button" name="b1" value="Disable" onclick="disable()">
<input type="button" name="b1" value="Enable" onclick="enable()">
</form>
</body>
</html>

Output:

36
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

3.9.2 Read only Elements:

In Javascript we can restrict the user from changing the value of an element by setting its
readonly property to true. If we want user to enter value in that element then we can set its
readonly property to false. It is possible to change the value of the readonly attribute from
within your javascript function.

Program: Write a javascript code to implement readonly property of form


element.
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
function readonly()
{
document.forms.form1.t1.readOnly=true;
}
function write()
{
document.forms.form1.t1.readOnly=false;
}
</script>
<form name="form1">
Student Name: <input type="text" name="t1"/><br>
<input type="button" name="b1" value="Read Only" onclick="readonly()">
<input type="button" name="b1" value="Write" onclick="write()">
</form>
</body>
</html>

37
Client SIDE Scripting Language (CSS)-UNIT 3 Mrs. S.S.Kadam

Output:

38
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

UNIT:4

Cookies And Browser


Data

[08 Mark]

Contents:

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.

Course Outcome:
Use JavaScript for handling cookies.

Reference:
1. https://www.w3schools.com/js/js_cookies.asp

2. https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

3. https://stackoverflow.com/questions/11219582/how-to-detect-my-browser

4. https://www.studytonight.com/javascript/javascript-browser-object-model

1
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

Unit 04
Cookies and Browser Data
[8 marks]

4.1 Cookies

A cookie is a small amount of named data stored by the web browser and associated with a
particular web page or web site. Cookies are used to store information as well as access information.
Cookie is a small text file stored in the subfolder of the browsers installation folder. It contains following
data: name-value pair, expiry date for that cookie.

There are two types of cookies namely, session cookies (non-persistent) and persistent cookies
• Session cookies are created temporarily in your browser’s subfolder while you are visiting a
website. Once you leave the site, the session cookie is deleted.
• Persistent cookie files remain in your browser’s subfolder and are activated again once you visit
the created the particular cookie. A persistent cookie remains in the browser’s subfolder for the
duration period set within the cookie’s file.

4.1.1 Writing/Creating a Cookie


JavaScript can create cookies with the document.cookie property
Document.cookie = “username=Meenakshi”;

Program: Creating Cookie


<html>
<script>
function disp()
{
document.cookie="username=sampada";
alert('created cookie....');
}
</script>
<body>
<form>
<input type="button" name="b1" value=" create Cookies" onclick="disp()">

2
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

</form>

</body>
</html>

4.1.2 Reading a Cookie


We can then use document.cookie whenever we want to access the cookie. With
JavaScript, cookies can be read like this: var x = document.cookie;

Program :Read Cookies

<html>
<script>
function disp()
{
document.cookie="username=sampada";
alert('created cookie....');
}
function read()
{
alert(document.cookie);
}
</script>
<body>
<form>
<input type="button" name="b1" value=" create Cookies" onclick="disp()">
<input type="button" name="b2" value="Read Cookies" onclick="read()">
</form>
</body>
</html>
4.1.3 Deleting a Cookie
Deleting a cookie is very simple, just set the expires parameter to a passed date:
document.cookie = “username=; expires=Thu, 01 Jan 1970 00:00:00 GMT”;

3
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return
nothing. To do this, you just need to set the expiry date to a time in the past.
<html>
<script>
function disp()
{
document.cookie="username=sampada; expires=Thu, 18 Dec 2021 12:00:00 UTC; ";
alert('cookie....Created');
}
</script>

<body>
<form>
<input type="button" name="b1" value="Cookies" onclick="disp()">
</form>
</body>
</html>

4.1.5 Setting the expiration Date of Cookie

The expiration date is typically an increment of the current date. JavaScript can create, read,
and delete cookie with the document.cookie property.

document.cookie=”username=Meenakshi; expires=Thu, 18 Dec 2020 12:00:00 GMT”

4.2 Browser
• The window object represents a window in browser.
• An object of window is created automatically by the browser.
• It is used to control the browser window lifecycle and perform various operations on it.
• Whenever you open a new window or tab, a window object representing that window/tab
is automatically created.
• Window is the object of browser, it is not the object of javascript

4.2.1 Opening a Window


open() function –
▪ It is used to open a new window from current window.
▪ It is invoked on window object
Syntax: window.open(url, name, style);

4
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

url: URL of the new page going to be open in new Window.


name: to set the name of the window (optional).
style: such as scrollbar, toolbar, height, width, location, etc. (optional).

Style Parameter:
toolbar= yes|no|1|0 To display the browser toolbar

status= yes|no|1|0 To add a status bar

titlebar= yes|no|1|0 To display the title bar

menubar= yes|no|1|0 To display the menubar

fullscreen=yes|no|1|0 To display the browser in full screen mode

resizable=yes|no|1|0 To determine whether the window is resizable

scrollbars= yes|no|1|0 To display scroll bars

height=pixels The height of window minimum value is 100

width=pixels The width of the window

left=pixels The left position of the window

top=pixels Top position of window

Program: Open a New Window


<html>
<script>
function openwin()
{
window.open("http://www.google.com","","left=100,top=100,width=200,height=100");
}
</script>
<body>
<form name="frm1">
<input type = "button" value = "Open" onclick = "openwin()">
</form>
</body>
</html>
5
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

4.2.2 focus() function


It is used to focus on the new open window
Syntax: - window.focus();

Program: Changing Focus of Window

<html>
<script>
function disp()
{
var myWin1=window.open("http://www.google.com","GPage","height=200,width=100");
var myWin2=window.open("http://www.yahoo.com","yPage","height=200,width=100");
myWin1.focus();
}
</script>
<body>
<form>
<input type="button" name="b1" value="Open" onclick="disp()">
</form>
</body>
</html>

4.2.3 Window position


can set the specified position to the new window.
The attributes left and top are used to specify the position of the new window.
window.open("","“,”left=0, top=0, width=200,height=100”);

6
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

Program: Setting the position of new Window


<html>
<head>
<script>
function openwin()
{
window.open("","",”left=100, top=100, width=200,height=100”);
}
</script>
</head>
<body>
<form name="frm1">
<input type = "button" value = "Open" onclick = "openwin()">
</form>
</body>
</html>

4.2.4 Changing the content of window


• We can change the content of newly opened window.
• Example- you want the window to display a product each time a customer selects the item
on your web page.
• The secret to changing the content of a window is to call the open() method using the same
window name each time you change the content of the window.

Program: Changing Content of Newly opened Window (Image)

<html>
<script>
function openwin(ad)
{
var MyWin=window.open(ad,"w1","width=200,height=100");

7
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

}
</script>
<body>
<form name="frm1">
<input type = "button" value = "Samsung Galaxy M31" onclick = "openwin('M31.jpg')">
<input type = "button" value = "Apple iPhone 7" onclick = "openwin('iPhone.jpg')">
<input type = "button" value = "Mi" onclick = "openwin('Desert.jpg')">
</form>
</body>
</html>

Program : Changing Content of Newly opened Window(URL)


<html>
<script>
function openwin(ad)
{
var MyWin=window.open(ad,"w1","width=200,height=100");
}
</script>
<body>
<form name="frm1">
<input type = "button" value = "Gmail" onclick = "openwin('http://www.gmail.com')">
<input type = "button" value = "Yahoo" onclick = "openwin('http://www.yahoo.com')">
<input type = "button" value = "Facebook" onclick =
"openwin('http://www.facebook.com')">
</form>
</body>
</html>

4.2.5 Closing the window


• Is used to close any window.
• the open() method returns a reference to the newly opened window, which is a window
object. You use the reference to call the close() method.
Syntax: window.close();
• Note: A current window/tab will only get closed if and only if it was created &
opened by that script. Means the window.close syntax is only allowed for the
window/tab that is created & opened using window.open method.

Program: Closing a Window


<html>
8
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

<script>
var MyWin;
function openwin()
{
MyWin=window.open("","w1","width=200,height=100");
}
function closewin()
{
MyWin.close();

}
</script>
<body>
<form name="frm1">
<input type = "button" value = "Open" onclick = "openwin()">
<input type = "button" value = "Close" onclick = "closewin()">
</form>
</body>
</html>

4.2.6 scrollTo() and scrollBy()


4.2.6.1 scrollTo() –
• scrollTo() is used to scroll to a particular set of coordinates in the document.
• It scrolls to the document to the specified coordinates.
Syntax: window.scrollTo(x-coord, y-coord)
x-coord – The coordinate to scroll to, along the x-axis (horizontal) in pixels
y-coord- The coordinate to scroll to, along the Y-axis (vertical) in pixels

Program: scrollTo()
<html>
<head>
<style>
body {
width: 5000px;
}
</style>
<script>
function STo() {
window.scrollTo(300, 500);
}
</script>
</head>
9
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

<body>
<form>
<input type="button" value="ScrollTo" onclick="STo()">
</form>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
10
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
</body>
</html>

4.2.6.2 scrollBy()
• It is used to scroll the document by given number of pixels.
Syntax: window.scrollBy( xcoordinate, ycoordinate );
x-coordinate: is the horizontal pixel value that you want to scroll by.
11
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

y-coordinate: is the vertical pixel value that you want to scroll by.

Program: scrollBy ( )
<html>
<head>
<style>
body {
width: 5000px;
}
</style>
<script>
function scrollWin() {
window.scrollBy(800, 0);
}
</script>

</head>
<body>
<form>
<input type="button" value="ScrollBy" onclick="scrollWin()">
</form>

</body>
</html>

4.2.7 Multiple Windows at a glance:


We can open multiple windows by using window.open( ) function multiple times. Also we can
use loop to open multiple windows. The last opened window will get the focus by default.

Program: Multiple Windows at Glance without Loop


<html>
<script>
function disp()
{
var myWin1=window.open("http://www.google.com","GPage","height=100,width=100");
var myWin2=window.open("http://www.yahoo.com","YPage","height=100,width=100");
var myWin3=window.open("http://www.facebook.com","FPage","height=100,width=100");
var myWin4=window.open("http://www.rediff.com","RPage","height=100,width=100");
}
</script>
<body>
<form>
<input type="button" name="b1" value="Open" onclick="disp()">

12
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

</form>
</body>
</html>

Program: Multiple Windows at glance using Loop


<html>
<script>
function disp()
{
for(var i=0;i<=7;i++)
{
window.open("","","height=100,width=100");
}
}
</script>
<body>
<form>
<input type="button" name="b1" value="Open" onclick="disp()">
</form>
</body>
</html>

4.2.8 Creating Web Page in a new Window


• Can design a newly created window using write() function
• Can pass html code as a string parameter to write()
• Syntax: - win_refence.document.write(“<htmlcode>”);

13
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

• Example: - MyWin1.document.write(“<b> Welcome</b>”);

Program: Creating a web page in a new window


<html>
<script>
function disp()
{
var w1=window.open(","","height=100,width=100");
w1.document.write("<html>");
w1.document.write("<head>");
w1.document.write("<title> My New Page </title></head>");
w1.document.write("<body>");
w1.document.write("<h2> This is Child Web Page</h2>");
w1.document.write("</body></html>");
}
</script>
<body>
<form>
<input type="button" name="b1" value="Open" onclick="disp()">
</form>
</body>
</html>

4.2.8 Javascripts in URLs:


Javascript code can be used with the URL by using ‘javascript’ pseudo-protocol specifier. The
pseudo-protocol specifier that the body of URL is an arbitrary javascript code. This code is going to
be interpreted by the javascript interpreter.

For example:javascript:alert(“hello world”);

If the javascript code in a javascript: URL contains multiple statements, the statements need to be
separated by semicolon.
14
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

Such a URL looks like: javascript:var now=new Date();”The time is ”+now;

When the browser “loads” these Javascript URLs, it executes the Javascript code to present in that
URL and displays the result. For security reasons the recent browsers are not allowing to execute the
javascript code in URLs.

4.2.9 Javascript Security:

There are several Javascript security issues that needs to be considered. As a javascript used in
client side, a risk is there for end users. It enables malicious users to send scripts over the web and run
them on client computers. There are two measures need to be considered. We should use scripts
separately so that the malicious users can only access certain resources and perform tasks. The second
measures is we should implement the same origin policy i.e. we must use the script from only one site,
which prevents scripts of one site from accessing data from script of other sites.

Cross-site scripting (XSS) is one of the most common javascript security vulnerability. Cross-Site
Scripting vulnerabilities allow malicious users to manipulate websites to manipulate websites to return
malicious script to the users. These malicious scripts then execute on the client web browsers. It can
be result in user data theft, account tampering, malware spreading or remote control over a user
browser.

Cross-Site Request Forgery(CSRF) is another common javascript security vulnerability. It allows


attackers to manipulate users browsers to take venerable actions on other sites. It happens due to target
sites authenticate the request based on the users cookie. Attackers are able to send requests using users
cookies. This Javascript security issue causes account tampering, data theft, fraud and more.

4.2.10 Timers
Sometimes there is a need of asynchronous code execution
Javascript provides certain in-built functions which allow us to schedule tasks to be executed
after a specific amount of time.
Example -use timers to change the advertisement banners at regular intervals, or display a real-
time clock, etc.
Two Timer functions –
setTimeout()
setInterval()

4.2.11.1 setTimeout()
15
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

• This method executes a particular function after a certain period of time.


• Syntax: - setTimeout(function, milliseconds)
Function - the function to execute
Miliseconds-which is the number of milliseconds representing the amount of time to wait
before executing the function (1 second = 1000 milliseconds). By default, the value is set
to 0.
Program: setTimeout( )
<html>
<body>
<script>
function myFunction()
{
alert('Hello World!');
}
</script>
<form name="frm1">
<input type="button" name="b1" value="Click Me" onclick="setTimeout(myFunction,
2000)">
</form>
</body>
</html>

Program: setTimeout( )
<html>
<body>
<script>
function myFunction()
{
setTimeout(disp, 2000);
}
function disp()
{
alert('Hello World!');
}
</script>
<form name="frm1">
16
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

<input type="button" name="b1" value="Click Me" onclick="myFunction()">


</form>
</body>
</html>

4.2.11.2 setInterval ( )
This method repeatedly executes a particular function repeatedly at fixed time intervals.
Syntax – setInterval (function, milliseconds)
Parameters –
function-the function to execute,
Interval- which is the number of milliseconds representing the amount of time to wait
before executing the function (1 second = 1000 milliseconds)

Program: setInterval ( )
<html>
<body>
<script>
function disp()
{
alert('Hello Students!');
}
</script>
<form name="frm1">
<input type="button" name="b1" value="Click Me" onclick="setInterval(disp,5000)">
</form>
</body>
<html>

17
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

Program: setInterval ( )
<html>
<script>
function disp()
{
var d = new Date();
document.getElementById("p1").innerHTML = d;
}
</script>
<body>
<p id="p1"> </p>
<form name="frm1">
<input type="button" name="b1" value="Click Me" onclick="setInterval(disp,5000)">
</form>
</body>
</html>

4.2.11 Browser Location

 The location property of a window is a reference to a Location object, it represents the current
URL of the document being displayed in that window.
Syntax - window.location.propertyname
▪ window.location.href: It returns the URL of the current working page.
▪ window.location.hostname: It returns the domain name of web host.
▪ window.location.pathname: It returns the path and filename of the current working page.
▪ window.location.protocol: It returns the used protocol (http: or https:).
▪ window.location.port(): It prints the port number.
▪ window.location.host(): It prints host name along with port number.
▪ window.location.assign(): It loads new document.

18
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

Program: Browser Location


<html>
<body>
<script>
function disp()
{
document.write("Href =" + window.location.href + "<br>");
document.write("Hostname =" + window.location.hostname+ "<br>");
document.write("Pathname ="+ window.location.pathname+ "<br>");
document.write("Protocol ="+window.location.protocol+ "<br>");
document.write("Port ="+window.location.port+ "<br>");
document.write("Host ="+window.location.host+ "<br>");
}
</script>
<form name="frm1">
<input type="button" name="b1" value="Show" onclick="disp()">
</form>
</body>
</html>

Program: load new page using assign property


<html>
<body>
<script>
function pgload()
{
window.location.assign("https://www.google.com");
}
</script>
<form name="frm1">
<input type="button" name="b2" value="Google" onclick="pgload()">
</form>
</body>
19
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

</html>

4.2.13 History
 The history property of the Window object refers to the History object.
 It contains the browser session history, a list of all the pages visited in the current frame or window.
 Syntax – window.history.property/method

Property:
▪ Length - it is used to return the number of URLs in the list of history.
Methods:
▪ back() - it is used to load the previous URL in the history list.
▪ forward() - it is used to load the next URL in the history list.
▪ go() - it is used to load a specific URL from the history list.

Program: Length property


<html>
<script>
function getViews()
{
alert("You've accessed " + history.length + " web pages in this session.");
}
</script>
<body> <form name="frm1">
<input type="button" name="b1" value="Views" onclick="getViews()">
</form>
</body>
</html>

20
Client-Side Scripting-CSS –UNIT:4 Mrs. S.S. Kadam

Program:
<html>
<script>
function pgLoad()
{
window.location.assign("https://www.google.com");
}

function goBack()
{
window.history.back();
}

function goForward()
{
window.history.forward();
}

</script>
<body> <form name="frm1">
<input type="button" name="b1" value="Load" onclick="pgLoad()">
<input type="button" name="b2" value="Back" onclick="goBack()">
<input type="button" name="b2" value="Forward" onclick="goForward()">
</form>
</body>
</html>

21
UNIT:5

Regular Expression, Rollover And Frame

[14 Mark]

Contents:

5.1 Regular Expression language of regular expression, finding non matching characters,
entering a range of characters, matching digits and non digits, matching punctuations and
symbols, matching words, replacing a the text using regular expressions, returning the
matched characters, regular expression object properties.

5.2 Frames - create a frame, invisible borders of frame, calling a child windows, changing a
content and focus of a child window, writing to a child window, accessing elements of
another child window.

5.3 Rollover creating rollver, text rollver, Multiple actions for rollover, more efficient rollover.

Course Outcome:

Create interactive webpage using regular expressions for validations.

Reference:
1. https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Regular_expressions

2. https://www.geeksforgeeks.org/javascript-regexpregular-expression

3. https://stackoverflow.com/questions/9423693/javascript-function-definition-
syntax

4. https://www.oreilly.com/library/view/javascript-application-
cookbook/1565925777/ch06s05
CLIENT SIDE SCRIPTING UNIT-5(REGULAR EXPRESSION) MRS. S.S. KADAM

Programs on Regular Expression


Finding Non-Matching Characters-
<html>
<script>
var re1=/[^abc]/;
var s=prompt("Enter String");
if(re1.test(s))
{
document.write(s+" does not contain abc");
}
else
{
document.write(s+" contain abc");
}
</script>
<body>
</body>
</html>

Entering range of Characters –


<html>
<script>
var re1=/[0-9]/;
var s=prompt("Enter String");
if(re1.test(s))
{
document.write(s+" contain number");
}
else
{
document.write(s+" does not contain number");
}
</script>
<body>
</body>
</html>

Matching Digits -
<html>
<script>
var re1=/\d/;
var s=prompt("Enter String");
if(re1.test(s))
{
document.write(s+" contain Digit");
CLIENT SIDE SCRIPTING UNIT-5(REGULAR EXPRESSION) MRS. S.S. KADAM

}
else
{
document.write(s+" does not contain Digit");
}
</script>
<body>
</body>
</html>

Matching Non-Digits -
<html>
<script>
var re1=/\D/;
var s=prompt("Enter String");
if(re1.test(s))
{
document.write(s+" contain Non-Digit");
}
else
{
document.write(s+" contain Digit");
}
</script>
<body>
</body>
</html>

Matching Punctuations and Symbols – check other than special symbols


<html>
<script>
var re1=/\w/;
var s=prompt("Enter String");
if(re1.test(s))
{
document.write(s+" contain letter/number/punctuation");
}
else
{
document.write(s+" does not contain letter/number/punctuation");
}

</script>
<body>
</body>
</html>
CLIENT SIDE SCRIPTING UNIT-5(REGULAR EXPRESSION) MRS. S.S. KADAM

Matching Punctuations and Symbols – check only special symbols


<html>
<script>
var re1=/\W/;
var s=prompt("Enter String");
if(re1.test(s))
{
document.write(s+" contain special symbols");
}
else
{
document.write(s+" does not contain special symbols");
}
</script>
<body>
</body>
</html>

Matching Words – to find exact word including spaces.


<html>
<script>
var re1=/\bBob\b/;
var s="bob Welcome";
document.write(re1.test(s));
</script>
<body>
</body>
</html>

Matching Words – to find word without any consideration


<html>
<script>
var re1 = /\BON/;
var str = "HELLO JHON";
var result = re1.test(str);
document.write(result);
</script>
<body>

</body>
</html>
CLIENT SIDE SCRIPTING UNIT-5(REGULAR EXPRESSION) MRS. S.S. KADAM

Replacing Text with Regular Expression –


<html>
<script>
var re1 = /\bBob\b/;
var str = "Good Morning Bob";
document.write("Before Replacement = "+str);
var result = str.replace(re1, 'Mary');
document.write("<br>After Replacement = "+result);
</script>
<body>
</body></html>

Return the matched Character –


<html>
<script>
var str = 'Hello Bob';
var re1 = /bob/i;
var result;
result = re1.exec(str);
document.write(result);
</script>
<body>
</body>
</html>
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

Frame:
HTML frames are used to divide your browser window into multiple sections where each
section can load a separate HTML document. A collection of frames in the browser window is
known as a frameset. The window is divided into frames in a similar way the tables are
organized: into rows and columns.

Creating Frames

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:


 cols: The cols attribute is used to create vertical frames in a web browser. This attribute
is basically used to define the no. of columns and their size inside the frameset tag.
 rows: The rows attribute is used to create horizontal frames in the web browser. This
attribute is used to define the no. of rows and their size inside the frameset tag.

Attributes of <frame> tag:


 name: This attribute is used to give names to the frame. It differentiate one frame
from another. It is also used to indicate which frame a document should loaded into.
 src: This attribute in frame tag is basically used to define the source file that should
be loaded into the frame.The value of src can be any url.
 marginwidth: This attribute in frame tag is used to 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 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 in frame use scrollbar attribute in
frame tag. This is basically used to control the 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.
 border: This attribute of frameset tag defines the width of the border of each frame
in pixels. Zero value is used for no border.
 frameborder: This attribute of frameset tag is used to specify whether a three-
dimensional border should be displayed between the frames or not for this use two
values 0 and 1, where 0 defines no border and value 1 signifies for yes there will be a
border.

Following program arrange the frame horizontally one after another by using
cols attribute.
<html>
<frameset cols="25%,75%">
<frame name="frame1" frameborder="1" />
<frame name="frame2" frameborder="1"/>
</frameset>
</html>

1
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

Following program arrange the frame vertically one after another by using
rows attribute.

<html>
<frameset rows="15%,35%,50%">
<frame name="frame1" frameborder="1" />
<frame name="frame2" frameborder="1"/>
<frame name="frame3" frameborder="1"/>
</frameset>
</html>

Following program arrange the frame by using rows and cols attributes.
<html>
<frameset rows="15%,35%,50%" cols="40%,60%">
<frame name="frame1" frameborder="1" />
<frame name="frame2" frameborder="1"/>
<frame name="frame3" frameborder="1"/>
<frame name="frame4" frameborder="1"/>
<frame name="frame5" frameborder="1"/>
<frame name="frame6" frameborder="1"/>
</frameset>
</html>

2
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

Nested frames:
Program1:
<html>
<frameset rows="10%,*,15%">
<frame src="frame1.html" name="frame1"/>
<frameset cols="60%,40%">
<frame src="frame2.html" name="frame2"/>
<frame src="frame3.html" name="frame3"/>
</frameset>
<frame src="frame4.html" name="frame4"/>
</frameset>
</html>

Program2:
<html>
<frameset rows="60%,40%">
<frameset cols="30%,30%,*">
<frame src="frame1.html" name="frame1"/>
<frame src="frame2.html" name="frame2"/>
<frame src="frame3.html" name="frame3"/>
</frameset>

3
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

<frame src="frame4.html" name="frame4"/>


</frameset>
</html>

Following program load webpages in each frame

Main_frame.html Frame1.html

<html> <html>
<frameset cols="40%,30%,30%"> <body bgcolor="green">
<frame src="frame1.html" This is frame1
name="frame1" frameborder="1" /> </body>
<frame src="frame2.html" </html>
name="frame2" frameborder="1"/>
<frame src="frame3.html"
name="frame3" frameborder="1"/>
</frameset>

4
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

</html>

Frame2.html Frame3.html
<html>
<html> <body bgcolor="yellow">
<body bgcolor="pink"> This is frame3
This is frame2 </body>
</body> </html>
</html>

Invisible Border of Frame:

Frame get border by default.If we want to set the border of a frame invisible, then we need to set
the attribute frameborder =0 and border=0.

Javascript program to set the invisible border of a frame

<html>
<frameset cols="40%,30%,30%">
<frame src="frame1.html" name="frame1" frameborder="0" border="0"/>
<frame src="frame2.html" name="frame2" frameborder="0" border="0"/>
<frame src="frame3.html"name="frame3" frameborder="0" border="0"/>
</frameset>
</html>

5
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

Program:
Write a javascript for creating following frame structure:

TYIF
Frame1
Client Side Scripting This is Frame 3
 Chapter 1 Frame3
Frame2  Chapter 2

Chapter1 and chapter2 are linked to webpage ch1.html &ch2.html


respectively. When user click on these links corresponding data appears in frame3.

Mainframe.html Frame1.html
<html> <html>
<frameset rows="15%,75%"> <body>
<frame src="frame1.html" name="frame1"/> <h4
<frameset cols="40%,60%,"> align="center">TYIF</h4>
<frame src="frame2.html" name="frame2"/> </body>
<frame src="frame3.html" name="frame3"/> </html>
</frameset>
</frameset>
</html>
Frame2.html: Frame3.html
<html>
<body> <html>
<h4>Client Side Scripting</h4> <body>
<ul> This is frame3
<a href="F:/frame\ch1.html" target="frame3"><li>Chapter </body>
1</li></a> </html>

<a href="="F:/frame\ch2.html" target="frame3"><li>Chapter


2</li></a>
<ul>
</body>
</html>
Ch1.html Ch2.html
<html> <html>
<body> <body>
<h4>Chapter 1</h4> <h4>Chapter 2</h4>
Introduction to Javascript.<br> Array<br>
Data types in Javascript<br> Function<br>
Operator in javascript<br> String<br>
Control statement<br> </body>
Looping Statement<br> </html>
object in Javascript<br>
</body>
</html>

6
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

Output:

Calling a child window:


We can define one or more than one frame in a web page, then that web page become
parent window for other frames. web pages present in frame become child window.

7
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

Changing the content and focus of child window:


We can assign new source t child window by using href attribute

8
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

Assessing element of another child window:

Mainframe.html Frame2.html

<html> <html>
<frameset cols="40%,60%"> <body>
<frame src="frame1.html" name="frame1"> <h1>Frame2</h1>
<frame src="frame2.html" name="frame2"> <p id="p1">In frame 2</p>
</frameset> </body>
</html> </html>
Frame1.html

html>
<script>
function display()
{
parent.frame2.document.getElementById("p1").innerHTML="Access element from
frame1";

}
</script>
<body>
<h1>Frame1</h1>
<input type="button" name="b1" value="click" onclick="display()">
</body>
</html>

9
CLIENT SIDE SCRIPTING(CSS) UNIT-5 S.S. KADAM

10
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 5 MRS. S.S.KADAM

Roll Over:
 Rollover means a webpage changes when the user moves his or her mouse over an object
on the page.
 The rollover effect is mainly used in webpage designing for advertising purpose.

creating Rollover-
on many web pages, JavaScript rollovers are handled by adding an onmouseover() and onmouseout
() event on images or text.
1) onmouseover () is triggered when the mouse move over an element.
2) onmouseout () is triggered when the mouse moves away from the element

Text Roll Over:


 In text rollover, user rollover the text.
 Javascript allows to change the page. element usually some graphics image

<html>
<script>
function over()
{
document.getElementById("i1").src="apple.jpg";
}
function out()
{
document.getElementById("i1").src="kiwi.jpg";
}
</script>
<body>
<h1>Text Rollover</h1>
<h2 id="t1" onmouseover="over()" onmouseout="out()"> Fruits </h3>
<img id="i1" src=" E:\CSS\Rollover\textrollover\fruits.jpg">
</body>
</html>

1
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 5 MRS. S.S.KADAM

Image Rollover:
<html>
<script>
function over()
{
document.getElementById("i1").src="up.jpg";
}
function out()
{
document.getElementById("i1").src="sad.jpg";
}
</script>
<body>
<h1>Image Rollover</h1>
<img id="i1" src="F:\CSS\Chapter 5\Rollover\happy.jpg" onmouseover="over()"
onmouseout="out()">
</body>

</html>

Multiple Roll over:


 suppose user is rolling the cursor over the text, then instead of simply changing the
image we can display more window displaying some feature or additional info about
the item on which the mouse is rolling over. This process is referred a multiple actions
for rollover.
 Due to this effect visitors get more info at glance.

<html>
<script>
function over()
{
document.getElementById("i1").src="apple.jpg";
document.getElementById("p1").innerHTML="Develop resistance against infection";

2
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 5 MRS. S.S.KADAM

}
function out()
{
document.getElementById("i1").src="kiwi.jpg";
document.getElementById("p1").innerHTML="Increases Bone Mass";
}
</script>
<body>
<h1>Fruits</h1>
<img id="i1" src="F:\CSS\RollOver\multiple\fruits.jpg" onmouseover="over()" onmouseout="out()">
<p id="p1"> Reasons to Eat Fruits </h3>
</body>
</html>

More Efficient Roll over:


The images can be stored in array & required images are displayed when the webpage is
loaded.

This makes the rollover action efficient because the images are already collected & loaded in
array. The required image is displayed when user rollover particular text.

<html>
<script>
{
f1=new Image;
f2=new Image;
if(document.images)
{
f1.src="apple.jpg";
f2.src="kiwi.jpg";
}
}

3
CLIENT SIDE SCRIPTING LANGUAGE (CSS)-UNIT 5 MRS. S.S.KADAM

</script>
<body>
<h1>Fruits</h1>
<img name="i1" src=" ">
<br>
<b onmouseover="document.i1.src=f1.src">
Apple </b>
<br><br>
<b onmouseout="document.i1.src=f2.src">
Kiwi </b>
</body>
</html>

4
UNIT:6

Menus, Navigation and Web Page Protection

[12 Mark]

Contents:
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 pulidown menu, dynamically changing a menu, validating menu
selection, Floating menu, chain select menu, tab menu, pop-up 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 Frameworks of javasript and its application.

Course Outcome:
Create Menus and navigations in web Pages.

Reference:

1. https://www.w3schools.com/howto/howto_js_dropdown.asp

2. https://www.codingninjas.com/studio/library/javascript-dom-navigation

3. https://jscrambler.com/blog/the-most-effective-way-to-protect-client-side-
javascript-applications

4. https://www.veracode.com/security/javascript-security

You might also like