• No results found

Unit-III Chapter-2 Objects in Javascript

N/A
N/A
Protected

Academic year: 2020

Share "Unit-III Chapter-2 Objects in Javascript"

Copied!
18
0
0

Loading.... (view fulltext now)

Full text

(1)

UNIT-III

Chapter-II: Objects in JavaScript

Data and objects in JavaScript, regular expressions, exception handling

JavaScript Objects

A javascript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects.

Creating Objects in JavaScript

There are mainly 2 ways to create objects. 1. By object literal

2. By creating instance of Object directly (using new keyword)

JavaScript Object by object literal

The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2...propertyN:valueN} As you can see, property and value is separated by : (colon).

Example:

<html>

<body> <script>

emp={id:102,name:"Shyam Kumar",salary:40000} document.write(emp.id+" "+emp.name+" "+emp.salary); </script>

</body> </html>

(2)

By creating instance of Object

The syntax of creating object directly is given below: var objectname=new Object();

Here, new keyword is used to create object.

Example:

<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: 101 Ravi Malik 50000

******************************************************************************

Built-in Objects in Javascript

Javascript provides a number of Built-in objects. They are as follows.

 Document object

 Window object

 Form object

 Browser object

 Date object

Document Object

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.

It is the object of window. So window.document Is same as

(3)

Properties of document object

• bgColor Used to change the background color of a web page. • fgColor Used to change the foreground color of a web page. • lastModfied It returns the date and time of last modified document. • LinksIt returns all the hyperlinks used in the web page as an array. • Title  It returns the title of web page.

Javascript program to demonstrate document object properties

<html>

<head>

<script language="javascript"> document.write("<font size=50px>");

document.bgColor="green"; document.fgColor="blue";

document.write("Hello World 123"); var x=document.lastModified;

document.writeln("The document modified at:" + x); document.write("</font>");

</script> </head>

</html>

Output:

Methods of document object

We can access and change the contents of document by its methods. The important methods of document object 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.

(4)

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.

Window Object

The window object represents a window in browser. An object of window is created automatically by the browser.

Window is the object of browser; it is not the object of javascript. The javascript objects are string, array, date etc. It is used to display the popup dialog box such as alert dialog box, confirm dialog box, input dialog box etc.

Methods of window object

Method Description

alert() Displays the alert box containing message with ok button.

confirm() Displays the confirm dialog box containing message with ok and cancel button. prompt() Displays a dialog box to get input from the user.

open() Opens the new window. close() Closes the current window.

setTimeout() Performs action after specified time like calling function, evaluating expressions etc.

clearTimeout( )

Remove a timeout that was set using the setTimeout function.

Javascript program to demonstrate open() method

<html>

<body>

<p>Click the button to open a new browser window.</p> <button onclick="myFunction()">Open</button>

<script>

function myFunction() {

window.open("http://www.bvrice.ac.in"); }

</script> </body>

(5)

Output:

Form Object

The JavaScript Form Object is a property of the document object. This corresponds to an HTML input form constructed with the FORM tag. A form can be submitted by calling the JavaScript submit method or clicking the form submit button.

Form Object Properties

 action - This specifies the URL and CGI script file name the form is to be submitted to. It allows reading or changing the ACTION attribute of the HTML FORM tag.

 method - This is a read or write string. It has the value "GET" or "POST".  name - The form name. Corresponds to the FORM Name attribute.

Form Object Methods

 reset() - Used to reset the form elements to their default values.

 submit() - Submits the form as though the submit button were pressed by the user.

Javascript program to demonstrate reset() method

<html>

<body>

<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>

<form id="myForm">

First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br><br>

(6)

</form> <script>

function myFunction() {

document.getElementById("myForm").reset(); }

</script> </body>

</html>

Output:

Browser or Navigator Object

• The JavaScript navigator object is used for browser detection. It can be used to get browser information such as appName, appCodeName, userAgent etc.

• The navigator object is the window property, so it can be accessed by: window.navigator

OR

navigator

Property of JavaScript navigator object

There are many properties of navigator object that returns information of the browser.

No. Property Description

1 appName returns the name 2 appVersion returns the version 3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise false 5 userAgent returns the user agent

6 language returns the language. It is supported in Netscape and Firefox only. 7 platform returns the platform e.g. Win32.

(7)

Methods of JavaScript navigator object

The methods of navigator object are given below.

No .

Method Description

1 javaEnabled() checks if java is enabled.

2 taintEnabled() checks if taint is enabled. It is deprecated since JavaScript 1.2.

Date Object

The Date object is a built-in object in JavaScript that stores the date and time. It provides a number of built-in methods for formatting and managing that data.

The following are the ways to create a date object in JavaScript:

new Date()

For example today = new Date()

new Date(milliseconds)

For example inauguration_day = new Date("August 15, 1997 10:05:00")

new Date(dateString)

For example inauguration_day = new Date(97,8,15)

new Date(year, month, day, hours, minutes, seconds, milliseconds).

For example inauguration_day = new Date(97,8,15,10,05,0)

Javascript Date Objects Methods

Name Description

getDate Use to get the day of the month of a given date according to local time. getDay Use to get the day of the week of a given date according to local time. getFullYear Use to get the year of a given date according to local time.

getMonth Use to get the month of a given date according to local time

getTime Use to get the milliseconds of a given date according to local time.

(8)

getMilliseconds Use to get the milliseconds from the current time according to local time. getMinutes Use to get the minutes from the current time according to local time. getSeconds Use to get the seconds from the current time according to local time.

Javascript program to demonstrate Date object methods

<html>

<head>

<title> Example on Date Object </title> </head>

<body>

<center><h1>Example on Date Object Methods</h1></center> <hr>

<script language="javascript"> var d=new Date();

document.writeln("The date is:" + d + "<br>");

document.writeln("getDate():" + d.getDate() + "<br>"); document.writeln("getDay():" + d.getDay() + "<br>"); document.writeln("getMonth():" + d.getMonth() + "<br>"); document.writeln("getFullYear():" + d.getFullYear() + "<br>");

document.writeln("getTime():" + d.getTime() + "<br>"); document.writeln("getHours():" + d.getHours() + "<br>"); document.writeln("getMinutes():" + d.getMinutes() + "<br>"); document.writeln("getSeconds():" + d.getSeconds() + "<br>"); document.writeln("getMilliseconds():" + d.getMilliseconds());

</script> </body>

</html>

Output:

(9)

Dialog Boxes in Javascript

Dialog boxes are methods of the window object. However, we can invoke them without explicit reference to window. They may be used depending on the type (alert, confirm, prompt) to display an information or to get input from the user.

Three Types of Dialog Boxes Available  Alert dialog box

 Confirmation dialog box  Prompt dialog box

Alert Dialog Box

It is used to show a message in the dialog box, and there is an OK button. It is mostly used to prompt message if user missed input value or invalid data in given form or text. It is supported by all major browsers.

Javascript Alert Dialog Box Example <html>

<head>

<title>Javascript Alert Dialog Box Example</title> <script>

function f1() {

alert('Hello BVRICE Students!'); }

</script> </head>

<body>

<form >

<input type="button" value="Say Hello" onClick="f1()"> </form>

</body> </html>

(10)

Confirm Dialog Box

It is used to show a message box with "Ok" and "Cancel" button. It is mostly used to take user confirmation on any option.

Confirm displays a dialog box with two buttons: OK and Cancel. If the user clicks on OK the window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false.

Javascript Confirm Dialog Box Example <html>

<body>

<p>Click the button to display a confirm box.</p> <button onclick="myFunction()">Try it</button> <script>

function myFunction() {

var x=confirm("Press a button!"); if(x==true)

{

window.alert("You pressed on OK"); }

else {

window.alert("You pressed on Cancel"); }

} </script>

</body> </html>

(11)

Prompt Dialog Box

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt()returns null.

Javascript Prompt Dialog Box Example

<html> <head>

<script type="text/javascript"> function getValue()

{

var retVal = prompt("Enter your name : ", "your name here"); document.write("You have entered : " + retVal);

} </script> </head> <body>

<p>Click the following button to see the result: </p> <form>

<input type="button" value="Click Me" onclick="getValue();" /> </form>

</body> </html>

(12)

******************************************************************************

Regular Expressions

Regular expressions are a powerful way of searching and replacing inside a string. In JavaScript regular expressions are implemented using objects of a built-in RegExp class and integrated with strings.

A regular expression (also “regexp”, or just “reg”) consists of a pattern and optional flags.

There are two syntaxes to create a regular expression object.

The long syntax:

regexp = new RegExp("pattern", "flags");

…And the short one, using slashes "/":

regexp = /pattern/; // no flags

regexp = /pattern/gmi; // with flags g,m and i (to be covered soon)

Slashes "/" tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings.

Flags

Regular expressions may have flags that affect the search. There are mainly 3 flags in JavaScript:

(13)

With this flag the search is case-insensitive: no difference between A and a (see the example below).

G:

With this flag the search looks for all matches, without it – only the first one (we’ll see uses in the next chapter).

M:

Multiline mode (covered in the chapter Article "regexp-multiline" not found).

Meta characters

• A meta character is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.

• For instance, you can search for a large sum of money using the '\d' meta character: /([\d] +)000/, Here \d will search for any string of numerical character.

The following table lists a set of meta characters which can be used in Regular Expressions.

Sr.N o

Character & Description

1 . a single character

2 \s a whitespace character (space, tab, newline) 3 \S non-whitespace character

4 \d a digit (0-9) 5 \D a non-digit

6 \w a word character (a-z, A-Z, 0-9, _) 7 \W a non-word character

8 [\b] a literal backspace (special case).

9 [aeiou] matches a single character in the given set 10 [^aeiou] matches a single character outside the

given set

(14)

Example on exec() and test() methods

<html> <body> <script>

var str="A lot about Javascript at javascript book"; //look for "javascript"

var patt=/javascript/g; var result=patt.exec(str);

document.write("Using exec() method Returned value: " + result); patt=/javascript/g;

result=patt.test(str);

document.write("<br>Using test() method Returned value: " + result); </script>

</body> </html>

(15)

Using exec() method Returned value: javascript Using test() method Returned value: true

Example on match(), serach(), replace() and split() methods

<html> <body> <script>

//using match()

var str="The rain in SPAIN stays mainly in the plain"; var n=str.match(/ain/gi);

document.write("using match()" + n); //using search()

var result = str.search( /AIN/gi );

document.write("<br>using search():" + result); //using replace()

var n=str.replace(/ain/gi,"ead");

document.write("<br>using replace():" + n); //using split()

var n=str.split(" ");

document.write("<br>Using split():" + n); </script>

</body> </html>

Output:

using match()ain,AIN,ain,ain using search():5

using replace():The read in SPead stays meadly in the plead Using split():The,rain,in,SPAIN,stays,mainly,in,the,plain

******************************************************************************

Exception Handling in Javascript

Runtime error handling is vitally important in all programs. An exception is an error which we have designed our program to handle with.

(16)

JavaScript try and catch:

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The JavaScript statements try and catch come in pairs. The general format is

try {

//Run some code here }

catch(err) {

//Handle errors here }

Example:

The following program consist typographical error in the try block. The catch block catches the error in the try block, and executes code to handle it.

<html>

<head>

<script>

var txt="";

function display(){ try{

adddlert("Welcome to BVRICE!"); var n=promptt("Enter value:"); }

catch(e){

txt="There was an error on this page.\n\n"; txt+="Error description: " + e.message + "\n\n"; txt+="Click OK to continue.\n\n";

alert(txt); }

} </script>

</head> <body>

<input type="button" value="View message" onclick="display()" /> </body>

</html>

(17)

The Throw Statement:

When an error occurs, when something goes wrong, the JavaScript engine will normally stop, and generate an error message. The technical term for this is: JavaScript will throw an error.

The throw statement allows us to create a custom error. If we use the throw statement together with try and catch, we can control program flow and generate custom error messages. The general format is

throw exception

The exception can be a JavaScript String, a Number, a Boolean or an Object.

Example:

This example examines the value of an input variable. If the value is wrong, an exception (error) is thrown. The error is caught by the catch statement and a custom error message is displayed.

<html>

<head>

<title>Example on Exception Handling</title> </head>

<body bgcolor="#CDF357">

<h3>EXAMPLE ON EXCEPTION HANDLING</h3> <hr>

<p><b>Please input a number between 5 and 10</b></p> <form>

<input id="demo" type="text">

<button type="button" onclick="myFunction()">Test Input</button> </form>

<b><p id="message"></p></b> <script language="javascript">

function myFunction() {

(18)

x = document.getElementById("demo").value; try

{

if(x == "") throw "empty";

if(isNaN(x)) throw "not a number"; x = parseInt(x);

if(x < 5) throw "too low"; if(x > 10) throw "too high"; if(x>=5 && x<=10)

{

alert("The number is:" + x); }

}

catch(err) {

document.getElementById("message").innerHTML ="Input is " + err;

} }

</script> </body>

</html>

Output:

******************************************************************************

Important Questions

1. Define object and explain how to create and use them in javascript with example.

2. Explain about different Built-in Objects in Javascript. 3. Write about document object in Javascript.

4. Explain window object in javascript.

5. Write about the dialog boxes used in javascript.

6. Explain Form object methods and properties in javascript. 7. Write a javascript program using Date object.

8. Define Regular Expression and explain with examples.

9. Define Exception and explain about try and catch blocks in javascript. 10. Explain how to throw the user defined exceptions in javascript with

(19)

References

Related documents

and globally, remain on the negative side of the digital divide. This age-based digital divide is of concern because the internet enables users to expand their

The correlations between the Mental Rotation Task (MRT) and the Image Control and Recognition Task (ICRT) indices were non-significant, however the median split

The Department of Life Sciences was formed on 1 August 2007 by the linking of the Divisions of Biology, Cell and Molecular Biology, and Molecular Biosciences. The statistics for

Using Biot-Savart law it is easy to calculate the magnetic field at any point in the space produced by such current distribution, then integrating the xy field component on

In large horsepower (hp) applications (greater than 100 hp), gear systems tend to be designed for greater efficiency because of the costs, heat, and noise problems that result

Teleport questions with parents is it phrase is important to do they are better understand grammar quiz and relative clause and organize your team has a quizizz.. Nailed it to use

Hyphae localization in tissue surrounding the wound or inoculation sites indicates that Pch colonizes all cell types, such as vascular tissues, paratracheal parenchyma cells,

The goal of this thesis is to develop a convolutional neural network (CNN) to perform vehicle detection and classification on vehicle and background images.. More precisely