Download - Java Script Notes Sem-II-1
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 1/55
Lesson Plan No. 1: Algorithm and fow charts
Algorithms:- To make a computer do anything, you have to write a computerprogram. To write a computer program, you have to tell the computer, step bystep, exactly what you want it to do. The computer then "executes" theprogram, following each step mechanically, to accomplish the end goal.
When you are telling the computer what to do, you also get to choose how it'sgoing to do it. That's where computer algorithms come in. The algorithm isthe basic technique used to get the ob done. !et's follow an example to helpget an understanding of the algorithm concept.
!et's say that you have a friend arriving at the airport, and your friend needs toget from the airport to your house. ere are four di#erent algorithms that youmight give your friend for getting to your home$
The taxi algorithm$
%. &o to the taxi stand.. &et in a taxi.(. &ive the driver my address.
The call-me algorithm$
%. When your plane arrives, call my cell phone.. )eet me outside baggage claim.
The rent-a-car algorithm$
%. Take the shuttle to the rental car place.. *ent a car.(. +ollow the directions to get to my house.
The bus algorithm$
%. utside baggage claim, catch bus number -.. Transfer to bus %/ on )ain 0treet.(. &et o# on 1lm street./. Walk two blocks north to my house.
2ll four of these algorithms accomplish exactly the same goal, but eachalgorithm does it in completely di#erent way. 1ach algorithm also has a di#erentcost and a di#erent travel time. Taking a taxi, for example, is probably thefastest way, but also the most expensive. Taking the bus is de3nitely lessexpensive, but a whole lot slower. 4ou choose the algorithm based on thecircumstances.
Summar :- The sequence of steps to be performed in order to solve aproblem by the computer is known as an algorithm
!lowchart $5 2 6owchart is a type of diagram that represents an algorithm,work6ow or process, showing the steps as boxes of various kinds, and theirorder by connecting them with arrows. This diagrammatic representationillustrates a solution model to a given problem.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 2/55
+or 1xample $5
Summar :- +lowchart is a graphical or symbolic representation of analgorithm. 7t is the diagrammatic representation of the step5by5step solution toa given problem
Lesson Plan No. ": #ntroduction to $eb ser%er andtheir &eatures
#ntroduction to $eb ser%er :- Web servers are computers that deliver8serves up9 Web pages. 1very Web server has an 7: address and possibly adomain name. +or example, if you enter the ;*!http$<<www.pcwebopedia.com<index.html in your browser, this sends a requestto the Web server whose domain name is pcwebopedia.com.
The server then fetches the page named index.html and sends it to yourbrowser. 2ny computer can be turned into a Web server by installing serversoftware and connecting the machine to the 7nternet. There are many Webserver software applications, including public domain software from =>02 and2pache, and commercial packages from )icrosoft, =etscape and others.
'ost web ser%ers ha%e &eatures that allow ou to do the&ollowing:
• >reate one or more websites.• >on3gure log 3le settings, including where the log 3les are saved, what
data to include on the log 3les etc.• >on3gure website<directory security. +or example, which user accounts
are<aren't allowed to view the website, which 7: addresses are<aren'tallowed to view the website etc.
• >reate an +T: site. 2n +T: site allows users to transfer 3les to and fromthe site.
• >reate virtual directories, and map them to physical directories
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 3/55
• >on3gure<nominate custom error pages. This allows you to build anddisplay user friendly error messages on your website. +or example, youcan specify which page is displayed when a user tries to access a pagethat doesn't exist 8i.e. a "// error"9.
• 0pecify default documents.
Lesson Plan No. (: #ntroduction to Programming )Scripting Languages
#ntroduction to Programming :- 2 program is a set of instructions thattell the computer to do various things? sometimes the instruction it has toperform depends on what happened when it performed a previous instruction. This section gives an overview of the two main ways in which you can givethese instructions, or @commandsA as they are usually called. ne way uses aninterpreter , the other a compiler . 2s human languages are too diBcult for acomputer to understand in an unambiguous way, commands are usually writtenin one or other languages specially designed for the purpose.
#ntroduction to Scripting language :- 2 scripting language or scriptlanguage is a programming language that supports scripts, programs written fora special run5time environment that can interpret 8rather than compile9 andautomate the execution of tasks that could alternatively be executed one5by5one by a human operator.
*a%a script
Cava script is a client slide scripting language which is used to change T)!
static page into dynamic pages or it brings interactivity in T)! web pages. 2 client side scripting language means , it has support in the browser D
doesnEt require a web server to be executed Cava script is supported by all maor browsers and it is written inside T)!
document.
The +istor o& *a%a script
Cava script was initially introduced by =etscape a web browser in %FFG
.The 3rst author of this language was Hrendan 1ich. Cava scriptEs 3rst version was released in %FF( and the latest version is
(. Cava script has support for communicating with web server and that was
included in Cava script in 7n I Cava script released its most popular library called @JueryA which
is now used by millions of websites on the web.
,ierence between lient side ) ser%er side Scripting
Language
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 4/55
Ser%er side scripting language /P+P0ASP re2uires a separate
online ser%er &or execution . $hile lient side scripting language /*a%a script0 ,+T'L doesn3t
re2uire a web ser%er. The source code o& a client side /*a%a script is alwas %isible to
the users. $hile Ser%er side scripting source code is not a%ailable to the
users .
Lesson Plan No.4: #ntroduction to *a%aScript ) itsapplication &or web.
JavaScriptJavaScript is an object-based scripting language that is lightweight and cross-
platform.
JavaScript is not compiled but translated. The JavaScript Translator (embedded
in browser) is responsible to translate the JavaScript code.
Where JavaScript is used
JavaScript is used to create interactive websites. It is mainly used for:
) !lient-side validation") #ynamic drop-down menus$) #isplaying data and time%) #isplaying popup windows and dialog bo&es (li'e alert dialog bo& confirm
dialog bo& and prompt dialog bo&)) #isplaying cloc's etc.
JavaScript Example
Program 1:
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script> document.write("Hello JavaScript"); </script>
</body>
</html>
Out Put:-
Welcome to JavaScript
Hello JavaScript
JavaScript Example. JavaScript Example
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 5/55
". Within body tag
$. Within head tag
Javascript e&le is easy to code. JavaScript provides $ places to put the
JavaScript code: within body tag within head tag and e&ternal JavaScript file.
*et+s create the first JavaScript e&le.
<script type,te&t/avascript> document.write(JavaScript is a simple language for learners)0</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the
browser about the data.
The document.write() function is used to display dynamic content through
JavaScript. 1e will learn about document ob/ect in detail later.
Places to put JavaScript code. 2etween the body tag of html". 2etween the head tag of htmlli3$. In ./s file (e&ternal /avaScript)
1) JavaScript Example : code between the body tag
In the above e&le we have displayed the dynamic content using JavaScript.
*et+s see the simple e&le of JavaScript that displays alert dialog bo&.
Program 2:
<html>
<body>
<script>
document.write("Hello JavaScript");
</script>
</body>
</html>
Out Put:-
Hello JavaScript
2) JavaScript Example : code between the head tag
*et+s see the same e&le of displaying alert dialog bo& of JavaScript that is
contained inside the head tag.
In this e&le we are creating a function msg(). To create function in
JavaScript you need to write function with function4name as given below.
To call function you need to wor' on event. 5ere we are using onclic' event to
call msg() function.
Program 3:
<html><head>
<script type="text/javascript">
function msg(){
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 6/55
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form><input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Output:
Welcome to Javascript
3) External JavaScript file
1e can create e&ternal JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in
several html pages.
6n e&ternal JavaScript file must be saved by ./s e&tension. It is recommended
to embed all JavaScript files into a single file. It increases the speed of the
webpage.
*et+s create an e&ternal JavaScript file that prints 5ello Javatpoint in a alert
dialog bo&.message.jsfunction msg()7alert(5ello Javatpoint)0
8
Program 4:
<html> <head>
<script type,te&t/avascript src,message./s></script> </head> <body> <p>1elcome to JavaScript</p> <form> <input type,button value,clic' onclic',msg()/> </form> </body> </html>
JavaScript Comment. JavaScript comments
". Advantage of javaScript comments
$. Single-line and Multi-line comments
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 7/55
The Javacript comments are meaningful way to deliver message. It is used
to add information about the code warnings or suggestions so that end user
can easily interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in
the browser.
Advantages of JavaScript comments
There are mainly two advantages of JavaScript comments.1 !o ma"e code easy to understand It can be used to elaborate the code
so that end user can easily understand the code.! !o avoid the unnecessary code It can also be used to avoid the code
being e&ecuted. Sometimes we add the code to perform some action. 2utafter sometime there may be need to disable the code. In such case it isbetter to use comments.
Types of JavaScript Comments
There are two types of comments in JavaScript.. Single-line !omment". 9ulti-line !omment
JavaScript Single line Comment
It is represented by double forward slashes (). It can be used before and after
the statement.
*et+s see the e&le of single-line comment i.e. added before the statement.<script>
It is single line commentdocument.write(hello /avascript)0</script>
*et+s see the e&le of single-line comment i.e. added after the statement.<script> var a,0var b,"0var c,a;b0It adds values of a and b variabledocument.write(c)0prints sum of and "
</script>
JavaScript Multi line Comment
It can be used to add single as well as multi line comments. So it is more
convenient.
It is represented by forward slash with asteris' then asteris' with forward slash.
<or e&le: = your code here =
It can be used before after and middle of the statement.
<script> = It is multi line comment.It will not be displayed =document.write(e&le of /avascript multiline comment)0
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 8/55
</script>
Lesson Plan No. 5: *a%aScript 6asics 7 8ariables0onstants ) ,ata tpes
JavaScript Variable. JavaScript variable
". JavaScript "ocal variable
$. JavaScript #lobal variable
6 Javacript variable is simply a name of storage location. There are two
types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also 'nown as
identifiers).. >ame must start with a letter (a to ? or 6 to @) underscore( 4 ) or
dollar( A ) sign.". 6fter first letter we can use digits ( to B) for e&le value.$. JavaScript variables are case sensitive for e&le & and C are different
variables.
Correct JavaScript variablesvar & , 0var 4value,sonoo0
Incorrect JavaScript variables
var "$,$0var =aa,$"0
*et+s see a simple e&le of JavaScript variable.
Program 5:
KhtmlL
KbodyLKscriptLvar x M %?var y M ?
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 9/55
var NMxOy?document.write8N9?K<scriptLK<bodyLK<htmlL
Output of the above example:#$
JavaScript local variable6 JavaScript local variable is declared inside bloc' or function. It is accessible
within the function or bloc' only. <or e&le:<script> function abc()7var &,0local variable8</script>
Dr<script> If(<%#)7var y,"0JavaScript local variable8</script>
JavaScript global variable
6 Javacript global variable is accessible from any function. 6 variable i.e.
declared outside the function or declared with window ob/ect is 'nown as global
variable. <or e&le:
Program 6:
<html>
<body>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
</body>
</html>
OutPut:
!$$ !$$
JavaScript Global Variable
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 10/55
6 Javacript global variable is declared outside the function or declared with
window ob/ect. It can be accessed from any function.
*et+s see the simple e&le of global variable in JavaScript.
Program 7:
<html>
<body>
<script>var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
a();
</script>
</body>
</html>
OutPut: 50
Declaring JavaScript global variable within function
To declare JavaScript global variables inside function you need to use window
object. <or e&le:
window.value,B0>ow it can be declared inside any function and can be accessed from any
function. <or e&le:function m()7window.value,0declaring global variable by window ob/ect8function n()7alert(window.value)0accessing global variable from other function8
Program 8:
<html>
<body>
<script>
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}m();
n();
</script>
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 11/55
</body>
</html>
O/P: 100
Internals of global variable in JavaScript
1hen you declare a variable outside the function it is added in the window
ob/ect internally. Eou can access it through window ob/ect also. <or e&le:var value,0function a()7alert(window.value)0accessing global variable8
Javascript Data Types
JavaScript provides different data types to hold different types of values. There
are two types of data types in JavaScript.. Frimitive data type". >on-primitive (reference) data type
JavaScript is a dynamic type language means you donGt need to specify type
of the variable because it is dynamically used by JavaScript engine. Eou need to
use var here to specify the data type. It can hold any type of values such as
numbers strings etc. <or e&le:var a,%0holding number
var b,Hahul0holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description
String represents seuence of characters e.g. hello
>umber represents numeric values e.g.
2oolean represents boolean value either false or true
ndefined represents undefined value
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 12/55
>ull represents null i.e. no value at all
JavaScript non-primitive data types
The non-primitive data types are as follows:
Data Type Description
Db/ect represents instance through which we can access members
6rray represents group of similar values
HegK&p represents regular e&pression
Lesson Plan No. 9: JavaScript Operators
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. <or e&le:var sum,;"0
5ere ; is the arithmetic operator and , is the assignment operator.
There are following types of operators in JavaScript.
. 6rithmetic Dperators". !omparison (Helational) Dperators$. 2itwise Dperators%. *ogical Dperators. 6ssignment DperatorsL. Special Dperators
JavaScript Arithmetic Operators
6rithmetic operators are used to perform arithmetic operations on the
operands. The following operators are 'nown as JavaScript arithmetic
operators.Operator Description Example
; 6ddition ;" , $
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 13/55
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 14/55
JavaScript Logical Operators
The following operators are 'nown as JavaScript logical operators.
Operator Description Example
QQ *ogical 6># (,," QQ ",,$$) , false
RR *ogical DH (,," RR ",,$$) , false
N *ogical >ot N(,,") , true
JavaScript Assignment Operators
The following operators are 'nown as JavaScript assignment operators.
Operator Description Example
, 6ssign ; , "
;, 6dd and assign var a,0 a;,"0 >ow a , $
-, Subtract and assign var a,"0 a;,0 >ow a ,
=, 9ultiply and assign var a,0 a=,"0 >ow a , "
, #ivide and assign var a,0 a,"0 >ow a ,
M, 9odulus and assign var a,0 aM,"0 >ow a ,
JavaScript Special Operators
The following operators are 'nown as JavaScript special operators.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 15/55
Operator Precedence:
Precedence Operators
1 Parentheses , array subscripts or function call
2 !, ~, -, ++, --
3 *, /, %
4 +,-
5 <<, >>, >>>
6 <, <=, >, >=
7 ==, !=
8 &
9 ^
10 |
11 &&
12 ||
13 ?:
14 =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ̂=, |=
The operator determines which operations are evaluated before others during the parsing and
execution of complex expressions
The precedence of the operator which operations are evaluated before others during the parsing
and execution of complex expressions.
Operator Description
(U:) !onditional Dperator returns value based on the condition. It is li'e
if-else.
!omma Dperator allows multiple e&pressions to be evaluated as
single statement.
delete #elete Dperator deletes a property from the ob/ect.
in In Dperator chec's if ob/ect has the given property
instanceof chec's if the ob/ect is an instance of given type
new creates an instance (ob/ect)
typeof chec's the type of ob/ect.
void it discards the e&pressionGs return value.
yield chec's what is returned in a generator by the generatorGs iterator.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 16/55
Lesson Plan No. : Program ontrol Statements andloops.
Program ontrol Statement
JavaScript If-else
The Javacript if&else statement is used to execute the code whethercondition is true or false. There are three forms of if statement in JavaScript.
. If Statement". If else statement$. if else if statement
JavaScript If statement
It evaluates the content only if e&pression is true. The signature of JavaScript if
statement is given below.if(e&pression)7
content to be evaluated8
Flowchart of JavaScript If statement
*et+s see the simple e&le of if statement in /avascript.<script> var a,"0if(a>)7document.write(value of a is greater than )08</script>
Output of the above example
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 17/55
value of a is greater than
Program:
<html>
<body>
<script>
var a=20;
if(a>10){document.write("value of a is greater than 10");
}
</script>
</body>
</html>
O/P:value of a is greater than 1$
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The synta& of
JavaScript if-else statement is given below.if(e&pression)7
content to be evaluated if condition is true8else7
content to be evaluated if condition is false8
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 18/55
Flowchart of JavaScript If...else statement
*et+s see the e&le of if-else statement in JavaScript to find out the even or
odd number.<script> var a,"0if(aM",,)7document.write(a is even number)08else7
document.write(a is odd number)08</script>
Output of the above example
a is even number
Program:
<html>
<body><script>
var a=20;
if(a%2==0){
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 19/55
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 20/55
Program:
<html>
<body>
<script>
var a=20;
if(a==10){document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
Output of the above example
a is eual to "
JavaScript Switch
The Javacript switch statement is used to execute one code from multiple
expressions. It is /ust li'e else if statement that we have learned in previous
page. 2ut it is convenient than if..else..if because it can be used with numbers
characters etc.
The signature of JavaScript switch statement is given below.
switch(e&pression)7
case value:code to be e&ecuted0brea'0
case value":code to be e&ecuted0brea'0
......
default:code to be e&ecuted if above values are not matched0
8
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 21/55
Program:
<!DOCTYPE html>
<html>
<body>
<script>var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
Output of the above example
2 Orade
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
</body>
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 22/55
Output of the above example
2 Orade 2 Orade ! Orade >o Orade
JavaScript Loops
The Javacript loops are used to iterate the piece of code using for while do
while or for-in loops. It ma'es the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
. for loop". while loop$. do-while loop%. for-in loop
1) JavaScript For loop
The Javacript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is 'nown. The synta& of for loop is given
below.
for (initiali?ation0 condition0 increment)7
code to be e&ecuted8
*et+s see the simple e&le of for loop in /avascript.
Program:
<!DOCTYPE html>
<html>
<body>
<script>for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
Dutput:
"
$
%
2) JavaScript while loop
The Javacript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not 'nown. The synta& of whileloop is given below.
while (condition)7
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 23/55
code to be e&ecuted8
*et+s see the simple e&le of while loop in /avascript.
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=13)
{
document.write(i + "<br/>");
i++;
}
</script></body>
</html>
Dutput:
"
$
3) JavaScript do while loop
The Javacript do while loop iterates the elements for the infinite number of
times li'e while loop. 2ut code is executed at least once whether condition is
true or false. The synta& of do while loop is given below.do7
code to be e&ecuted8while (condition)0
*et+s see the simple e&le of do while loop in /avascript.
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=23);
</script></body>
</html>
Dutput:
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 24/55
"
""
"$
Lesson Plan No. ;: Arras in *a%aScript 7 concepts0tpes ) usage.
JavaScript Array
Javacript array is an ob/ect that represents a collection of similar type of
elements.
There are $ ways to construct array in JavaScript. 2y array literal". 2y creating instance of 6rray directly (using new 'eyword)$. 2y using an 6rray constructor (using new 'eyword)
1) JavaScript array literal
The synta& of creating array using array literal is given below:var arrayname,Vvaluevalue".....value>W0
6s you can see values are contained inside V W and separated by (comma).
*et+s see the simple e&le of creating and using array in JavaScript.<script> var emp,VSonooXimalHatanW0for (i,0i<emp.length0i;;)7document.write(empViW ; <br/>)08</script>
Program:
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
Output of the above example
Sonoo
XimalHatan
2) JavaScript Array directly (new keyword)
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 25/55
The synta& of creating array directly is given below:var arrayname,new 6rray()0
5ere new "eyword is used to create instance of array.
*et+s see the e&le of creating array directly.
Program:
<html><body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Output of the above example
6run
XarunJohn
JavaScript array constructor (new keyword)
5ere you need to create instance of array by passing arguments in constructor
so that we donGt have to provide value e&plicitely.
The e&le of creating ob/ect by array constructor is given below.
Program:
<html>
<body>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Output of the above example
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 26/55
Jai
Xi/ay
Smith
Lesson Plan No. <: #ntroduction to !unctions in *a%aScript
JavaScript Functions
Javacript functions are used to perform operations. 1e can call JavaScript
function many times to reuse the code.
Advantage of JavaScript functionThere are mainly two advantages of JavaScript functions.
1 'ode reusability: 1e can call a function several times so it save coding.! ess coding: It ma'es our program compact. 1e don+t need to write
many lines of code each time to perform a common tas'.
JavaScript Function Syntax
The synta& of declaring function is given below.function function>ame(Varg arg" ...arg>W)7 code to be e&ecuted8
JavaScript <unctions can have or more arguments.
JavaScript Function Example
*et+s see the simple e&le of function in JavaScript that does not has
arguments.
Program:
<html>
<body><script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Output:
Function Arguments
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 27/55
1e can call function by passing arguments. *et+s see the e&le of function
that has one argument.<script> function getcube(number)7alert(number=number=number)08</script>
<form> <input type,button value,clic' onclic',getcube(%)/> </form>
Program:
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
Function with Return Value1e can call function that returns a value and use it in our program. *et+s see
the e&le of function that returns value.
Program:
<html>
<body>
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
Output of the above example
hello /avatpointN 5ow r uU
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 28/55
Lesson Plan No. 1=: 6uilt in *a%aScript &unctionso%er%iew.
JavaScript Objects
6 JavaScript ob/ect is an entity having state and behavior (properties and
method). <or e&le: car pen bi'e chair glass 'eyboard monitor etc.
JavaScript is an ob/ect-based language. Kverything is an ob/ect in JavaScript.
JavaScript is template based not class based. 5ere we donGt create class to get
the ob/ect. 2ut we direct create ob/ects.
Creating Objects in JavaScript
There are $ ways to create ob/ects.
. 2y ob/ect literal". 2y creating instance of Db/ect directly (using new 'eyword)$. 2y using an ob/ect constructor (using new 'eyword)
1) JavaScript Object by object literal
The synta& of creating ob/ect using ob/ect literal is given below:ob/ect,7property:valueproperty":value".....property>:value>8
6s you can see property and value is separated by : (colon).
*et+s see the simple e&le of creating ob/ect in JavaScript.<script> emp,7id:"name:Shyam Yumarsalary:%8document.write(emp.id; ;emp.name; ;emp.salary)0</script>
Program:
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body> </html>
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 29/55
Output of the above example:%$ hyam *umar +$$$$
2) By creating instance of Object
The synta& of creating ob/ect directly is given below:var ob/ectname,new Db/ect()0
5ere new "eyword is used to create ob/ect.
*et+s see the e&le of creating ob/ect directly.<script> var emp,new Db/ect()0emp.id,0emp.name,Havi 9ali'0emp.salary,0document.write(emp.id; ;emp.name; ;emp.salary)0</script>
Program:
<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body></html>
Output of the above example
Havi
3) By using an Object constructor
5ere you need to create function with arguments. Kach argument value can be
assigned in the current ob/ect by using this 'eyword.
The this "eyword refers to the current ob/ect.
The e&le of creating ob/ect by ob/ect constructor is given below.<script> function emp(idnamesalary)7this.id,id0this.name,name0this.salary,salary08e,new emp($Ximal Jaiswal$)0
document.write(e.id; ;e.name; ;e.salary)0
</script> Program:
<html>
<body>
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 30/55
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
Output of the above example
$ Ximal Jaiswal $
Defining method in JavaScript Object
1e can define method in JavaScript ob/ect. 2ut before defining method weneed to add property in the function with same name as method.
The e&le of defining method in ob/ect is given below.
Program:
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
Output of the above example
$ Sonoo Jaiswal $$ Sonoo Jaiswal %
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 31/55
Lesson Plan No. 11: The String data tpe in *a%aScript.
#ntroduction to String0 'ath and ,ate !unctions.
JavaScript String
The Javacript string is an ob/ect that represents a seuence of characters.
There are " ways to create string in JavaScript. 2y string literal
". 2y string ob/ect (using new 'eyword)
1) By string literal
The string literal is created using double uotes. The synta& of creating string
using string literal is given below:var stringname,string value0
*et+s see the simple e&le of creating string literal.
Program:
<!DOCTYPE html>
<html> <body>
<script>
var str="This is string literal";
document.write(str);
</script>
</body></html>
Dutput: This is string literal
2) By string object (using new keyword)The synta& of creating string ob/ect using new 'eyword is given below:
var stringname,new String(string literal)0
5ere new "eyword is used to create instance of string.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 32/55
*et+s see the e&le of creating string in JavaScript by new 'eyword.<script> var stringname,new String(hello /avascript string)0document.write(stringname)0</script>
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>
Dutput:hello /avascript string
JavaScript String Methods
*etGs see the list of JavaScript string methods with e&les.) char6t(inde&)") concat(str)$) inde&Df(str)%) lastInde&Df(str)) to*ower!ase()L) topper!ase()Z) slice(beginInde& endInde&)[) trim()
1) JavaScript String charAt(index) Method
The JavaScript String char6t() method returns the character at the given inde&.<script> var str,/avascript0document.write(str.char6t("))0</script>
Program:<!DOCTYPE html>
<html>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
</body>
</html>
Dutput: v
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 33/55
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or /oins two strings.<script> var s,/avascript 0var s",concat e&le0var s$,s.concat(s")0document.write(s$)0
</script>
Program:
<!DOCTYPE html>
<html> <body> <script>
var s1="javascript ";
var s2="concat example";
var s3=s1+s2;
document.write(s3);
</script> </body> </html>Dutput:
/avascript concat e&le
3) JavaScript String indexOf(str) Method
The JavaScript String inde&Df(str) method returns the inde& position of the
given string.<script> var s,/avascript from /avatpoint inde&of0var n,s.inde&Df(from)0
document.write(n)0</script>
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");document.write(n);
</script>
</body>
</html>]
Dutput: 11
4) JavaScript String lastIndexOf(str) Method
The JavaScript String lastInde&Df(str) method returns the last inde& position of
the given string.<script> var s,/avascript from /avatpoint inde&of0
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 34/55
var n,s.lastInde&Df(/ava)0document.write(n)0</script>
Dutput: L
5) JavaScript String toLowerCase() MethodThe JavaScript String to*ower!ase() method returns the given string in
lowercase letters.<script> var s,JavaScript to*ower!ase K&le0var s",s.to*ower!ase()0document.write(s")0</script>
Dutput:
/avascript tolowercase e&le
6) JavaScript String toUpperCase() Method
The JavaScript String topper!ase() method returns the given string in
uppercase letters.
<script> var s,JavaScript topper!ase K&le0var s",s.topper!ase()0
document.write(s")0</script>
Dutput: J6X6S!HIFT TDFFKH!6SK KC69F*K
7) JavaScript String slice(beginIndex, endIndex) Method
The JavaScript String slice(beginInde& endInde&) method returns the parts of
string from given beginInde& to endInde&. In slice() method beginInde& is
inclusive and endInde& is e&clusive.
<script> var s,abcdefgh0var s",s.slice(")0document.write(s")0</script>
Dutput: cde
8) JavaScript String trim() MethodThe JavaScript String trim() method removes leading and trailing whitespaces
from the string.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 35/55
<script> var s, /avascript trim 0var s",s.trim()0document.write(s")0</script>
Dutput:
/avascript trim
JavaScript Date Object
The Javacript date ob/ect can be used to get year month and day. Eou can
display a timer on the webpage by the help of JavaScript date ob/ect.
Eou can use different #ate constructors to create date ob/ect. It provides
methods to get and set day month year hour minute and seconds.
Constructor
Eou can use % variant of #ate constructor to create date ob/ect.. #ate()". #ate(milliseconds)$. #ate(dateString)%. #ate(year month day hours minutes seconds milliseconds)
JavaScript Date Methods
The important methods of date ob/ect are as follows:
Method Description
get<ullEear() returns the year in % digit e.g. ". It is a new method and
suggested than getEear() which is now deprecated.
get9onth() returns the month in " digit from to $.
get#ate() returns the date in or " digit from to $.
get#ay() returns the day of wee' in digit from to L.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 36/55
get5ours() returns all the elements having the given name value.
get9inutes() returns all the elements having the given class name.
getSeconds() returns all the elements having the given class name.
get9illiseconds() returns all the elements having the given tag name.
JavaScript Date Example
*etGs see the simple e&le to print date ob/ect. It prints date and time both.!urrent #ate and Time: <span id,t&t></span> <script> var today,new #ate()0document.getKlement2yId(Gt&tG).inner5T9*,today0</script>
Program:
<html> <body>Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script> </body> </html>
OP:%urrent &ate and 'ime( 'hu Apr $) !$1* 11($+(1, #M'$*.$ /0ndia Standard 'ime
JavaScript Current Time Example
*etGs see the simple e&le to print current time of system.
!urrent Time: <span id,t&t></span> <script> var today,new #ate()0var h,today.get5ours()0var m,today.get9inutes()0var s,today.getSeconds()0document.getKlement2yId(Gt&tG).inner5T9*,h;:;m;:;s0</script>
Program:2html3 2body3
%urrent &ate and 'ime( 2span id45txt5326span32script3
var today4ne7 &ate/8
documentgetElement9y0d/:txt:inner;'M"4today8
26script3 26body3 26html3
Dutput: !urrent Time: :L:%
JavaScript Digital Clock Example
*etGs see the simple e&le to display digital cloc' using JavaScript date
ob/ect.
There are two ways to set interval in JavaScript: by setTimeout() or
setInterval() method.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 37/55
Program:
<html> <body>
Current Time: <span id="txt"></span>
<script>
window.onload=function(){getTime();}
function getTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds(); // add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
} //setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
}
return i;
} </script> </body> </html>
OP:%urrent 'ime
JavaScript Math Object
The Javacript math ob/ect provides several constants and methods to
perform mathematical operation. nli'e date ob/ect it doesnGt have
constructors.
Math.sqrt(n)
The JavaScript math.srt(n) method returns the suare root of the given
number.Suare Hoot of Z is: <span id,p></span> <script> document.getKlement2yId(GpG).inner5T9*,9ath.srt(Z)0</script>
Program:2<&=%'>?E html3
2html3
2body3
S@uare oot of 1+ is( 2span id45p15326span3
2script3
documentgetElement9y0d/:p1:inner;'M"4Maths@rt/1+8
26script326body3
26html3
Dutput:
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 38/55
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 39/55
The JavaScript math.round(n) method returns the rounded integer nearest for
the given number. If fractional part is eual or greater than . it goes to upper
value otherwise lower value .
<or e&le % for $.Z $ for $.$ L for .B etc.
Hound of %.$ is: <span id,pL></span><br>
Hound of %.Z is: <span id,pZ></span> <script> document.getKlement2yId(GpLG).inner5T9*,9ath.round(%.$)0document.getKlement2yId(GpZG).inner5T9*,9ath.round(%.Z)0
</script>
Dutput:
Hound of %.$ is: %
Hound of %.Z is:
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given
number. <or e&le % for -% L.L for -L.L etc.
6bsolute value of -% is: <span id,p[></span> <script> document.getKlement2yId(Gp[G).inner5T9*,9ath.abs(-%)0</script>
Dutput:
6bsolute value of -% is: %
Lesson Plan No. 1":- oncepts o& Pop >p boxes in *a%aScript
Browser Object Model
%. Browser Object Model BOM!
The ,rowser -bject odel (2D9) is used to interact with the browser.
The default ob/ect of browser is window means you can call all the functions of
window by specifying window or directly. <or e&le:window.alert(hello /avatpoint)0
is same as:alert(hello /avatpoint)0
Eou can use a lot of properties (other ob/ects) defined underneath the window
ob/ect li'e document history screen navigator location inner5eight
inner1idth
Note: The document object represents an html document. It forms DOM (DocumentObject Model).
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 40/55
Window Object. Windo7 =bject
". ?roperties of Windo7 =bject$. Methods of Windo7 =bject
%. Example of Windo7 =bject
The window object represents a window in browser. 6n ob/ect of window is
created automatically by the browser.
1indow is the ob/ect of browser it is not the object of javascript. The
/avascript ob/ects are string array date etc.
Note: if html document contains frame or iframe, browser creates additional window
objects for each frame.
Methods of window object
The important methods of window ob/ect are as follows:
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 41/55
Method Description
alert() displays the alert bo& containing message with o' button.
confirm() displays the confirm dialog bo& containing message with o' and cancel
button.
prompt() displays a dialog bo& to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time li'e calling function evaluating
e&pressions etc.
Alert Box6n alert bo& is often used if you want to ma'e sure information comes through to
the user.
1hen an alert bo& pops up the user will have to clic' DY to proceed.
Syntax
window.alert8"sometext "9?
The window.alert method can be written without the window prefi&.
Examplealert8"7 am an alert boxP"9?
OUTPUT :-%licB the button to display an alert box(
'ry it
Example of alert() in javascript
It displays alert dialog bo&. It has message and o' button.
<script type,te&t/avascript> function msg()7alert(5ello 6lert 2o&)0
8</script> <input type,button value,clic' onclic',msg()/>
Output of the above example
Confirm Box6 confirm bo& is often used if you want the user to verify or accept something.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 42/55
1hen a confirm bo& pops up the user will have to clic' either DY or !ancel to
proceed.
If the user clic's DY the bo& returns true. If the user clic's !ancel the bo&
returns false.
Syntax
window.con3rm8"sometext "9?
The window.confirm() method can be written without the window prefi&.
Example
var r M con3rm8":ress a button"9?if 8r MM true9 Q x M "4ou pressed RP"?S else Q x M "4ou pressed >ancelP"?
S
OUTPUT:-%licB the button to display a confirm box
'ry it
Example of confirm() in javascript
It displays the confirm dialog bo&. It has message with o' and cancel buttons.<script type,te&t/avascript>
function msg()7var v, confirm(6re u sureU)0if(v,,true)7alert(o')08else7alert(cancel)088</script>
<input type,button value,delete record onclic',msg()/> Output of the above example
Prompt Box6 prompt bo& is often used if you want the user to input a value before entering a
page.
1hen a prompt bo& pops up the user will have to clic' either DY or !ancel to
proceed after entering an input value.
If the user clic's DY the bo& returns the input value. If the user clic's !ancel
the bo& returns null.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 43/55
Syntax
window.prompt8"sometext ","defaultText "9?
The window.prompt() method can be written without the window prefi&.
Example
var person M prompt8":lease enter your name", "arry :otter"9?
if 8person PM null9 Q document.get1lementHy7d8"demo"9.innerT)! M "ello " O person O "P ow are you today"?S
Example of prompt() in javascript
It displays prompt dialog bo& for input. It has message and te&tfield.<script type,te&t/avascript> function msg()7var v, prompt(1ho are youU)0
alert(I am ;v)08
</script>
<input type,button value,clic' onclic',msg()/>
Output of the above example
Example of open() in javascript
It displays the content in a new window.<script type,te&t/avascript> function msg()7open(http:www./avatpoint.com)08</script> <input type,button value,/avatpoint onclic',msg()/>
Output of the above example
Example of setTimeout() in javascriptIt performs its tas' after the given milliseconds.
<script type,te&t/avascript> function msg()7setTimeout(function()7alert(1elcome to Javatpoint after " seconds)8")0
8
</script>
<input type,button value,clic' onclic',msg()/>
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 44/55
Output of the above example
Lesson Plan No. 1(:- #ntroduction to the ,ocument?b@ect 'odel.
Document Object Model. &ocument =bject
". ?roperties of document object
$. Methods of document object
%. Example of document object
) ocument object represents the whole html document.
1hen html document is loaded in the browser it becomes a document ob/ect. It
is the root element that represents the html document.
6s mentioned earlier it is the ob/ect of window. So
window.documentIs same as
document
6ccording to 1$! - "The W3C Document Object odel !DO is a platform and
language-neutral interface that allows programs and scripts to d#namicall#
access and update the content$ structure$ and st#le of a document."
2) Properties of document object
*etGs see the properties of document ob/ect that can be accessed and modified
by the document
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 45/55
ob/ect.
3) Methods of document object1e can access and change the contents of document by its methods.
The important methods of document ob/ect are as follows:
Method Description
write(string) writes the given string on the doucment.
writeln(string) writes the given string on the doucment with
newline character at the end.
getKlement2yId() returns the element having the given id value.
getKlements2y>ame() returns all the elements having the given name
value.
getKlements2yTag>ame() returns all the elements having the given tag name.
getKlements2y!lass>ame() returns all the elements having the given class
name.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 46/55
Accessing the field value by document object
In this e&le we are going to get the value of input te&t by user. 5ere we
are usingdocument.form%.name.value to get the value of name field.
5ere document is the root element that represents the html document.
form% is the name of the form.
name is the attribute name of the input te&t.
value is the property that returns the value of the input te&t.
*etGs see the simple e&le of document ob/ect that prints name with
welcome message.
<script type,te&t/avascript> function printvalue()7var name,document.form.name.value0alert(1elcome: ;name)08
</script> <form name,form> Knter >ame:<input type,te&t name,name/> <input type,button onclic',printvalue() value,print name/> </form>
Output of the above example
Knter >ame:
Javascript - document.getElementById() method. getElement9y0d/ method
". Example of getElement9y0d/
The document.get0lement,y1d() method returns the element of specified id.
In the previous page we have used document.form%.name.value to get the
value of the input value. Instead of this we can use
document.getKlement2yId() method to get value of the input te&t. 2ut we need
to define id for the input field.*etGs see the simple e&le of document.getKlement2yId() method that prints
cube of the given number.<script type,te&t/avascript> function getcube()7var number,document.getKlement2yId(number).value0alert(number=number=number)08</script> <form>
Knter >o:<input type,te&t id,number name,number/><br/> <input type,button value,cube onclic',getcube()/> </form>
Output of the above example
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 47/55
Knter >o:
Javascript - document.getElementsByName() method. getElements9yCame/ method
". Example of getElements9yCame/
The document.get0lements,y2ame() method returns all the element of
specified name.The synta& of the getKlements2y>ame() method is given below:
document.getKlements2y>ame(name)
5ere name is reuired.
Example of document.getElementsByName() method
In this e&le we going to count total number of genders. 5ere we are using
getKlements2y>ame() method to get all the genders.<script type,te&t/avascript> function totalelements()
7var allgenders,document.getKlements2y>ame(gender)0alert(Total Oenders:;allgenders.length)08</script> <form> 9ale:<input type,radio name,gender value,male> <emale:<input type,radio name,gender value,female> <input type,button onclic',totalelements() value,Total Oenders></form>
Output of the above example9ale: <emale:
Javascript - document.getElementsByTagName() method. getElements9y'agCame/ method
". Example of getElements9y'agCame/
The document.get0lements,y!ag2ame() method returns all the element of
specified tag name.
The synta& of the getKlements2yTag>ame() method is given below:document.getKlements2yTag>ame(name)
5ere name is reuired.
Example of document.getElementsByTagName() method
In this e&le we going to count total number of paragraphs used in the
document. To do this we have called the
document.getKlements2yTag>ame(p) method that returns the total
paragraphs.<script type,te&t/avascript> function countpara()7var totalpara,document.getKlements2yTag>ame(p)0
alert(total p tags are: ;totalpara.length)08</script> <p>This is a pragraph</p>
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 48/55
<p>5ere we are going to count total number of paragraphs by getKlement2yTag>ame() method.</p> <p>*etGs see the simple e&le</p>
<button onclic',countpara()>count paragraph</button>
Output of the above example
This is a pragraph
5ere we are going to count total number of paragraphs by
getKlement2yTag>ame() method.
*etGs see the simple e&le
count paragraph
Another example of document.getElementsByTagName() method
In this e&le we going to count total number of h" and h$ tags used in the
document.<script type,te&t/avascript> function counth"()7var totalh",document.getKlements2yTag>ame(h")0alert(total h" tags are: ;totalh".length)08function counth$()7var totalh$,document.getKlements2yTag>ame(h$)0alert(total h$ tags are: ;totalh$.length)08</script> <h>This is h" tag</h>
<h>This is h" tag</h> <h#>This is h$ tag</h#> <h#>This is h$ tag</h#> <h#>This is h$ tag</h#> <button onclic',counth"()>count h"</button> <button onclic',counth$()>count h$</button>
Output of the above example
!his is h tag
!his is h tag!his is h# tag
!his is h# tag
!his is h# tag
count h" count h$
Note: Output of the i!en e"amples ma# differ on this pae because it will count the
total number of para , total number of h$ and total number of h% tas used in
this document.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 49/55
Javascript - innerHTML. javascript inner;'M"
". Example of inner;'M" property
The inner3! property can be used to write the dynamic html on the html
document.
It is used mostly in the web pages to generate the dynamic html such as
registration form comment form lin's etc.
Example of innerHTML property
In this e&le we are going to create the html form when user clic's on the
button.
In this e&le we are dynamically writing the html form inside the div namehaving the id mylocation. 1e are identifing this position by calling the
document.getKlement2yId() method.<script type,te&t/avascript >
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 50/55
function showcommentform() 7var data,>ame:Pinput type,Gte&tG name,GnameG3Pbr3!omment:Pte&tarea rows,GG cols,G[G3Pte&tarea3Pbr3Pinput type,GsubmitG value,GcommentG30
document.getKlement2yId(GmylocationG).inner5T9*,data08
</script>
<form name,my<orm> <input type,button value,comment onclic',showcommentform()>
<div id,mylocation></div> </form>
Output of the above example
2ext !opicJavascript innerTe&t
Javascript - innerText. javascript inner'ext
". Example of inner'ext property
The inner!ext property can be used to write the dynamic te&t on the html
document. 5ere te&t will not be interpreted as html te&t but a normal te&t.
It is used mostly in the web pages to generate the dynamic content such as
writing the validation message password strength etc.
Example of innerText property
In this e&le we are going to display the password strength when releases
the 'ey after press.<script type,te&t/avascript > function validate() 7var msg0if(document.my<orm.userFass.value.length>)7msg,good08else7msg,poor08document.getKlement2yId(GmylocationG).innerTe&t,msg08
</script> <form name,my<orm> <input type,password value, name,userFass on'eyup,validate()> Strength:<span id,mylocation>no strength</span> </form>
Output of the above example
Strength:no strength
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 51/55
JavaScript Form Validation. JavaScript form validation
". Example of JavaScript validation
$. JavaScript email validation
It is important to validate the form submitted by the user because it can haveinappropriate values. So validation is must.
The JavaScript provides you the facility the validate the form on the client side
so processing will be fast than server-side validation. So most of the web
developers prefer JavaScript form validation.
Through JavaScript we can validate name password email date mobile
number etc fields.
JavaScript form validation example
In this e&le we are going to validate the name and password. The name
can+t be empty and password can+t be less than L characters long.
5ere we are validating the form on form submit. The user will not be forwarded
to the ne&t page until given values are correct.<script> function validateform()7var name,document.myform.name.value0var password,document.myform.password.value0
if (name,,null RR name,,)7alert(>ame canGt be blan')0return false0
8else if(password.length<4)7alert(Fassword must be at least L characters long.)0return false08
8
</script> <body> <form name,myform method,post action,abc./sp onsubmit,return validateform() > >ame: <input type,te&t name,name><br/> Fassword: <input type,password name,password><br/>
<input type,submit value,register> </form>
JavaScript Retype Password Validation
<script type,te&t/avascript> function matchpass()7var firstpassword,document.f.password.value0var secondpassword,document.f.password".value0
if(firstpassword,,secondpassword)7return true0
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 52/55
8else7alert(password must be sameN)0return false088
</script>
<form name,f action,register./sp onsubmit,return matchpass()>
Fassword:<input type,password name,password /><br/> He-enter Fassword:<input type,password name,password"/><br/> <input type,submit> </form>
JavaScript Number Validation
*etGs validate the te&tfield for numeric value only. 5ere we are using is>a>()function.
<script> function validate()7var num,document.myform.num.value0if (is>a>(num))7
document.getKlement2yId(numloc).inner5T9*,Knter >umeric valueonly0
return false08else7
return true08
8
</script> <form name,myform onsubmit,return validate() > >umber: <input type,te&t name,num><span id,numloc></span><br/> <input type,submit value,submit> </form>
JavaScript validation with image*et+s see an interactive JavaScript form validation e&le that displays correct
and incorrect image if input is correct or incorrect.<script> function validate()7var name,document.f.name.value0var password,document.f.password.value0var status,false0
if(name.length<%)7document.getKlement2yId(nameloc).inner5T9*,Pimg src,Gunchec'ed.gifG3 Flease enter your name0status,false08else7
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 53/55
document.getKlement2yId(nameloc).inner5T9*,Pimg src,Gchec'ed.gifG30status,true08if(password.length<4)7document.getKlement2yId(passwordloc).inner5T9*,Pimg src,Gunchec'ed.gifG3 Fassword must be at least L char long0
status,false08else7document.getKlement2yId(passwordloc).inner5T9*,Pimg src,Gchec'ed.gifG30status,true08return status08
</script>
<form name,f action,\ onsubmit,return validate()> <table> <tr><td>Knter >ame:</td><td><input type,te&t name,name/>
<span id,nameloc></span></td></tr> <tr><td>Knter Fassword:</td><td><input type,te&t name,password/>
<span id,passwordloc></span></td></tr> <tr><td colspan,"><input type,submit value,register/></td></tr>
</table> </form>
Dutput:
Knter >ame:
Knter Fassword:
Submit
JavaScript email validation
1e can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the email id such as:
• email id must contain the ] and . character
• There must be at least one character before and after the ].
• There must be at least two characters after . (dot).
*etGs see the simple e&le to validate the email field.
<html>
<body>
<script>
function validateemail()
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 54/55
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
HTML/DOM events for JavaScript
5T9* or #D9 events are widely used in JavaScript code. JavaScript code is
e&ecuted with 5T9*#D9 events. So before learning JavaScript let+s have
some idea about events.
Events Description
onclic' occurs when element is clic'ed.
ondblclic' occurs when element is double-clic'ed.
onfocus occurs when an element gets focus such as button input
te&tarea etc.
8/19/2019 Java Script Notes Sem-II-1
http://slidepdf.com/reader/full/java-script-notes-sem-ii-1 55/55
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 ob/ect or frameset is loaded.
onunload occurs when body or frameset is unloaded.
onscroll occurs when document is scrolled.
onresi?ed occurs when document is resi?ed.
onreset occurs when form is reset.
on'eydown occurs when 'ey is being pressed.
on'eypress occurs when user presses the 'ey.
on'eyup occurs when 'ey is released.