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>
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>