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

Javascript

The document discusses JavaScript, including its introduction, types of scripts and examples, DOM objects, form validation, and dynamic effects. It covers JavaScript fundamentals, control and looping structures, different implementation methods, and event handling. Key topics include JavaScript variables and scopes, output methods like innerHTML and document.write, keywords, and operators. The objectives are to learn JavaScript structures, control flows, implementations, and event handling concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Javascript

The document discusses JavaScript, including its introduction, types of scripts and examples, DOM objects, form validation, and dynamic effects. It covers JavaScript fundamentals, control and looping structures, different implementation methods, and event handling. Key topics include JavaScript variables and scopes, output methods like innerHTML and document.write, keywords, and operators. The objectives are to learn JavaScript structures, control flows, implementations, and event handling concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

JavaScript

 Introduction to JavaScript
 Math, Date and String
 Types of Scripts with suitable objects with Example
 example  DOM Objects
 Control and looping structure  Form Validation
 Various Operators in Javascript  Dynamic effect using
 Array its Types JavaScript
 Event Handling with Example

1 International Institute of Management MASTER OF COMPUTER


Science (IIMS) APPLICATION
Unit Objective

I. To learn the fundamentals of JavaScript


II. To learn the Control and looping structure of JavaScript.
III. To understand the different ways of implementation of
Javascript.
IV. To learn the Event handling concept of JavaScript

Unit Outcomes

I. To study the structure and principles of JavaScript


II. To understand & implement Control and looping structure of
JavaScript.
III. To understand & learn the Event handling concept of JavaScript

2 International Institute of Management MASTER OF COMPUTER


Science (IIMS) APPLICATION
What is JavaScript?
 What is JavaScript?
 JavaScript is a scripting language
 A scripting language is a lightweight programming language .
 JavaScript is a scripting language, not a tool in and of itself .
 JavaScript was designed to add interactivity to HTML pages.
 JavaScript is very easy to implement because it is integrated with
HTML.
 It is open and cross-platform.

3 International Institute of Management MASTER OF COMPUTER


Science (IIMS) APPLICATION
What is JavaScript?
 What are advantages of JavaScript?
 A scripting language is a lightweight programming language .
 JavaScript is client-side as well as server-side scripting Language.
 Everyone can use JavaScript without purchasing a license.
 JavaScript is an interpreted language.
 JavaScript is much more flexible.
 JavaScript is an Object-Based Language
 JavaScript is Event Driven
 Less server interaction
 Immediate feedback to the visitors :
 They don't have to wait for a page reload to see if they have
forgotten to enter something.
4 International Institute of Management MASTER OF COMPUTER
Science (IIMS) APPLICATION
What is JavaScript?
 What are Limitations of JavaScript?
 JavaScript is not a full-fledged programming language.
 It has following limitations such as ……
 Client-side JavaScript does not allow the reading or writing of
files. This has been kept for security reason.
 JavaScript cannot be used for networking applications because
there is no such support available.
 JavaScript doesn't have any multi-threading or multiprocessor
capabilities.

5 International Institute of Management MASTER OF COMPUTER


Science (IIMS) APPLICATION
What is JavaScript?
 JavaScript implementation in HTML File
 There is a flexibility given to include JavaScript code anywhere in
an HTML document.
 the most preferred ways to include JavaScript in an HTML file are as
follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head>
section.

6 International Institute of Management MASTER OF COMPUTER


Science (IIMS) APPLICATION
JavaScript Variables
 JavaScript variables have only two scopes.
 Global Variables:
 A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
 Local Variables :
 A local variable will be visible only within a function where it is
defined.
 Function parameters are always local to that function.

7 International Institute of Management MASTER OF COMPUTER


Science (IIMS) APPLICATION
JavaScript Variables
 Where does JavaScript code is written?
 It can be written implicitly or explicitly:
 Implicitly
Means that it can be written in one of two places in the web page:
 Head Section:
 In which will be loaded before the rest of the document and if it's
written in a function it will be loaded upon request.
 Body section: which will be loaded in it's turn on the page .
<html><head>
<script>
// code
</script>
</head>

8 International Institute of Management MASTER OF COMPUTER


Science (IIMS) APPLICATION
JavaScript Variables
 Where does JavaScript code is written?
 It can be written implicitly or explicitly:
Means that code will be written in separate file and linked to the
desired page.
External JavaScript Advantages
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
Syntax
<script language=“javascript” type=“text/javascript”>
// all variables and functions declaration ….
……..

</script>
9 International Institute of Management MASTER OF COMPUTER
Science (IIMS) APPLICATION
JavaScript Output
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Using innerHTML
 To access an HTML element, JavaScript can use the
document.getElementById(id) method.
 Using document.write():
<script>
document.write(5 + 6);
</script>
 Using window.alert()
<script>
window.alert(5 + 6);
</script>
1 International Institute of Management MASTER OF COMPUTER
0 Science (IIMS) APPLICATION
JavaScript Output
Using innerHTML
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 10 +20;
</script>

</body>
</html>

1 International Institute of Management MASTER OF COMPUTER


1 Science (IIMS) APPLICATION
JavaScript Output
Using document.write()
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

1 International Institute of Management MASTER OF COMPUTER


2 Science (IIMS) APPLICATION
JavaScript Output
Using window.alert()
You can use an alert box to display data:
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>

1 International Institute of Management MASTER OF COMPUTER


3 Science (IIMS) APPLICATION
JavaScript Variables
 <html>  <html>
<body onload = test();> <body onload = test();>
<script type = "text/javascript"> <script type = "text/javascript">
function test( ) <!-- var name = “Kapil";
{ // Declare a global variable
var name = “Sachin"; "; function test( )
// Declare a local variable {
document.write(name ); var myVar = “I am local";
} //--> // Declare a local variable
</script> document.write(myVar);
</body> document.write(name );
</html> } //-->
</script>
</body>
</html>

1 International Institute of Management MASTER OF COMPUTER


4 Science (IIMS) APPLICATION
JavaScript keyword
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super

1 International Institute of Management MASTER OF COMPUTER


5 Science (IIMS) APPLICATION
What is an Operator?
 JavaScript supports the following types of operators.
• An operator is a symbol which helps the user to command the
computer to do a certain mathematical or logical manipulations.
• Operators are used in C language program to operate on data and
variables.
• Operators are three types Unary, Binary, Ternary.
• C has a rich set of operators which can be classified as…..
 Arithmetic operators  Conditional Operators
 Relational Operators  Bitwise Operators
 Logical Operators  Special Operators
 Assignment Operators
 Increments and
Decrement Operators

1 International Institute of Management MASTER OF COMPUTER


6 Science (IIMS) APPLICATION
Arithmetic Operator?
++ (Increment)
+ (Addition)
Adds two operands Increases an integer value by one
Ex: A + B will give 30
Ex: A++ will give 11
* (Multiplication) 7
Multiply both operands
Ex: A * B will give 200 -- (Decrement)
/ (Division)
Divide the numerator by the Decreases an integer value by one
denominator
Ex: B / A will give 2 Ex: A-- will give 9
% (Modulus)
Outputs the remainder of an
integer division
Ex: B % A will give 0

1 International Institute of Management MASTER OF COMPUTER


7 Science (IIMS) APPLICATION
Comparison Operators?
 JavaScript supports the following comparison operators −
 = = (Equal):
 Checks if the value of two operands are equal or not, if yes, then the
condition becomes true.
 Ex: (A == B) is not true.
 != (Not Equal):
 Checks if the value of two operands are equal or not, if the values
are not equal, then the condition becomes true.
 Ex: (A != B) is true.
 > (Greater than):
 Checks if the value of the left operand is greater than the value of
the right operand, if yes, then the condition becomes true.
 Ex: (A > B) is not true.

1 International Institute of Management MASTER OF COMPUTER


8 Science (IIMS) APPLICATION
Comparison Operators?
 < (Less than):
 Checks if the value of the left operand is less than the value of the
right operand, if yes, then the condition becomes true.
 Ex: (A < B) is true.
 >= (Greater than or Equal to):
 Checks if the value of the left operand is greater than or equal to
the value of the right operand, if yes, then the condition becomes
true.
 Ex: (A >= B) is not true.

1 International Institute of Management MASTER OF COMPUTER


9 Science (IIMS) APPLICATION
Bitwise Operators?
 Bit operators work on 32 bits numbers.
 Any numeric operand in the operation is converted into a 32 bit
number. The result is converted back to a JavaScript number.
Deci
Operator Description Example Same as Result
mal
& AND 5&1 0101 & 0001 0001  1
| OR 5|1 0101 | 0001 0101  5
~ NOT ~5  ~0101 1010  10
^ XOR 5^1 0101 ^ 0001 0100  4

<< Zero fill left shift 5 << 1 0101 << 1 1010  10

>> Signed right shift 5 >> 1 0101 >> 1 0010  2

>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010  2

2 International Institute of Management MASTER OF COMPUTER


0 Science (IIMS) APPLICATION
Comparison Operators?
 JavaScript supports the following comparison operators −
 = = (Equal)
 Checks if the value of two operands are equal or not, if yes, then the
condition becomes true.
 Ex: (A == B) is not true.
 != (Not Equal)
 Checks if the value of two operands are equal or not, if the values are
not equal, then the condition becomes true.
 Ex: (A != B) is true.
 > (Greater than)
 Checks if the value of the left operand is greater than the value of the
right operand, if yes, then the condition becomes true.
 Ex: (A > B) is not true.

2 International Institute of Management MASTER OF COMPUTER


1 Science (IIMS) APPLICATION
Assignment Operators?
Operator Example Same As Operator Example Same As

= x=y x=y >>= x >>= y x = x >> y


+= x += y x=x+y >>>= x >>>= y x = x >>> y
-= x -= y x=x-y &= x &= y x=x&y
*= x *= y x=x*y ^= x ^= y x=x^y
/= x /= y x=x/y |= x |= y x=x|y
%= x %= y x=x%y **= x **= y x = x ** y
<<= x <<= y x = x << y >>= x >>= y x = x >> y

2 International Institute of Management MASTER OF COMPUTER


2 Science (IIMS) APPLICATION
Data Types in Javascript
 JavaScript variables can hold many data types:
 Primitive Datatypes
 numbers, strings, objects
 Non-Primitive Datatypes
 Array

2 International Institute of Management MASTER OF COMPUTER


3 Science (IIMS) APPLICATION
Statements in Javascript
 In Javascript Programs the instructions are executed in the same order in
which they appear within the program.
 This type of execution is known as Sequential execution.
 Programs can be much powerful if we can control the order in which
statements are runs.
 Select a set of statement from the several options.
 Skip certain statements depending on some conditions in the programs and
continue execution of program from some other point.
 Repeat a section of program for a known number of times or until a specified
condition is satisfied.
 There are some control statements such as……..

if-else statement switch statement loops


for statement while statement do-while statement break statement
continue statement

2 International Institute of Management MASTER OF COMPUTER


4 Science (IIMS) APPLICATION
Decision Control in Javascript
If statement :
This is the most simple form of the Conditional statements.
To control the flow of execution of the program using certain statements are called
"Conrol Instructions ".
It takes an expression in parenthesis and an statement or block of statements.
if the expression is true then the statement or block of statements gets executed
otherwise these statements are skipped.

if (expression) if (expression) if (expression)


statement; { {
Block of statements; Block of statements;
} }
else
{
Block of statements;
}

2 International Institute of Management MASTER OF COMPUTER


5 Science (IIMS) APPLICATION
Decision Control in Javascript
If statement :
Relational operators Logical Operators(Expression)
This Is true if &&(And) Both the conditions
expression must true
Eg.
x==y x is equal to y if(per>=50 &&
x !=y x is not equal to y per<60) // both
x<y x is less than y
x>y x is greater than y ||(or) Either one condition
is true
x<=y x is less than or equal Eg.
to y if(per>=50 ||
per<60) //any one
x>=y x is greater than or
equal to y

2 International Institute of Management MASTER OF COMPUTER


6 Science (IIMS) APPLICATION
Decision Control in Javascript
If else statement :
If statement can be followed by an optional else statement, which executes when the
condition expression is false.

Syntax Eg.
If(condition) If (mark>40)
{ {
statement/statements; alert (“student is pass”);
} }
else else
{ {
statement/statements; alert (“student is fail”);
} }

2 International Institute of Management MASTER OF COMPUTER


7 Science (IIMS) APPLICATION
Decision Control in Javascript
Nested if statement :
It can be used to check multiple conditions in program.
If or else if statement within another if or else if statement.
Syntax Eg. if(a<=b)
if(condition) if (a==100) {
{ {
if(condition) document.write(“A=100”); if(a<b)
{ } document.write (“a <b”);
else else
statement/statements; { document.write (“a <b”);
} if (b==200) }
else {
{ document.write else
(“B=200”); {
statement/statements; } document.write (“a >b”);
} } }
else
{ }

statement/statements;
}

2 International Institute of Management MASTER OF COMPUTER


8 Science (IIMS) APPLICATION
Decision Control in Javascript
If-else-Ladder statement :
Sometimes we wish to make a multi-way decision based on several conditions.
It can be used to check multiple conditions in program.
If or else if statement within another if or else if statement.

Syntax if(result>=75)
If(expression/condition) {
statement/statements; printf(“Passed :Grade A++\n”);
else If(expression/condition) Else if(result>=60)
statement/statements; printf(“Passed :Grade B\n”);
else If(expression/condition) Else if(result>=55)
statement/statements; printf(“Passed :Grade C\n”);
else Else
statement/statements; printf(“Failed\n”);

2 International Institute of Management MASTER OF COMPUTER


9 Science (IIMS) APPLICATION
Decision Control in Javascript
Switch statement :
A switch is an alternative way to write a conditional statement in C
programming.
A switch statement allows a variable to test for equality against a list of values.
It is a safe alternative to nested if statement and comfortable as compared to
nested if statements.
•A switch statement is used to develop menu driven programs.
Syntax Eg.
switch(expression) switch(grade)
{ {
case value: statement; case ‘A’alert(“Excellent !”);
break; /* optional */ break; /* optional */
case value: statement; case ‘C’: alert(“Well Done !”);
break; /* optional */ break; /* optional */
case value: statement; case ‘F’: alert(“Better Try again !”);
break; /* optional */ break; /* optional */
Default : /* optional */ Default : /* optional */
statement; alert(“Invalid grade\n !”);
} }

3 International Institute of Management MASTER OF COMPUTER


0 Science (IIMS) APPLICATION
Rules for Switch statements
 Rules for Switch statement :
 The switch expression must be an integer type.
 Case labels must be constants or constant expressions.
 Case labels must be unique.
 No two labels can have the same value.
 Case labels must end with semicolon.
 The break statement transfers the control out of the switch
statement.
 The break statement is optional.
 The default statement is optional. If present, it will be executed
when the expression does not find a matching case label.
 There can be at most one default label.

3 International Institute of Management MASTER OF COMPUTER


1 Science (IIMS) APPLICATION
Break/Continue Statement
Break statement :
 In C programming, Break statement is used to duplicate can be used to
terminate current execution.
 The break statement has two uses.
 It is use to terminate a Case in the switch statement.
 The break statement to force immediate termination of loop.
 A break is usually associated with an if statements.
Syntax Eg.
switch(expression) switch(grade)
{ {
case value: statement; case ‘A’:
break; /* optional */ document.write (“Excellent !”);
Default : /* optional */ break; /* optional */
statement; case ‘F’:
} document.write (“Better Try again !”);
break; /* optional */
Default : /* optional */
document.write (“Invalid grade\
n !”);
}

3 International Institute of Management MASTER OF COMPUTER


2 Science (IIMS) APPLICATION
Looping Statement
In JavaScript language, loop statements allow the set of instructions to be
executed repeatedly until certain condition is reached
A loop section of the program consists of two parts : Body of the loop and
Control Statement.
The control statement performs a logical test whose result is either true or false.
If a logical test value is true, the statements in the body of the loop are executed
otherwise the loop is terminated.
Depending on the position of the control statement in the loops are two types….
Pre-tested loop : The control statement performs a logical test before
execution of the loop body.
If the test is true, the loop is executed otherwise it is terminated.
Post-tested loop : The control statement performs a logical test after
execution of the loop body
If the test is true, the loop is executed otherwise it is terminated.

3 International Institute of Management MASTER OF COMPUTER


3 Science (IIMS) APPLICATION
Looping Statement
Post-tested Loop
Pre-tested Loop
Body of loop
Test
Exit
Condition
false
True
True Test
Condition Exit
Body of loop
There are three loop control elements….
Initialization Expression: It set initial value for the loop counter before the
statements within the loop body start to execute.
Test Expression : It tests the condition to determine whether to execute the loop or
not.
Update Expression: It increments or decrements the loop encounter value
such that after appropriate iterations.
3 International Institute of Management MASTER OF COMPUTER
4 Science (IIMS) APPLICATION
Looping Statement
In JavaScript language, loop statements allow the set of instructions to be
executed repeatedly until certain condition is reached
A loop section of the program consists of two parts : Body of the loop and
Control Statement.
The control statement performs a logical test whose result is either true or false.
If a logical test value is true, the statements in the body of the loop are executed
otherwise the loop is terminated.
Depending on the position of the control statement in the loops are two types….
Pre-tested loop : The control statement performs a logical test before
execution of the loop body.
If the test is true, the loop is executed otherwise it is terminated.
Post-tested loop : The control statement performs a logical test after
execution of the loop body
If the test is true, the loop is executed otherwise it is terminated.

3 International Institute of Management MASTER OF COMPUTER


5 Science (IIMS) APPLICATION
Looping Statement
In Javascript gives a choice of three types of Loops : While, do while and for.
The for loop is frequently used, where the loop is to be executed a fixed number
of times.
The while loop keeps repeating an action until an associated test returns false.
This is useful where the programmer does not know in advance how many times
the loop to be executed.
The do while loop is similar to while loop, but the test loop body is run at least
once.

3 International Institute of Management MASTER OF COMPUTER


6 Science (IIMS) APPLICATION
Looping Statement
The for loop is a most commonly used loop statement.
It is pre-test loop and it is used when the number of iterations of the loop is
known before the loop is entered.
The for loop consists of three parts(initialization expression, test expression
and update expression)separated by semicolons.
The initialization expression is run before the loop is entered. Generally it is
initialize the loop variable.
The second is test, the loop is excited when this returns false.
The third is an increment or decrement of the loop counter.
This statement is run every time the loop body is completed.

3 International Institute of Management MASTER OF COMPUTER


7 Science (IIMS) APPLICATION
Looping Statement
for(expression1;expersion2;expression3) Eg:
{ for(i=0; i<10; i++)
Body of loop; {
} document.write(“Hello
World”);
document.write(i);
}

3 International Institute of Management MASTER OF COMPUTER


8 Science (IIMS) APPLICATION
Nested for loops Statement
The one for statement within another for statement is called Nested for loops.

for(expression1;expersion2;expression3) Eg:
{ For(i=1; i<=10; i++)
statement; {
for(expression1;expersion2;expression3) For(j=1; j<=i; j++)
{
statement; {
} document.write(“Hello World”);
} document.write(“%d”, i);
}
}

3 International Institute of Management MASTER OF COMPUTER


9 Science (IIMS) APPLICATION
Nested while loops Statement
While loops are repetitive operations.
In while loop, first the condition is checked.
If the condition is true , then the statements are executed. After
that again the condition is checked and this keeps on repeating , until
the condition is false.
If the condition is false, then the statements inside the loop are
not executed, instead the control directly comes out of the loop.
Syntax of while loop;
while (condition) While loop demo
{
statement;
statement;
}

4 International Institute of Management MASTER OF COMPUTER


0 Science (IIMS) APPLICATION
do-while loops Statement
do-while loops are repetitive operations.
In case of do-while loop, first the statements are executed and then
the condition is checked.
If the condition is true , then the statements are executed. After that
again the condition is checked and this keeps on repeating , until the
condition is false.
If the condition is false, then the statements inside the loop are not
executed.
In case of do-while loop, the statements are executed atleast once even
if the condition is not true for the first statement.
Syntax of while loop;
do do-while loop demo
{ statement;
statement;
} while (condition);
International Institute of Management MASTER OF COMPUTER
4
1 Science (IIMS) APPLICATION
While v/s do-while Statement
While loop Do-while loop
This is called as a entry This is called exit controlled loop.
controlled loop. The entry inside this loop is sure.
The entry inside the loop is But the exit is possible only if the
possible only if the condition is condition is false.
true
If the condition is true , then the Even if the condition is not true
statements are executed. for the first time, then the statements
are executed atleast once.
There is no semicolon(;) after There is a semicolon(;) after the
the condition in the syntax of condition in the syntax of do-while
while loop. loop.

4 International Institute of Management MASTER OF COMPUTER


2 Science (IIMS) APPLICATION
Introduction to Functions
Function is a sequence of program instructions that perform a
specific task, packaged as a unit.
This unit can then be used in programs wherever that particular task
should be performed.

Why use Function?


 Don’t write the entire logic in one function .
 Writing functions avoids rewriting the same code over and over.
 It becomes easier to write programs and keep track of what they
are doing.
function functionName([arg1, arg2, ...argN])
{  
 //code to be executed  
}  
4 International Institute of Management MASTER OF COMPUTER
3 Science (IIMS) APPLICATION
Introduction to Functions
 JavaScript Functions
 JavaScript functions are used to perform operations.
 We can call JavaScript function many times to reuse the code.
 Advantage of JavaScript function
 There are mainly two advantages of JavaScript functions.
 Functions reduces the repetition of code within a program
 Functions makes the code much easier to maintain Code
reusability: We can call a function several times so it save
coding.
 Functions makes it easier to eliminate the errors
 Less coding: It makes our program compact.
 We don’t need to write many lines of code each time to perform
a common task.
 JavaScript Function Syntax
4 International Institute of Management MASTER OF COMPUTER
4 Science (IIMS) APPLICATION
Introduction to Functions
<body> Function with Return Value
<script> We can call function that returns a
function fun() value and use it in our program.
{ <script>  
alert("hello! this is message"); function SIOM()
} {  
</script> return “Sinhgad Institute of
<input type="button" Management";  
onclick=“fun()" value="call }  
function"/> </script>  
</body> <script>  
document.write(SIOM());  
</script>  

4 International Institute of Management MASTER OF COMPUTER


5 Science (IIMS) APPLICATION
Array in JavaScript
What is an Array?
 An array is a special variable, which can hold more than one
value at a time.
 JavaScript arrays are used to store multiple values in a single
variable.
 JavaScript array is an object that represents a collection of
similar type of elements.
 There are 3 ways to construct array in JavaScript
 By array literal
 By creating instance of Array directly (using new keyword)
 By using an Array constructor (using new keyword)

4 International Institute of Management MASTER OF COMPUTER


6 Science (IIMS) APPLICATION
Array in JavaScript
 How to create an Array?
1) JavaScript array literal
 Creating an Array
 Using an array literal is the easiest way to create a JavaScript
Array.
 var array_name = [item1, item2, ...];  
 var gods=[“Ram",“Krishna",“Sai"]; 
2) JavaScript Array directly (new keyword)
 The syntax of creating array directly is given below:
 var arrayname=new Array();  
3) JavaScript array constructor (new keyword)
 To create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly.
 var emp=new Array("Jai","Vijay","Sachin");  
4 International Institute of Management MASTER OF COMPUTER
7 Science (IIMS) APPLICATION
Array in JavaScript
<html> <script>  
<body> var i;  
<script> var emp = new Array();  
var emp=["Sachin","Virat","Kapil"];
emp[0] = “Kapil";  
emp[1] = “Sachin";  
for (i=0;i<emp.length;i++) emp[2] = “Virat";  
{   for (i=0;i<emp.length;i++)
document.write(emp[i] + "<br/>"); {  
} document.write(emp[i] + "<br>"); 
</script>  
</body> }  
</html> </script>  

4 International Institute of Management MASTER OF COMPUTER


8 Science (IIMS) APPLICATION
JavaScript string
 JavaScript String
 The JavaScript string is an object that represents a sequence of
characters.
 There are 2 ways to create string in JavaScript
 By string literal
 By string object (using new keyword)
 By string literal
 The string literal is created using double quotes. The syntax of
creating string using string literal is given below:
var string_nm="string content";  
var str="Sinhgad Institute Of Management";
 By string object (using new keyword)
 The syntax of creating string object using new keyword.
var stringname=new String("string literal");  
4 International Institute of Management MASTER OF COMPUTER
9 Science (IIMS) APPLICATION
Event handling in javascript
 Events are actions or occurrences that happen in the system you
are programming.
 Event provide a mechanism by which some kind of action can be
automatically taken (e.g. some code running) when the event
occurs.
 when events happen, you may want to do something.
 JavaScript lets you execute code when events are detected.
 Each available event has an event handler, which is a block of
code ( user-defined JavaScript function) that will be run when
the event fires.
 HTML allows event handler attributes, with JavaScript code, to
be added to HTML elements.

5 International Institute of Management MASTER OF COMPUTER


0 Science (IIMS) APPLICATION
Event handling in JavaScript
 The document and window objects, and adding Event Listeners
to them.
 How to add the listener on the window object
 The addEventListener method is the most preferred way to add
an event listener to window, document or any other element in
the DOM.
 An event object is passed as an argument (optional) to the
handler which contains all the information related to the event
(mousedown) on the window.

5 International Institute of Management MASTER OF COMPUTER


1 Science (IIMS) APPLICATION
Event handling in javascript
 when events happen, you may want to do something.
 JavaScript lets you execute code when events are detected.
 HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.

 <element event="some JavaScript">


 Syntax is:
<button onclick="document.getElementById('demo').innerHTML =
Date()">Todays Date:</button>
<button onclick="this.innerHTML = Date()"> Todays Date:
</ </button>

5 International Institute of Management MASTER OF COMPUTER


2 Science (IIMS) APPLICATION
Event handling in javascript
<html> <html>
<body> <body>
<button <button
onclick="document.getElementBy onclick="this.innerHTML=Date()
Id('demo').innerHTML=Date()"> ">Date:</button>
Date:</button>
<p id="demo"></p>
<p id="demo"></p>
</body>
</body> </html>
</html>

5 International Institute of Management MASTER OF COMPUTER


3 Science (IIMS) APPLICATION
JavaScript string methods
Methods Description
charAt() It provides the char value present at the specified index.
It provides the Unicode value of a character present at the
charCodeAt()
specified index.
concat() It provides a combination of two or more strings.
It is used to fetch the part of the given string on the basis of the
substr()
specified starting position and length.
It is used to fetch the part of the given string on the basis of the
substring()
specified index.
toLowerCase() It converts the given string into lowercase letter.
toUpperCase() It converts the given string into uppercase letter.

5 International Institute of Management MASTER OF COMPUTER


4 Science (IIMS) APPLICATION
Event handling in javascript
 What is an Event ?
 JavaScript's interaction with HTML is handled through events
that occur when the user or the browser manipulates a page.
 Events are a part of the Document Object Model (DOM)
 HTML element contains a set of events which can trigger
JavaScript Code.
 When the page loads, it is called an event.
 When the user clicks a button, that click is an event.
 pressing any key
 Closing a window
 Resizing a window

5 International Institute of Management MASTER OF COMPUTER


5 Science (IIMS) APPLICATION
Event handling in javascript
<form> Level Events

Attribute Value Description


onchange script Script runs when the element changes
onsubmit script Script runs when the form is submitted
onreset script Script runs when the form is reset
onselect script Script runs when the element is selected
onblur script Script runs when the element loses focus
onfocus script Script runs when the element gets focus

5 International Institute of Management MASTER OF COMPUTER


6 Science (IIMS) APPLICATION
Event handling in javascript
Keyboard Events

Attribute Value Description


onkeydown script Script runs when key is pressed
onkeypress script Script runs when key is pressed and released
onkeyup script Script runs when key is released

5 International Institute of Management MASTER OF COMPUTER


7 Science (IIMS) APPLICATION
Event handling in javascript
other Events

Attribute Value Description


onclick script Script runs when a mouse click

ondblclick script Script runs when a mouse double-click

onmousedown script Script runs when mouse button is pressed

onmousemove script Script runs when mouse pointer moves

onmouseout script Script runs when mouse pointer moves out of an element

onmouseover script Script runs when mouse pointer moves over an element

onmouseup script Script runs when mouse button is released

5 International Institute of Management MASTER OF COMPUTER


8 Science (IIMS) APPLICATION
Event handling in javascript
Events Description
onclick occurs when element is clicked.
ondblclick occurs when element is double-clicked.
onfocus occurs when an element gets focus such as button, input, textarea etc.
onblur occurs when form looses the focus from an element.
onsubmit occurs when form is submitted.
onmouseover occurs when mouse is moved over an element.
onmouseout occurs when mouse is moved out from an element (after moved over).
onmousedown occurs when mouse button is pressed over an element.
onmouseup occurs when mouse is released from an element (after mouse is pressed).
onload occurs when document, object or frameset is loaded.
onunload occurs when body or frameset is unloaded.
onscroll occurs when document is scrolled.
onresized occurs when document is resized.
onreset occurs when form is reset.
onkeydown occurs when key is being pressed.
onkeypress occurs when user presses the key.
onkeyup occurs when key is released.
5 International Institute of Management MASTER OF COMPUTER
9 Science (IIMS) APPLICATION
Form Validation
 JavaScript provides facility to validate the form on the client-side
so data processing will be faster than server-side validation.
 Most of the web developers prefer JavaScript form validation.
  validation is must to authenticate user.
 JavaScript, we can validate name, password, email, date, mobile
numbers and more fields.
 Form validation normally used to occur at the server, after the client
had entered all the necessary data and then pressed the Submit
button.
 If the data entered by a client was incorrect or was simply missing,
the server would have to send all the data back to the client and
request that the form be resubmitted with correct information.

6 International Institute of Management MASTER OF COMPUTER


0 Science (IIMS) APPLICATION
Form Validation
 JavaScript provides a way to validate form's data on the client's
computer before sending it to the web server.
 Basic Validation :
 The form must be checked to make sure all the mandatory fields are
filled in.
 It would require just a loop through each field in the form and check
for data.
 Data Format Validation :
 The data that is entered must be checked for correct form and value.
 Your code must include appropriate logic to test correctness of
data.

6 International Institute of Management MASTER OF COMPUTER


1 Science (IIMS) APPLICATION

You might also like