SlideShare a Scribd company logo
Java Script Advance
BCA -302
2
Content
 JavaScript Cookies
 JavaScript Page Redirection
 JavaScript Document Object Model
 JavaScript Form Validation
 JavaScript Email Validation
 JavaScript Exceptional Handling
3
JavaScript Cookies
 A cookie is an amount of information that persists between a server-side and a client-
side. A web browser stores this information at the time of browsing.
 A cookie contains the information as a string generally in the form of a name-value
pair separated by semi-colons. It maintains the state of a user and remembers the
user's information among all the web pages.
 Cookies were originally designed for CGI programming. The data contained in a
cookie is automatically transmitted between the web browser and the web server, so
CGI scripts on the server can read and write cookie values that are stored on the
client.
 JavaScript can also manipulate cookies using the cookie property of
the Document object. JavaScript can read, create, modify, and delete the cookies
that apply to the current web page.
4
How Cookies Work?
 When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.
 So, to recognize the old user, we need to add the cookie with the response from the
server.
 browser at the client-side.
 Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users
5
Cookies
Cookies are a plain text data record of 5 variable-length fields −
1. Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.
2. Domain − The domain name of your site.
3. Path − The path to the directory or web page that set the cookie. This may be blank if you want
to retrieve the cookie from any directory or page.
4. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
5. Name=Value − Cookies are set and retrieved in the form of key-value pairs
Here the expires attribute is optional. If programmer provide this attribute with a valid date or time,
then the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason,
JavaScript escape() function is used to encode the value before storing it in the cookie and the
corresponding unescape() function is used to read the cookie value.
6
Syntax and Example of creating cookies
document.cookie = "key1 = value1;key2 = value2;expires = date";
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
7
Syntax and Example of creating cookies
document.cookie = "key1 = value1;key2 = value2;expires = date";
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
8
Example of creating cookies
9
JavaScript Page Redirection
There might be a situation where you clicked a URL to reach a page X but internally you were
directed to another page Y. It happens due to page redirection.
There could be various reasons why you would like to redirect a user from the original page. We are
listing down a few of the reasons −
 You did not like the name of your domain and you are moving to a new one. In such a scenario,
you may want to direct all your visitors to the new site. Here you can maintain your old domain but
put a single page with a page redirection such that all your old domain visitors can come to your
new domain.
 You have built-up various pages based on browser versions or their names or may be based on
different countries, then instead of using your server-side page redirection, you can use client-
side page redirection to land your users on the appropriate page.
 The Search Engines may have already indexed your pages. But while moving to another domain,
you would not like to lose your visitors coming through search engines. So you can use client-side
page redirection. But keep in mind this should not be done to fool the search engine, it could lead
your site to get banned.
10
Page Redirection Example
To redirect the page from one URL to another location() function is used:
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.ismp.ac.in";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>
</body>
</html>
11
JavaScript Document Object Model (DOM)
 The document object represents the whole html document.
 When html document is loaded in the browser, it becomes a document object.
 It is the root element that represents the html document.
 It has properties and methods.
 By the help of document object, we can add dynamic content to our web page
 The way a document content is accessed and modified is called the Document Object
Model, or DOM.
 The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document..
12
JavaScript Document Object Model (DOM)
 The document object represents the whole html document.
 When html document is loaded in the browser, it becomes a document object.
 It is the root element that represents the html document.
 It has properties and methods.
 By the help of document object, we can add dynamic content to our web page
 The way a document content is accessed and modified is called the Document Object
Model, or DOM.
 The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document..
13
JavaScript DOM Hierarchy
14
JavaScript DOM Methods
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.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
15
JavaScript DOM Example
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
In the above code
document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
16
JavaScript getElementById() Example
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
17
JavaScript getElementsByName() Example
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Gend
ers">
</form>
18
JavaScript getElementsByTagName() Example
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by get
ElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
19
JavaScript innerHTML property Example
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows
='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
The innerHTML property can be used to write the dynamic html on the html document.
It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.
20
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
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.
Programmer can validate a form by defining different function as per requirement. Common
validation include:
 Text Length
 Text Type
 Password Validation
 Email Validation, etc.
21
JavaScript Email Validation Example
<script>
function validateemail()
{
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="#" onsubmit="return valida
teemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
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).
22
JavaScript Form Validation Example
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
Following code will validate the name and password. The name can’t be empty and password can’t
be less than 6 characters long.
23
JavaScript Error and Exceptional Handling
 An exception signifies the presence of an abnormal condition which requires special
operable techniques. In programming terms, an exception is the anomalous code that
breaks the normal flow of the code. Such exceptions require specialized programming
constructs for its execution.
 In programming, exception handling is a process or method used for handling the abnormal
statements in the code and executing them.
 It also enables to handle the flow control of the code/program.
 For handling the code, various handlers are used that process the exception and execute
the code.
 For example, the Division of a non-zero value with zero will result into infinity always, and it
is an exception. Thus, with the help of exception handling, it can be executed and handled.
24
JavaScript Error and Exceptional Handling
While coding, there can be three types of errors in the code:
Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming
language, a syntax error may appear. It is also known as Parsing Error. When a syntax error
occurs in JavaScript, only the code contained within the same thread as the syntax error is
affected and the rest of the code in other threads gets executed assuming nothing in them
depends on the code containing the error.
Runtime Error: When an error occurs during the execution of the program, such an error is
known as Runtime error. The codes which create runtime errors are known as Exceptions.
Thus, exception handlers are used for handling runtime errors. Exceptions also affect the thread
in which they occur, allowing other JavaScript threads to continue normal execution.
Logical Error: An error which occurs when there is any logical mistake in the program that may
not produce the desired output, and may terminate abnormally. Such an error is known as
Logical error.
25
JavaScript Error and Exceptional Handling Contd…
There are following statements that handle if any exception occurs:
1. throw statements
2. try…catch statements
3. try…catch…finally statement
try{} statement: Here, the code which needs possible error testing is kept within the try block.
In case any error occur, it passes to the catch{} block for taking suitable actions and handle the
error. Otherwise, it executes the code written within.
catch{} statement: This block handles the error of the code by executing the set of statements
written within the block. This block contains either the user-defined exception handler or the
built-in handler. This block executes only when any error-prone code needs to be handled in the
try block. Otherwise, the catch block is skipped.
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and
the catch block is executed. The optional finally block executes unconditionally after try/catch.
26
Example of throw statement
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
</script>
</head>
<body>
<p>Click the following to see the
result:</p>
<form>
<input type = "button" value = "Click
Me" onclick = "myFunc();" />
</form>
</body>
</html>
27
Example of try-catch statement
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
</script>
</head>
<body>
<p>Click the following to see the
result:</p>
<form>
<input type = "button" value = "Click
Me" onclick = "myFunc();" />
</form>
</body>
</html>
28
Example of try…catch…finally statement
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always
execute!" );
}
}
</script>
</head>
<body>
<p>Click the following to see the
result:</p>
<form>
<input type = "button" value = "Click
Me" onclick = "myFunc();" />
</form>
</body>
</html>

More Related Content

PDF
22 j query1
Fajar Baskoro
 
PPTX
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
PPTX
2.java script dom
PhD Research Scholar
 
PPTX
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
PPTX
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Ayes Chinmay
 
PPTX
Internet and Web Technology (CLASS-6) [BOM]
Ayes Chinmay
 
PPTX
Ch05 state management
Madhuri Kavade
 
PDF
Web 6 | JavaScript DOM
Mohammad Imam Hossain
 
22 j query1
Fajar Baskoro
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
2.java script dom
PhD Research Scholar
 
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Ayes Chinmay
 
Internet and Web Technology (CLASS-6) [BOM]
Ayes Chinmay
 
Ch05 state management
Madhuri Kavade
 
Web 6 | JavaScript DOM
Mohammad Imam Hossain
 

What's hot (20)

PDF
1 ppt-ajax with-j_query
Fajar Baskoro
 
PDF
Web 5 | JavaScript Events
Mohammad Imam Hossain
 
PPTX
JSON and XML
People Strategists
 
PPTX
Web Development Introduction to jQuery
Laurence Svekis ✔
 
PPTX
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
PDF
AngularJS By Vipin
Vipin Mundayad
 
PDF
Mongodb By Vipin
Vipin Mundayad
 
PPTX
Javascript
poojanov04
 
PPT
Spsl v unit - final
Sasidhar Kothuru
 
PDF
Javascript and DOM
Brian Moschel
 
PPTX
Java script cookies
AbhishekMondal42
 
PDF
Javascript projects Course
Laurence Svekis ✔
 
PPT
JavaScript Training
Ramindu Deshapriya
 
PPT
03DOM.ppt
Bhavani Testone
 
DOCX
Managing states
Paneliya Prince
 
PDF
Intro to jQuery
Shawn Calvert
 
PPTX
Jquery Basics
Umeshwaran V
 
PPTX
Java script
Sukrit Gupta
 
PDF
GDI Seattle - Intro to JavaScript Class 4
Heather Rock
 
1 ppt-ajax with-j_query
Fajar Baskoro
 
Web 5 | JavaScript Events
Mohammad Imam Hossain
 
JSON and XML
People Strategists
 
Web Development Introduction to jQuery
Laurence Svekis ✔
 
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
AngularJS By Vipin
Vipin Mundayad
 
Mongodb By Vipin
Vipin Mundayad
 
Javascript
poojanov04
 
Spsl v unit - final
Sasidhar Kothuru
 
Javascript and DOM
Brian Moschel
 
Java script cookies
AbhishekMondal42
 
Javascript projects Course
Laurence Svekis ✔
 
JavaScript Training
Ramindu Deshapriya
 
03DOM.ppt
Bhavani Testone
 
Managing states
Paneliya Prince
 
Intro to jQuery
Shawn Calvert
 
Jquery Basics
Umeshwaran V
 
Java script
Sukrit Gupta
 
GDI Seattle - Intro to JavaScript Class 4
Heather Rock
 
Ad

Similar to Java script Advance (20)

PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PPTX
Introduction to java script, how to include java in HTML
backiyalakshmi14
 
PPTX
Internet protocol second unit IIPPT.pptx
ssuser92282c
 
PPT
Cookies and sessions
Lena Petsenchuk
 
PPTX
Knockout.js
Vivek Rajan
 
PPTX
19_JavaScript - Storage_Cookies_students.pptx
VatsalJain39
 
PPS
Java script
Mohammed Sheikh Salem
 
PPTX
Javascript for web Programming creating and embedding with html
E.M.G.yadava womens college
 
PPTX
How to add Many2Many fields in odoo website form.pptx
Celine George
 
PPTX
CHAPTER 3 JS (1).pptx
achutachut
 
PDF
Angular JS2 Training Session #2
Paras Mendiratta
 
DOCX
Caching in asp.net
MohitKumar1985
 
DOCX
Caching in asp.net
MohitKumar1985
 
PPTX
Web Technologies - forms and actions
Aren Zomorodian
 
PPTX
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
DOCX
Angular js
prasaddammalapati
 
PPT
9781305078444 ppt ch09
Terry Yoast
 
PPTX
81.pptx ajx fyjc semester paper 2 parrtens
epfoportal69
 
PDF
Introduction to Polymer and Firebase - Simon Gauvin
Simon Gauvin
 
PDF
Intro to JavaScript
Jussi Pohjolainen
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
Introduction to java script, how to include java in HTML
backiyalakshmi14
 
Internet protocol second unit IIPPT.pptx
ssuser92282c
 
Cookies and sessions
Lena Petsenchuk
 
Knockout.js
Vivek Rajan
 
19_JavaScript - Storage_Cookies_students.pptx
VatsalJain39
 
Javascript for web Programming creating and embedding with html
E.M.G.yadava womens college
 
How to add Many2Many fields in odoo website form.pptx
Celine George
 
CHAPTER 3 JS (1).pptx
achutachut
 
Angular JS2 Training Session #2
Paras Mendiratta
 
Caching in asp.net
MohitKumar1985
 
Caching in asp.net
MohitKumar1985
 
Web Technologies - forms and actions
Aren Zomorodian
 
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
Angular js
prasaddammalapati
 
9781305078444 ppt ch09
Terry Yoast
 
81.pptx ajx fyjc semester paper 2 parrtens
epfoportal69
 
Introduction to Polymer and Firebase - Simon Gauvin
Simon Gauvin
 
Intro to JavaScript
Jussi Pohjolainen
 
Ad

More from Jaya Kumari (20)

PPTX
Python data type
Jaya Kumari
 
PPTX
Introduction to python
Jaya Kumari
 
PPTX
Variables in python
Jaya Kumari
 
PPTX
Basic syntax supported by python
Jaya Kumari
 
PPTX
Oops
Jaya Kumari
 
PPTX
Inheritance
Jaya Kumari
 
PPTX
Overloading
Jaya Kumari
 
PPTX
Decision statements
Jaya Kumari
 
PPTX
Loop control statements
Jaya Kumari
 
PPTX
Looping statements
Jaya Kumari
 
PPTX
Operators used in vb.net
Jaya Kumari
 
PPTX
Variable and constants in Vb.NET
Jaya Kumari
 
PPTX
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
PPTX
Introduction to vb.net
Jaya Kumari
 
PPTX
Frame class library and namespace
Jaya Kumari
 
PPTX
Introduction to .net
Jaya Kumari
 
PPTX
Jsp basic
Jaya Kumari
 
PPTX
Java script Basic
Jaya Kumari
 
PPTX
Sgml and xml
Jaya Kumari
 
PPTX
Html form
Jaya Kumari
 
Python data type
Jaya Kumari
 
Introduction to python
Jaya Kumari
 
Variables in python
Jaya Kumari
 
Basic syntax supported by python
Jaya Kumari
 
Inheritance
Jaya Kumari
 
Overloading
Jaya Kumari
 
Decision statements
Jaya Kumari
 
Loop control statements
Jaya Kumari
 
Looping statements
Jaya Kumari
 
Operators used in vb.net
Jaya Kumari
 
Variable and constants in Vb.NET
Jaya Kumari
 
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
Introduction to vb.net
Jaya Kumari
 
Frame class library and namespace
Jaya Kumari
 
Introduction to .net
Jaya Kumari
 
Jsp basic
Jaya Kumari
 
Java script Basic
Jaya Kumari
 
Sgml and xml
Jaya Kumari
 
Html form
Jaya Kumari
 

Recently uploaded (20)

PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Software Development Methodologies in 2025
KodekX
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
This slide provides an overview Technology
mineshkharadi333
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Architecture of the Future (09152021)
EdwardMeyman
 

Java script Advance

  • 2. 2 Content  JavaScript Cookies  JavaScript Page Redirection  JavaScript Document Object Model  JavaScript Form Validation  JavaScript Email Validation  JavaScript Exceptional Handling
  • 3. 3 JavaScript Cookies  A cookie is an amount of information that persists between a server-side and a client- side. A web browser stores this information at the time of browsing.  A cookie contains the information as a string generally in the form of a name-value pair separated by semi-colons. It maintains the state of a user and remembers the user's information among all the web pages.  Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.  JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
  • 4. 4 How Cookies Work?  When a user sends a request to the server, then each of that request is treated as a new request sent by the different user.  So, to recognize the old user, we need to add the cookie with the response from the server.  browser at the client-side.  Now, whenever a user sends a request to the server, the cookie is added with that request automatically. Due to the cookie, the server recognizes the users
  • 5. 5 Cookies Cookies are a plain text data record of 5 variable-length fields − 1. Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. 2. Domain − The domain name of your site. 3. Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page. 4. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. 5. Name=Value − Cookies are set and retrieved in the form of key-value pairs Here the expires attribute is optional. If programmer provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible. Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, JavaScript escape() function is used to encode the value before storing it in the cookie and the corresponding unescape() function is used to read the cookie value.
  • 6. 6 Syntax and Example of creating cookies document.cookie = "key1 = value1;key2 = value2;expires = date"; <html> <head> <script type = "text/javascript"> function WriteCookie() { if( document.myform.customer.value == "" ) { alert("Enter some value!"); return; } cookievalue = escape(document.myform.customer.value) + ";"; document.cookie = "name=" + cookievalue; document.write ("Setting Cookies : " + "name=" + cookievalue ); } </script> </head> <body> <form name = "myform" action = ""> Enter name: <input type = "text" name = "customer"/> <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/> </form> </body> </html>
  • 7. 7 Syntax and Example of creating cookies document.cookie = "key1 = value1;key2 = value2;expires = date"; <html> <head> <script type = "text/javascript"> function WriteCookie() { if( document.myform.customer.value == "" ) { alert("Enter some value!"); return; } cookievalue = escape(document.myform.customer.value) + ";"; document.cookie = "name=" + cookievalue; document.write ("Setting Cookies : " + "name=" + cookievalue ); } </script> </head> <body> <form name = "myform" action = ""> Enter name: <input type = "text" name = "customer"/> <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/> </form> </body> </html>
  • 9. 9 JavaScript Page Redirection There might be a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons −  You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain.  You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client- side page redirection to land your users on the appropriate page.  The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned.
  • 10. 10 Page Redirection Example To redirect the page from one URL to another location() function is used: <html> <head> <script type = "text/javascript"> <!-- function Redirect() { window.location = "https://www.ismp.ac.in"; } //--> </script> </head> <body> <p>Click the following button, you will be redirected to home page.</p> <form> <input type = "button" value = "Redirect Me" onclick = "Redirect();" /> </form> </body> </html>
  • 11. 11 JavaScript Document Object Model (DOM)  The document object represents the whole html document.  When html document is loaded in the browser, it becomes a document object.  It is the root element that represents the html document.  It has properties and methods.  By the help of document object, we can add dynamic content to our web page  The way a document content is accessed and modified is called the Document Object Model, or DOM.  The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document..
  • 12. 12 JavaScript Document Object Model (DOM)  The document object represents the whole html document.  When html document is loaded in the browser, it becomes a document object.  It is the root element that represents the html document.  It has properties and methods.  By the help of document object, we can add dynamic content to our web page  The way a document content is accessed and modified is called the Document Object Model, or DOM.  The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document..
  • 14. 14 JavaScript DOM Methods 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. getElementById() returns the element having the given id value. getElementsByName() returns all the elements having the given name value. getElementsByTagName() returns all the elements having the given tag name. getElementsByClassName() returns all the elements having the given class name.
  • 15. 15 JavaScript DOM Example <script type="text/javascript"> function printvalue(){ var name=document.form1.name.value; alert("Welcome: "+name); } </script> <form name="form1"> Enter Name:<input type="text" name="name"/> <input type="button" onclick="printvalue()" value="print name"/> </form> In the above code document is the root element that represents the html document. form1 is the name of the form. name is the attribute name of the input text. value is the property, that returns the value of the input text.
  • 16. 16 JavaScript getElementById() Example <script type="text/javascript"> function getcube(){ var number=document.getElementById("number").value; alert(number*number*number); } </script> <form> Enter No:<input type="text" id="number" name="number"/><br/> <input type="button" value="cube" onclick="getcube()"/> </form>
  • 17. 17 JavaScript getElementsByName() Example <script type="text/javascript"> function totalelements() { var allgenders=document.getElementsByName("gender"); alert("Total Genders:"+allgenders.length); } </script> <form> Male:<input type="radio" name="gender" value="male"> Female:<input type="radio" name="gender" value="female"> <input type="button" onclick="totalelements()" value="Total Gend ers"> </form>
  • 18. 18 JavaScript getElementsByTagName() Example <script type="text/javascript"> function countpara(){ var totalpara=document.getElementsByTagName("p"); alert("total p tags are: "+totalpara.length); } </script> <p>This is a pragraph</p> <p>Here we are going to count total number of paragraphs by get ElementByTagName() method.</p> <p>Let's see the simple example</p> <button onclick="countpara()">count paragraph</button>
  • 19. 19 JavaScript innerHTML property Example <script type="text/javascript" > function showcommentform() { var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows ='5' cols='80'></textarea> <br><input type='submit' value='Post Comment'>"; document.getElementById('mylocation').innerHTML=data; } </script> <form name="myForm"> <input type="button" value="comment" onclick="showcommentform()"> <div id="mylocation"></div> </form> The innerHTML property can be used to write the dynamic html on the html document. It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.
  • 20. 20 JavaScript Form Validation It is important to validate the form submitted by the user because it can have inappropriate values. So, validation is must to authenticate user. 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. Programmer can validate a form by defining different function as per requirement. Common validation include:  Text Length  Text Type  Password Validation  Email Validation, etc.
  • 21. 21 JavaScript Email Validation Example <script> function validateemail() { 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="#" onsubmit="return valida teemail();"> Email: <input type="text" name="email"><br/> <input type="submit" value="register"> </form> </body> </html> 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).
  • 22. 22 JavaScript Form Validation Example <script> function validateform(){ var name=document.myform.name.value; var password=document.myform.password.value; if (name==null || name==""){ alert("Name can't be blank"); return false; }else if(password.length<6){ alert("Password must be at least 6 characters long."); return false; } } </script> <body> <form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" > Name: <input type="text" name="name"><br/> Password: <input type="password" name="password"><br/> <input type="submit" value="register"> </form> Following code will validate the name and password. The name can’t be empty and password can’t be less than 6 characters long.
  • 23. 23 JavaScript Error and Exceptional Handling  An exception signifies the presence of an abnormal condition which requires special operable techniques. In programming terms, an exception is the anomalous code that breaks the normal flow of the code. Such exceptions require specialized programming constructs for its execution.  In programming, exception handling is a process or method used for handling the abnormal statements in the code and executing them.  It also enables to handle the flow control of the code/program.  For handling the code, various handlers are used that process the exception and execute the code.  For example, the Division of a non-zero value with zero will result into infinity always, and it is an exception. Thus, with the help of exception handling, it can be executed and handled.
  • 24. 24 JavaScript Error and Exceptional Handling While coding, there can be three types of errors in the code: Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language, a syntax error may appear. It is also known as Parsing Error. When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads gets executed assuming nothing in them depends on the code containing the error. Runtime Error: When an error occurs during the execution of the program, such an error is known as Runtime error. The codes which create runtime errors are known as Exceptions. Thus, exception handlers are used for handling runtime errors. Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution. Logical Error: An error which occurs when there is any logical mistake in the program that may not produce the desired output, and may terminate abnormally. Such an error is known as Logical error.
  • 25. 25 JavaScript Error and Exceptional Handling Contd… There are following statements that handle if any exception occurs: 1. throw statements 2. try…catch statements 3. try…catch…finally statement try{} statement: Here, the code which needs possible error testing is kept within the try block. In case any error occur, it passes to the catch{} block for taking suitable actions and handle the error. Otherwise, it executes the code written within. catch{} statement: This block handles the error of the code by executing the set of statements written within the block. This block contains either the user-defined exception handler or the built-in handler. This block executes only when any error-prone code needs to be handled in the try block. Otherwise, the catch block is skipped. The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.
  • 26. 26 Example of throw statement <html> <head> <script type = "text/javascript"> function myFunc() { var a = 100; var b = 0; try { if ( b == 0 ) { throw( "Divide by zero error." ); } else { var c = a / b; } } catch ( e ) { alert("Error: " + e ); } } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "myFunc();" /> </form> </body> </html>
  • 27. 27 Example of try-catch statement <html> <head> <script type = "text/javascript"> function myFunc() { var a = 100; try { alert("Value of variable a is : " + a ); } catch ( e ) { alert("Error: " + e.description ); } } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "myFunc();" /> </form> </body> </html>
  • 28. 28 Example of try…catch…finally statement <html> <head> <script type = "text/javascript"> function myFunc() { var a = 100; try { alert("Value of variable a is : " + a ); } catch ( e ) { alert("Error: " + e.description ); } finally { alert("Finally block will always execute!" ); } } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "myFunc();" /> </form> </body> </html>