Web Technology Unit 4
Web Technology Unit 4
Objects in JavaScript: Data and objects in JavaScript, regular expressions, exception handling
DHTML with JavaScript: Data validation, opening a new window, messages and confirmations
In today’s world, almost all the modern programming language are the outcome of object oriented
concepts. An object is nothing but an entity(an existing thing) which can be distinguished from other entity.
JavaScript are not purely object oriented language rather than it can be referred as object based programming
language.
Example:- Output:-
<html>
<head>
<title>Using Objects in JavaScript</title>
<script type="text/javascript">
function person(name,age)
{
this.name = name;
this.age = age;
}
</script>
</head>
<body>
<script type="text/javascript">
this:- To differentiate global values and which are part of an object but may be accessed to same name,
javascript use ‘this’.
.(dot):- When referring to a property on an object, whether a method or a variable, a dot is placed between the
object name and property.
Built-in-object in JavaScript:-
JavaScript has many built-in objects which has the capability of performing many task, hence sometimes
javascript referred as an object based programming language. Every object consist of attributes (variables) and
behavior (methods). For example, if there is an object then it have size, color, volume are its attributes and
computing area of shape expanding the size of shape, or coloring the shape could be the associated methods of
that object.
Some of the objects in JavaScript are listed below
1. Date Object
2. Number Object
3. Boolean Object
4. String Object
5. Mathematical Object and
6. Regular Expression Object
1. Date Object:-
This object is used for obtaining the date and time. This date and time values is based on
Computer’s local time (System’s time) or it can be based on GMT (Greenwich Mean Time). Now a days this
GMT is also known as UTC i.e. Universal Coordinated Time. This is basically a world time standard.
Method Description
getUCTHours( ) Returns the hour value ranging from o to 23 based on UCT time zone
Example:- Output:-
<html>
<head>
<title>Date Object</title>
</head>
<body>
<script type="text/javascript">
var today = new Date();
document.write("Date Object: "+today+"<br>");
document.write("Date: "+today.getDate()+"<br>");
document.write("Month: "+today.getMonth()+"<br>");
document.write("Year: "+today.getFullYear()+"<br>");
document.write("Hours: "+today.getHours()+"<br>");
document.write("Minutes: "+today.getMinutes()+"<br>");
document.write("Seconds: "+today.getSeconds()+"<br>");
document.write("Milliseconds: "+today.getMilliseconds());
</script>
</body>
</html>
Methods Description
MAX_VALUE( ) Returns Largest Number
MIN_VALUE( ) Returns Smallest Number
NaN Not a Number
POSITIVE_INFINITY Returns Positive Infinity
NEGATIVE_INFINITY Returns Negative Infinity
Example:- Output:-
<html>
<head>
<title>Number Object</title>
</head>
<body>
<script type="text/javascript">
document.write("Maximum Value: "+Number.MAX_VALUE+"<br>");
document.write("Minimum Value: "+Number.MIN_VALUE+"<br>");
document.write("Not a Number: "+Number.NaN+"<br>");
document.write("Positive Infinity: "+Number.POSITIVE_INFINITY+"<br>");
document.write("Negative Infinity: "+Number.NEGATIVE_INFINITY);
</script>
</body>
</html>
3. Boolean Objects:-
Syntax:-
var val = new Boolean(value);
Example:- Output:-
<html>
<head>
<title>Boolean Object</title>
</head>
<body>
<script type = "text/javascript">
var a = new Boolean(true);
document.write("Boolean value for A is : "+a +"<br>");
document.write("Boolean value: "+(10>20));
</script>
</body>
</html>
Syntax:-
Modifier Description
g Performs a global match(find all matches rather that stopping after the
first match).
Modifier Description
\d Match a digit
\D Match anything except a digit
Example:- Output:-
<html>
<head>
<title>Regular Expression</title>
</head>
<body>
<script type="text/javascript">
var r = txt.search(re);
document.write("Position:"+r+"<br>");
var m = txt.match(re);
document.write("Matched Letter:"+m+"<br>");
</script>
</body>
</html>
3. Exception Handling:-
In earlier versions of JavaScript, the exceptions handling was no so efficient and programmers found it difficult to
use. Later versions of JavaScript resolved this difficulty with exception handling features like try…catch handlers,
which presented a more convenient solution for programmers of JavaScript.
It is very important that the errors thrown must be catched or trapped, so that they can be handled
more efficiently and conveniently and the users can move better through the web page.
In the try block, the code contains a block of code that is to be tested for errors. The catch block contains
the code that is to be executed if an error occurs.
Syntax:-
try
{
------------
------------ //block of code which is to tested for errors
------------
}
catch( err )
{
------------
------------ //block of code which is to executed if an error occurs
------------
}
When an error occurs in the try block, then the control is immediately transferred to the catch block
with the error information also passed to the catch block. Thus, the try…catch block helps to handle errors
without aborting the program and therefore proves user-friendly.
Example:- Output:-
<html>
<head>
<title>try...catch</title>
</head>
<body> Here, a is not defined. When try block gives error
<script type="text/javascript"> and transferred to catch block where error
try
message is printed.
{
document.write(a);
}
catch(err)
{
document.write(err.message);
}
</script>
</body>
</html>
throw in JavaScript:
There is another statement called throw, available in JavaScript that can be used along with try…catch
statements to throw exceptions and thereby helps in generating.
Syntax:- throw "exception"; Here, exception can be any variable of type integer (or) boolean (or) string.
Example:- Output:-
<html>
<head>
<title>using throw</title>
</head>
<body>
<script type="text/javascript">
try
{
var a=10;
if(a!=20)
throw "place error";
else
document.write(a);
}
catch(err)
{
if(err=="place error")
document.write("Variable is not equal to 20");
}
</script>
</body>
</html>
try…catch..finally statement:-
JavaScript has a finally statement that can be used as an optional construct along with try…catch
statements. When the finally statement is placed in a try…catch construct, it always runs following the try…catch
structure.
Syntax:-
try
{
------------
------------ //block of code which is to tested for errors
}
catch( err )
{
------------
------------ //block of code which is to executed if an error occurs
}
finally
{
------------
------------ //This is optio al a d ru s after tr … at h stru ture has ru
}
Example:- Output:-
<html>
<head>
<title>try...catch</title>
</head>
<body>
<script type="text/javascript">
try
{
document.write(a);
}
catch(err)
{
document.write(err.message);
}
finally
{
do u e t.write "< r>"+"This is fi all lo k… o pulsor e e utio " ;
}
</script>
</body>
</html>
Nested try…catch statement:-
It is also possible to have nested try…catch statement (or) one try…catch statement placed inside another.
Syntax:-
try
{
------------ //block of code
try
{
------------ //block of code
}
catch( err )
{
------------ //block of code
}
--------- //block of code
}
catch( err )
{
------------ //block of code
}
finally
{
------------ //This is optional and runs after try…catch structure has run
}
4. Data Validation:-
Data Validation is an essential aspect of any web application that accepts data from the user after all
you must ensure the data is formatted as expected before working with it. The web application it would be better
to validate data that is entered into your forms at the client.
In general, when the use enters data, the script performs the validation and an error being returned
to the user, but it is a delay process. Most of the error occurs because user entering wrong data like entering a
space or character other than a digit or a letter into a user name.
One of the way to overcome this problem is to use of regular expression for data validation.
Validation is the simple process of ensuring that the data might be correct for a particular application. Data
validation is the process of ensuring that user submits only.
Every Javascript string variable includes regular expression support via three methods, search( ),
search( ):- This method is used to search for a match between a regular expression and the specified string. If
match is found, the search method returns the index of the regular expression within the string, If not match is
found, -1 is returned.
match( ):- This method is used to match a regular expression against a string. If one or more matches are made,
an array is returned that contains all of the matches. Each entry in the array is a copy of a string that contains a
match. If no match is made, a null is returned.
replace( ):- The replace( ) method is used to match a regular expression against a string and replace any match
with a new substring. The first parameter is the regular expression, and the second parameter is the replace string.
Pattern-matching characters can be grouped into various categories. By understanding these characters,
first we need to understand the language needed to create a regular expression pattern. The categories are:
Position Matching:- You wish to match a substring that occurs at a specific location within the larger string.
For example, a substring that occurs at the very beginning or end of string.
Special literal character matching:- All alphabetic and numeric characters by default match themselves literally
newline in regular expressions, a special syntax is needed. Specifically, a backslash( \ ) followed by a designated
character.
For example, to match a newline, the syntax “\n” is used, while “\r” matches a carriage return.
Character Classes matching:- Individual characters can be combined into character classes to form more
complex matches, by placing them in designated containers such as a square bracket.
Example:-
<html>
<head>
<title>Data Validataion</title>
</head>
<body>
<form>
Enter Name : <input type="text"> <br><br>
<input type="submit" onclick="validate()">
</form>
<script type="text/javascript">
function validate()
{
var name = document.forms[0].elements[0].value;
var re = new RegExp("[0-9]");
if(name.match(re))
alert("Invalid Name"); In the above example, in text box the user
else enter name with any number, it alert
alert("Your name is submitted"); message as Invalid Name. If user type
} alphabets only, it alert message as Your
</script> name is submitted. Here data validation is
</body> occurred by using regular expression.
</html>
5. Opening a New Window:-
The majority of the JavaScript coding that will be based around the use of windows, The
typical piece of Microsoft Windows software uses the multiple document interface (MDI) structure. The
application has a single frame and when new windows are opened they appear inside that frame. The application
frame is said to be the parent of all the internal frames.
Syntax:-
Parameter Description
1.url Specifies the URL of the page to open. If no URL is specified, a new window with blank
is opened
2. name Specifies the target attribute of the name of the window. The following values are
supported
4. replace Optional. Specifies whether the URL creates a new entry or replaces the current entry in
the history list. The following values are supported:
Example:-
<html>
<head>
<title>Opening a New Window</title>
</head>
<body>
<p>If you click submit button, a new window will open</p>
<form>
<input type="submit" onclick="newwin()">
</form>
<script>
function newwin()
{
var var= window.open("https://svuniversity.edu.in","svu","height=500,width=500,status=yes,menubar=yes ");
}
</script>
</body>
</html>
JavaScript provides three built-in window types. These are useful when you need
information from visitors to your site. For instance, you may need them to click a confirmation button before
submitting information to you database. The three built-in windows are
1. Alert window
2. Confirm window and
3. Prompt window
1. Alert Window:- The alert command is very useful to display the text string and an OK button. This may be
used as a warning or to provide messages as visitors leaves your site.
Example:- Output:-
<html>
<head>
<title>Alert Window</title>
</head>
<body>
<script type="text/javascript">
alert("A Warning");
</script>
</body>
</html>
2. Confirm Window:-
The Confirm command is used to display confirmation messages, such as submitting
form data, or possibly as the user tries to follow a link that leaves you site for another. The confirmation
window have two buttons OK and Cancel. Selecting Cancel will abort any pending action, while OK will let
the action proceed.
Example:- Output:-
<html>
<head>
<title>Confirm Window</title>
</head>
<body>
<script type="text/javascript">
confirm("Are you Sure?");
</script>
</body>
</html>
3. Prompt Window:-
The prompt window is used to display a text box in which the user can enter something.
Hence it has two buttons OK and Cancel.
Example:- Output:-
<html>
<head>
<title>Prompt Window</title>
</head>
<body>
<script type="text/javascript">
prompt("Enter Your Name:");
</script>
</body>
</html>