[go: up one dir, main page]

0% found this document useful (0 votes)
102 views14 pages

Web Technology Unit 4

Web Technology Material

Uploaded by

sayeedabegum2010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views14 pages

Web Technology Unit 4

Web Technology Material

Uploaded by

sayeedabegum2010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT – IV

Objects in JavaScript: Data and objects in JavaScript, regular expressions, exception handling

DHTML with JavaScript: Data validation, opening a new window, messages and confirmations

1. Data and objects in JavaScript:-

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.

Objects in-terms of programming concept refers to a constructor by holding data on functions.

The new operator:-


The new operator is used to create an instance of an object. To create an object, the new
operator is followed by the constructor method.

The object constructor:-


A constructor is a function that creates and initialize an object. JavaScript provides a
special constructor function called object( ) to built an object.

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

var firstperson = new person("krishna",40)


document.write("Name:"+firstperson.name+"<br>");
document.write("Age:"+firstperson.age);
</script>
</body>
</html>

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.

Following are the commonly used methods of Date object:

Method Description

getTime( ) Returns the number of milliseconds, since 1st Jan 1970

setTime( ) Set the number of milliseconds, since 1st Jan 1970

getDate( ) Returns the day of the month as an integer from 1 to 31

setDate( ) Sets the day of the moths as an integer from 1 to 31

getMonth( ) Returns the month of the year in number format(jan-0…dec-11)

setMonth( ) Sets the month of the year in number format

getFullYear( ) Returns the current year

getHours( ) Returns the hours as an integer from 0 to 23

setHours( ) Set he hours as an integer from 0 to 23


getMinutes( ) Return current minutes(in the system time)

getSeconds( ) Returns current seconds (in the system time)

getMilliseconds( ) Returns current milliseconds (in the system time)

getUCTDate( ) Returns the current date obtained from UCT

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>

2. Number Object:- Various methods of number objects are listed below

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

JavaScript booleans can have one of two values: true or false.

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>

4. String Object:- Refer in 3rd unit ( String Manipulations )


5. Mathematical Object:- Refer in 3rd unit ( Mathematical Functions )
6. Regular Expression:- Refer in 4th unit
2. Regular Expression:-

A Regular Expression is an object that describes a pattern of characters. Regular


Expressions are used to perform pattern-matching and “search – and – replace” functions on text.

Syntax:-

var txt = new RegExp(pattern,modifiers);

or more simply, var txt = /pattern/modifiers;

 Pattern specifies the pattern of an expression.


 Modifiers specify if a search should be global, case-sensitive etc,.

Modifiers:- Modifiers are used to perform case-insensitive and global searches:

Modifier Description

i Perform case-insensitive matching

g Performs a global match(find all matches rather that stopping after the
first match).

m Perform multiline matching

Brackets:- Brackets are used to find a range of characters:

Modifier Description

[abc] Find any character between the brackets

[^abc] Find any character not between the brackets

[0-9] Find any digit from 0 to 9

[A-Z] Find any character from uppercase A to uppercase Z

[a-z] Find any character from lowercase a to lowercase z

[adgk] Find any character in the give set

(red | blue | green) Find any of the alternative specified.

\d Match a digit
\D Match anything except a digit

\w Match any alpha numeric character or underscore

\W Match anything except alphanumeric character or underscore

\s Match a whitespace character

\S Match except whitespace character

Example:- Output:-

<html>
<head>
<title>Regular Expression</title>
</head>
<body>
<script type="text/javascript">

var txt="Hello JavaScript";


var re=new RegExp("[JhS]");
document.write("Text:"+txt+"<br>");

var r = txt.search(re);
document.write("Position:"+r+"<br>");

var m = txt.match(re);
document.write("Matched Letter:"+m+"<br>");

var result = txt.replace("Hello","Welcome");


document.write("Replaced:"+result);

</script>
</body>
</html>
3. Exception Handling:-

It is impossible for a programmer to write a program without errors. Programming languages


include exceptions, or errors, that can be tracked and controlled. Exception handling is a very important concept
in programming technology.

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.

Catching errors in 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.

There are mainly two way of catching errors in JavaScript.

 Using try…catch statement and


 Using onerror event

Using try…catch statement:-

The try…catch statement has two blocks in it:

1. try block and


2. catch block

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( ),

match( ) and replace( )

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.

var a = “Hello JavaScript”;

var result = a.replace(“Hello”,”Welcome”);

Now, the result will be Welcome JavaScript

Categories of Pattern Matching Characters:-

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.

For example, / [abc] / matches “a”, “b”, “c”

/ [a-zA-Z0-9] / matches all alphanumeric characters

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

window.open(URL, name, specs, replace);

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

_blank – URL is loaded into a new window.(by default).

_parent – URL is loaded into the parent frame.

_self – URL replaces the current page.

_top – URL replace any framesets that may be loaded.

name – The name of the window.


3.specs A comma-separated list of items, no whitespaces. The following values are supported:

directories = yes | no | 1 | 0 - whether or not to add directory buttons. Default is yes.

fullscreen = yes | no | 1 | 0 - whether or not to display the browser in full-screen mode.


Default is no.
Height = pixels - The height of the window. Minimum value is 100.

Width = pixels - The width of the window. Minimum value is 100.

location = yes | no | 1 | 0 - whether or not to display the address field.

menubar = yes | no | 1 | 0 - whether or not to display the menu bar.

resizable = yes | no | 1 | 0 - whether or not the window is resizable.

status = yes | no | 1 | 0 - whether or not to add a status bar.

titlebar = yes | no | 1 | 0 - whether or not to display the title bar.

toolbar = yes | no | 1 | 0 - whether or not to display the browser toolbar.

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:

true – URL replaces the current document in the history list.

false – URL creates a new entry in the history list.


Rules:-

1. There cannot be line breaks or spaces in the parameter string.


2. Don’t have any space between the parameters.
3. Don’t forget the commas between parameters.

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>

6. Messages and Confirmations:-

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>

You might also like