Professional Documents
Culture Documents
S araswati
MULTIMEDIA & WEB TECHNOLOGY
Supplementary Reading Material
for
UNIT 3: WEB SCRIPTING
[FOR CLASS XI]
By
Gagan Sahoo
M.C.A.
Date: 27-04-2015
SYLLABUS
UNIT 3: WEB SCRIPTING
JavaScript: Introduction to client side scripting using Java Script, Using Java Script in HTML page
with <SCRIPT> tag, external Java Script;
JavaScript Variables: Declaring variable, assigning values to variables, Java Script literals; Data
types in Java Script String, Number, Boolean, Object, Function, Null; Type casting in Java Script;
JavaScript Operators:
Arithmetic Operators: +, -, *, /, % , ++, - - ;
Assignment Operators : =, +=, - =, *=, /=, %= ;
Comparison Operators: <, >, <=, >=, !=, == ;
Logical Operators: &&, ||, !;
String Operator: + (for concatenation);
Bitwise Operators : &, |, ~, ^, <<, >> ;
Unary + operator; typeof operator;
Conditional operator : (?:)
JavaScript Popup Boxes: Alert, Confirm and Prompt box
Comments in JavaScript: Single line and multiline;
Control Structures in JavaScript:
Conditional statements: If, Else, Else If.., switch case; break and default statement;
Loops: For, While, Do While loops; continue statement;
JavaScript Functions: Define a function, execute a function, return statement, function using
arguments, Scope of variables;
Objects in JavaScript: Window object, document object, location object, form object, working with
control objects(Button, reset and submit objects, checkbox objects, and radio objects, select objects,
password, text, textarea object), date object, Creating Dynamic Interface with HTML form controls
and JavaScript;
Array object in Java Script: length property, join(), sort(), for in loop;
Responding to events: onLoad, onUnload, onFocus, onBlur, onChange, onMouseOver, Timing
Events setTimeout( ) and clearTimeout();
CONTENTS
Chapter1 Introduction to JavaScript ............................................................................ 3.13.38
Chapter2 JavaScript Functions .................................................................................. 3.393.64
Chapter3 Branching in JavaScript .............................................................................. 3.653.88
Chapter4 Looping in JavaScript .............................................................................. 3.893.138
Chapter5 Objects in JavaScript .............................................................................. 3.1393.154
Chapter6 Working with Control Objects ................................................................. 3.1553.198
(2)
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.1
U N I T 3
Introduction to JavaScript
1
1.1 INTRODUCTION
The World Wide Web (WWW) began as a text-only mediumthe first browsers did not even support images
within web pages. Todays websites can include a lot of features: graphics, sounds, animation, video, and
occasionally useful content. Web scripting languages also, known as client-side scripting languages, such as
JavaScript, are one of the easiest ways to add dynamic state to a Web page and to interact with users in new
ways. Client-side scripts can control browser actions associated with a Web page. Scripts are programs written
in a simple and easy-to-use language to specify control of other programs. Client-side scripts are almost always
written in the JavaScript language to control browser actions.
Tasks performed with client-side scripts include:
x Asking the browser to display information
x Making the Web page different depending on the browser and browser features
x Monitoring user events and specifying reactions
x Generating HTML code for parts of the page
x Modifying a page in response to events
x Checking correctness of user input
x Replacing and updating parts of a page
x Changing the style and position of displayed elements dynamically
Client-side scripting can make Web pages more dynamic and more responsive.
Scripting languages are becoming more popular due to the emergence of web-based applications. Specialised
scripting languages include:
Perl (Practical Extraction and Report Language). This is a popular string processing language for
writing small scripts for system administrators and website maintainers. Much web development is
now done using Perl.
Hypertalk is another example. It is the underlying scripting language of HyperCard.
Lingo is the scripting language of Macromedia Director, an authoring system for developing high-
performance multimedia content and applications for CDs, DVDs and the Internet.
AppleScript, a scripting language for the Macintosh allows the user to send commands to the
operating system, for example open applications, to carry out complex data operations.
JavaScript, perhaps the most publicised and well-known scripting language was initially developed
3.1
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.2 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
by Netscape as LiveScript to allow more functionality and enhancement to web page authoring that
raw HTML could not accommodate. A standard version of JavaScript was later developed to work in
both Netscape and Microsofts Internet Explorer, thus making the language to a large extent, universal.
This means that JavaScript code can run on any platform that has a JavaScript interpreter.
VBScript, a cut-down version of Visual Basic, used to enhance the features of web pages in Internet
Explorer.
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely used open source general-
purpose scripting language that is especially suited for web development and can be embedded into
HTML.
Major advantages of scripting languages include:
x easy to learn and use.
x minimum programming knowledge or experience required.
x allow complex tasks to be performed in relatively few steps.
x allow simple creation and editing in a variety of text editors.
x allow the addition of dynamic and interactive activities to web pages.
x editing and running code is fast.
The major disadvantage of scripting languages is that executable code can inadvertently be downloaded
from a remote server to a web browsers machine, installed and run using the local browsers interpreter. This is
easily done by visiting dubious web sites or downloading programs without valid authenticity. The user is
probably unaware of anything devious occurring.
This is a weakness and major drawback in the formal rules defining scripting languages like JavaScript and
VBScript.
1.3 JAVASCRIPT
12345678901234567890
12345678901234567890
JavaScript (originally called LiveScript) is a widely used scripting 12345678901234567890
language originally developed by Netscape Communications 12345678901234567890
What is JavaScript?
12345678901234567890
Corporation for both client-side and server-side scripting. JavaScript 12345678901234567890
JavaScript is a cross-platform,
12345678901234567890
object-oriented scripting
is a lightweight programming language that is interpreted by the browser
engine when the web page is loaded.
12345678901234567890
12345678901234567890
language developed by
JavaScript is a widely supported language and it is available in 12345678901234567890
Netscape. JavaScript was
12345678901234567890
the following browsers: 12345678901234567890
created by
12345678901234567890
Netscape
x Netscape Navigator (beginning with version 2.0) 12345678901234567890
programmer Brendan Eich.
x Microsoft Internet Explorer (beginning with version 3.0)
x Firefox
x Safari
x Opera
x Google Chrome
Thus, most Internet users today have browsers that support JavaScript. That is why JavaScript is one of
the most popular tools in the Web developer's arsenal.
Client=Side Scripting. JavaScript code is executed/interpreted when an event is triggered. When
the code is executed, it is interpreted one line at a time. There are number of events that will trigger the
execution of a JavaScript, like clicking on a form button or the completion of a web page loading.
Server-Side Scripting. When the web server loads an .html page from the disk into the memory,
it automatically knows how to interpret the code in this document. Once the code has been interpreted,
the resulting HTML page is sent to the browser (client) making the request.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.3
It was the first web scripting language to be supported by browsers, and it is still by far the most popular.
JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents. It is a less
complex, interpreted scripting language similar to AppleScript. JavaScript is similar in some ways to Java, but
it does not require the programmer to understand or implement the complicated object-oriented syntax or worry
about programming issues like variable typing and object hierarchies. Thus, JavaScript is a programming
language that allows scripting of events, objects and actions to create Internet applications.
In fact, Java and JavaScript are so different that you can think of them with different titles depending on
your ability. It is convenient to think of creating programs of Java as programming and you can call creating
scripts in JavaScript authoring.
Here are a few of the things you can do with JavaScript:
x Display messages to the user as part of a web page, in the browsers status line, or in alert boxes.
x Validate the contents of a form and make calculations (for example, an order form can automatically
display a running total as you enter item quantities).
x Animate images or create images that change when you move the mouse over them.
x Create ad banners that interact with the user, rather than simply displaying a graphic.
x Detect the browser in use or its features and perform advanced functions only on browsers that
support them.
x Detect installed plug-ins and notify the user if a plug-in is required.
x Modify all or part of a web page without requiring the user to reload it.
x Display or interact with data retrieved from a remote server.
JavaScript is an object-oriented language and many constructs are similar to those in C++ or Java. It is
an interpreted programming language that can be embedded into an HTML web page or used in server side
scripting language.
The following are the major advantages of JavaScript:
x JavaScript is no more difficult to learn than HTML. It allows people with little or no programming
experience who are daunted by Javas complexity to create interactive and Web based applications.
x JavaScript can be used to solve common problems, such as validating forms input and can also be
used to create dramatic and visually appealing content, which would be impossible with HTML.
x JavaScript is the one of the Dynamic HTML available in both Netscape Navigator and Internet
Explorer.
x As JavaScript lives inside the HTML document, it can either exist as a complete script that is embedded
in the <head> or <body> elements or it can consist of event handlers that are written directly into the
HTML code.
JavaScript is based on an action-oriented model of the World Wide Web. Elements of a Web page, such as
a button or a checkbox may trigger actions or events. When one of these events occurs, a corresponding piece
of JavaScript code, usually a JavaScript function, is executed. That function, in turn, is composed of various
statements which perform calculations, examine or modify the contents of the Web page or perform other tasks
in order to respond in some way to that event. For example, pressing the SUBMIT button on an online order
form might invoke a JavaScript function that validates the contents of that form to ensure that the user
entered all the required information.
In general, the elements of a JavaScript program can be divided into following categories:
x StatementsStatements are the lines of code from which JavaScript programs are built.
x BlocksBlocks allow you to group statements.
x CommentsComments allow you to annotate your code with remarks.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.4 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
This explicitly declares to the browser that your script is a JavaScript (instead of VBscript, for example).
The "LANGUAGE" attribute while not essential to declare, is useful in certain cases. But the <script
language="JavaScript"> is incorrect. <script language = "JavaScript"> is deprecated as
"language" value is an identifier which has no standards. The correct syntax is:
<SCRIPT type = "text/JavaScript" SRC = "main/hello.js"
.....
.....
</SCRIPT>
This overrides the default scripting language. Here, the <SCRIPT> block that loads JavaScript code from
a filename hello.js in a directory main relative to the document.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.5
x If the SRC attribute is not given then it is expected that all the code between <SCRIPT> and </
SCRIPT> is the script source itself.
x It is recommended that source included between <SCRIPT> and </SCRIPT> be enclosed within the
HTML comment delimiters <!-- and ->.
For example,
<SCRIPT type = "text/JavaScript">
<!--
/* Our script only requires one quick statement! */
// prints words to Web document
document.write("Hello! I am Rahul and a Web programmer in Class-XI");
// end hiding -->
</SCRIPT>
From the above example, the entire script body is enclosed with HTML comment tags. These are optional
but recommended. They tell browsers that don't support JavaScript (or with JavaScript disabled) to ignore the
code in between. This prevents the code from being written out to your website users. At present, you should
structure your script according to the following rules:
x Place the comment start (<!--) on a line of its own.
x Follow it with your JavaScript code.
x Terminate the code with <!-- and -> on its own line.
The part that writes the actual text is only 1 line
document.write(Hello! I am Rahul and a Web programmer in Class-XI)
We can create external JavaScript file and embed it in many HTML pages. It provides code reusability because
single JavaScript file can be used in several HTML pages. As we know that an external JavaScript file must be
saved by .js extension. It is recommended to embed all JavaScript files into a single file. It increases the speed
of the web page. Let us create an external JavaScript file called hello.js that prints "Hello JavaScript
Programmer" in a dialog box.
function printMe() {
alert("Hello JavaScript Programmer");
}
Let us include the JavaScript file ( hello.js ) into html page. It calls the JavaScript function on button click.
<html>
<head>
<script type="text/javascript" src="hello.js"></script>
</head>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.6 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
<body>
<p>Welcome to JavaScript programming</p>
<form>
<input type="button" value="Click Me" onclick="printMe()"/>
</form>
</body>
</html>
Before you begin programming, have a look at this general information about how to incorporate JavaScript
into HTML pages. First, you should know that JavaScript is a scripting language. That is, the code is not
compiled (translated into machine language), but instead it appears as ASCII text in an HTML file. For integrating
it into the HTML code, you have three possibilities.
The first possibility is to incorporate the source code into the header of the HTML file. Here you can write code
that youll access later using one of the two other possibilities for incorporation. The source code for this
option looks like this:
<html>
<head>
<title>Title of the Page</title>
<script type="text/javascript">
<!--
Definition of Functions and Variables
//-->
</script>
...
...
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.7
Here, the tag <script language=JavaScript> introduces the JavaScript source code, the tag
</script> ends it. The codes <!-- and //--> cause source code from older browsers, ones that do not
support JavaScript, to be hidden. Within these tags, you can define functions, variables and other JavaScript
statements.
The second possibility is to carry out JavaScript commands given a surfers particular actions. Such actions
can include the loading or leaving of a page or the following of a link with the mouse. In the following example,
the function hello is supposed to be carried out when the page is loaded. This must be defined in advance in
the header of the HTML file:
...
<body onLoad="hello()">
...
In addition, you can incorporate JavaScript commands into a particular part of the page when youre building
the page. This is useful if, for example, youd like JavaScript to incorporate supplements such as text directly
into the HTML file. For example, if you want to incorporate a function write_time in the HTML BODY, then you
must define in the header as:
<BODY>
<script>
write_time()
</script>
<H3>JavaScript example:</H3>
</BODY>
x As with HTML programming, open your windows Notepad program and type the above code.
x Save the Notepad text with First.html.
x Open the First.html file in either Netscape or IE. If you are using IE, then the screen will look like
Figure 1.2.
The JavaScript defines a function called hello() and a statement with alert() for displaying something in
the form of a message. More on about function will be discussed in subsequence chapters. Instead of using
alert() command, you can display the text in the browser window using Document object. For example,
The String for display can be provided in double quotes or as a variable that we will learn soon. Here is an
example of displaying somebodys name using the document.write() function:
<SCRIPT type="text/javascript">
document.write("Author: Gagan Sahoo ")
</SCRIPT>
To display various lines of text, use as many document.write() lines in between <Script> and
<Script> tag as shown in Figure 1.3 on the next page.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.9
JavaScript allows you to mix its own syntax with HTML tags. When you include a string in your JavaScript
and send it to Internet Explorer, everything that is part of the string is sent to the browser as is. Once the
browser receives your string from the document.write() function, it gets rid of the document.write
wordsthe parentheses and double quotes. Then it treats the rest, the part of the string, as HTML code. If the
string that was sent is just a string, the browser would display the text. If you send any special character, the
browser would analyse it to find out if the character is a special HTML symbol. If it is, it would be treated
appropriately. For this reason, a script can result in complex code or difficult-to-interpret errors.
Based on this, you can include any HTML tag as part of the string. Here is an example:
<SCRIPT type="text/javascript">
document.write("Book Title: Multimedia and Web Technology<br>")
</Script>
When Internet Explorer receives this script, it gets rid of everything that is not part of the string. After this
operation, the remaining text becomes:
Book Title: Multimedia and Web Technology
This is what the browser would try to display. There is also an HTML tag in the code, namely, the break tag
<br>; therefore, the break tag would be applied. Let us see the following code:
<SCRIPT type="text/javascript">
document.write("Author: Gagan Sahoo<br>")
document.write("Book Title: Multimedia and Web Technology<br>")
document.write("Publisher: New Saraswati House (India) Pvt. Ltd. <br>")
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.10 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Now, save the file with ...\Unit 3\Chapter 1\Author2.html and preview the page in Internet Explorer
as shown in Figure 1.6.
1.4.6 Statements
JavaScript programs are made of statements. Let us take a look at our previous example, which contains a line,
This is a JavaScript statement. This line tells the browser to write the string "Author: Gagan Sahoo" to
the browser document window. As you saw the line "Author: Gagan Sahoo<br>" shows up just as if you had
included it as part of the HTML code.
1.4.8 Blocks
It is quite common in programming to want to group many statements together so that they can be treated as
one entity; this is often done with functions and in conditions.
This grouping of statements together into one entity is called a block. A block is created by surrounding
all the statements that it will contain with brackets ({ and }). For example,
{
document.write("Hello! I am Rahul and a Web programmer in Class-XII");
document.write("I am in DAV School, New Delhi");
}
1.4.9 Comments
Like other languages, JavaScript supports comments in its code. Comments are completely ignored by the
JavaScript interpreter, so you can type whatever descriptive text you want. You can write single-line or
multiline comments.
6LQJOH/LQH &RPPHQW
If you just need to add a small amount of description to the code, you are writing a single-line comment which
is probably the best option. Placing two slashes (//) before your text makes it a single-line comment.
For example,
{
// This is a single-line comment.
document.write("Hello! I am Rahul and a Web programmer in Class-XII");
document.write("I am in DAV School, New Delhi");
}
0XOWLOLQH &RPPHQW
Sometimes one line of comments is not enough for the description you want to provide. In this case, you can
use a multiline comment. Multiline comments are specified by surrounding the commented text with /* at the
beginning and */ at the end. For example,
{
/* This is the simple programming for Web to display texts
in a browser */
document.write("Hello! I am Rahul and a Web programmer in Class-XII");
document.write("I am in DAV School, New Delhi");
}
Variables enable you to define places to store this data. A variable may be initialized, meaning that it is given a
value when it is declared or it may be uninitialized. In addition, multiple variables can be declared on the same
line by separating their names with commas. JavaScript variables are untyped . They can contain values of any
data type.
'HFODULQJ YDULDEOHV
All JavaScript variables are declared using the keyword var or let. The following rules are used to declare
variables in JavaScript:
x The variable names start contains letters, digits, underscores, and dollar signs.
x The first character in the name must be an alphabetic letter.
x The names can also begin with $ and _ (underscore).
x Characters subsequent to the first character in the variable name can be alphabetic letters, numbers or
underscores.
x Variable names are case sensitive (num and Num are different variables).
x Reserved words (like JavaScript keywords) cannot be used as names.
For example,
<SCRIPT type="text/javascript">
var MyName;
var MySchool = "DAV Public School";
var Age = 15;
document.write("My school: " + MySchool);
</SCRIPT>
After you create a variable, you must assign (give) or initialize a value to it. The ( = ) equal sign is called
assignment operator: you assign the value of what is on the right side of the = sign to whatever is on the left
side of the = sign. Its syntax is:
VariableName = Value
Here, the VariableName must be a valid variable name. It cannot be a value such as a numeric value or
a (double-quoted) string. Here is an example that assigns a numeric value to a variable:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.13
<SCRIPT type="text/javascript">
Salary = 1255;
</Script>
Once a variable has been declared and assigned a value, you can call the document.write() function to
display its value. For example:
<SCRIPT type="text/javascript">
Salary = 22550;
document.write(Salary);
</Script>
To improve, safeguard and make your code more efficient, you should declare a variable before using it.
This is done using the var keyword. The above script could be written as follows:
<SCRIPT type="text/javascript">
var Salary;
Salary = 22550;
document.write(Salary);
</Script>
Let us start an example for assigning values into variables with the following code in a Notepad window:
<SCRIPT type="text/javascript">
var Job1Wage, Job2Wage
Job1Wage = 2500.38
Job2Wage = 2300
document.write("<p>Salaries :</p>")
document.write("Wage 1: Rs. ")
document.write(Job1Wage)
document.write("<br>")
document.write("Wage 2: Rs. ")
document.write(Job2Wage)
</Script>
Save the file as: ...\Unit 3\Chapter 1\Assign.html. When you open the file in IE, the following
screen will appear as shown in Figure 1.7.
The Table 1.1 shows five types of primitive data types in JavaScript:
123456789012345678901234567890121234567890123456789012345
Table 1.1 JavaScript primitive data types.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Data Type Description Example
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
String Represents sequence of characters "Hello", "We are selected in IIT"
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Number Represents numeric values 100, 250.60
123456789012345678901234567890121234567890123456789012345
Boolean Represents boolean value either false or true true, false
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Undefined Represents undefined value
123456789012345678901234567890121234567890123456789012345
Null Represents null No value at all
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Object document, window
123456789012345678901234567890121234567890123456789012345
Array a[0] = 1
123456789012345678901234567890121234567890123456789012345
Table 1.2 JavaScript primitive data types.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Data Type Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Object Represents instance through which we can access members.
123456789012345678901234567890121234567890123456789012345
Array Represents group of similar values.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
RegExp Represents regular expression.
6WULQJV
A string is any grouping of characters that is surrounded by either double quotation marks (") or single
quotation marks ('). Strings are used anytime you want to use text in a program. For example,
"Hello"
"We are selected in IIT"
Usually, double quotation marks are used to denote strings. If you want to include double quotes in the
string itself, use string quotation marks instead. For example,
'Hello friends! The CBSE introduced a special course for "Web Developers" in 2004'
JavaScript strings are immutable, which means that there is no way to change the contents of a string.
Methods that operate on strings typically return a modified copy of the string.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.15
1XPEHUV
There are two numeric types in JavaScript : integers and floating-point numbers. The rules for specifying both
types are almost identical. Integers may be specified in base 10 (decimal), base 8 (octal) or base 16 (hexadecimal)
formats. Any of the three forms can also start with a + or sign. The three forms are:
x 1-9 followed by any set of digits is a decimal integer. For example, 45 is a decimal integer.
x 0 followed by any set of the digits 0-7 is an octal integer. For example, 017 is an octal integer.
x 0x or 0X followed by any of 0-9, a-f or A-F is a hexadecimal integer. For example, 0x12EF5 is a hexadecimal
integer.
The minimum and maximum integers that can be used are implementation dependent, but at least 32 bits
should be expected.
Floating-point numbers can be specified in either the standard decimal point (.) format or the engineering
E-notation. Typically floating-point numbers should contain a decimal point or an exponent, which may begin
with either e or E. A floating-point number may also have a + or sign. 0.0, -1.4212 and 3.1424 are all valid
floating-point numbers.
%RROHDQ
A Boolean is a simplest data type available. A Boolean value has only two possible valuestrue and false.
They are often used to represent whether something has been done or not. It is possible to think of true as 1 and
false as 0. JavaScript converts these logical values into 1 and 0, respectively. JavaScript also accepts any non-
zero integer in place of true, for example, so that 5 and 3 can both be used as stand-ins for true.
2EMHFW
An object is a compound data type that contains any number of properties. Each property has a name and a
value. The . operator is used to access a named property of an object. For example, you can read and write
property values of an object o as follows:
Obj1.x = 1;
Obj1.y = 2;
Obj1.total = Obj1.x + Obj1.y;
Objects are created with the new operator. You can create a new object with no properties as follows:
var Obj1 = new Object( );
Similarly, to create a Data class object that represents the current time with its method,
var Now = new Date();
A function is a piece of JavaScript code that is defined once and can be executed multiple times by a program.
A function definition looks like this:
function sum(x, y) {
return x + y;
}
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.16 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Functions are invoked using the () operator and passing a list of argument values:
var total = sum(1,2); // Total is now 3
In JavaScript 1.1, you can create functions using the Function( ) constructor:
var sum = new Function (x, y, return x+y;);
1XOO
The value null has a very special role in the JavaScript language. The null data type only has one possible
value, i.e., null. When a variable is set to null, it means that it has no value. Variables are often set to null when
a value was to be returned to a function but instead none was generated.
In JavaScript, constants are declared with const keyword and assigned at the time of the declaration. A
constant can be global or local to a function where it is declared. Constants are read-only, therefore you cannot
modify them later on.
Naming a constant in JavaScript follows the same rule of naming a variable except that the const keyword
is always required, even for global constants. If the keyword is omitted, the identifier is assumed to represent
a variable. For example,
const Country = India;
const Num = 20;
1.8 KEYWORDS
In Table 1.3, keywords are part of the JavaScript language, and have special meaning to the JavaScript interpreter.
These reserved words are called keywords. Therefore, they may not be used as identifiers.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Table 1.3 Useful keywords.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
abstract boolean break byte case catch char
123456789012345678901234567890121234567890123456789012345
class const continue default delete
123456789012345678901234567890121234567890123456789012345
do double
else extend false final finally float for
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
function goto if implements import in instanceof
123456789012345678901234567890121234567890123456789012345
int interface long native new null package
123456789012345678901234567890121234567890123456789012345
private protected public return short
123456789012345678901234567890121234567890123456789012345 static super
123456789012345678901234567890121234567890123456789012345
switch synchronized this throw throws transient
123456789012345678901234567890121234567890123456789012345
true try typeof var void while with
Literals are the way you represent values in JavaScript. These are fixed values that you literally provide in your
application source, and are not variables.
,QWHJHU /LWHUDOV
Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).
x Decimal integer literal can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading
zeros. For example, 123, -20, 12345.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.17
x Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number is octal.
For example, 173, -24, 30071.
x Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F or
a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal. For example, 7b, -14, 3039.
%RROHDQ /LWHUDOV
The Boolean type has two literal values: true and false. You can use conditional statement to combine with a
Boolean. For example,
var Flag = true;
if(Flag == true) {
// If the condition evaluates to true
}
else {
// If the condition evaluates to false
}
It goes without saying that the Boolean object is an extremely important part of JavaScript. Without a
Boolean object, there wouldn't be anything to evaluate within conditional statements.
6WULQJ /LWHUDOV
A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be delimited
by quotes of the same type; that is, either both single quotes or double quotes. For example,
Table 1.4 lists the special characters or escape characters that you can use in JavaScript strings.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.18 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
Table 1.4 JavaScript special characters.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Characters Meaning
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\b Backspace
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\f Form feed
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\n New line
123456789012345678901234567890121234567890123456789012345
\r Carriage return
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\t Tab
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\v Vertical tab
123456789012345678901234567890121234567890123456789012345
\' Apostrophe or single quote
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\" Double quote
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\\ Backslash character
123456789012345678901234567890121234567890123456789012345
\XXX The character with the Latin-1 encoding specified by up to three octal digits XXX
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\xXX The character with the Latin-1 encoding specified by the two hexadecimal digits XX
123456789012345678901234567890121234567890123456789012345
between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
symbol.
123456789012345678901234567890121234567890123456789012345
\uXXXX The Unicode character specified by the four hexadecimal digits XXXX. For example,
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
\u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape
123456789012345678901234567890121234567890123456789012345
sequences.
123456789012345678901234567890121234567890123456789012345
You can insert quotes inside of strings by preceding them by a backslash. This is known as escaping the
quotes. For example,
var EQuote = "Hi friends! \"The CBSE multimedia course updated\" by Author: Gagan Sahoo."
document.write(EQuote)
$UUD\ /LWHUDOV
In JavaScript an array literal is a list of expressions, each of which represents an array element, enclosed in a pair
of square brackets ' [ ] ' . When an array is created using an array literal, it is initialized with the specified values
as its elements, and its length is set to the number of arguments specified. If no value is supplied ,it creates an
empty array with zero length. For example, to create an empty array Num,
var Num = [ ];
To create an array with week names,
var WNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
2EMHFW /LWHUDOV
An object literal is zero or more pairs of comma-separated list of property names and associated values,
enclosed by a pair of curly braces ({ }). To declare an object literal, we must maintain the following syntax rules:
x There is a colon (:) between property name and value.
x A comma separates each property name/value from the next.
x There will be no comma after the last property name/value pair.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.19
1.10 EXPRESSIONS
An operand or a combination of operands and operators that, when evaluated, yields a single value. Expressions
are constructs denoting rules of computation of obtaining values of variables and generating new values by
the application of operators. Expressions consist of operators and operands, i.e., variables, constants and
functions. For example,
(f 32) * 5 / 9
is an expression.
1XPHULF ([SUHVVLRQV
For example,
10 + 5
is a numeric expression. Table 1.5 depicted some numeracal expression uisng numerical operators.
123456789012345678901234567890121234567890123456789012345
Table 1.5 Common numerical operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Example Definition
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
+ 10 + 5 Addition
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
10 5 Subtraction
123456789012345678901234567890121234567890123456789012345
* 10 * 5 Multiplication
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
/ 10 / 5 Division
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
% 10 % 5 Modulo: The remainder after division
123456789012345678901234567890121234567890123456789012345
(15 * 5) Unary negation
/RJLFDO ([SUHVVLRQV
A logical (or Boolean) expression is an expression that when evaluated returns a result of either true or false.
Table 1.6 shows logical operators. For example,
true && false
123456789012345678901234567890121234567890123456789012345
Table 1.6 Logical operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Example Definition
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
&& And (exp1 && exp2) returns true if both exp1 and exp2 are true, otherwise
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
returns false.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.20 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
| Or (exp1 || exp2) returns true if either exp1 or exp2 is true, otherwise returns
123456789012345678901234567890121234567890123456789012345
false.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
! Not (!exp) returns false only if exp1 is true or true if exp is false.
1.11 TYPECASTING
JavaScript is a loosely typed language. That means that you do not have to specify the datatype of a variable
when you declare it, and datatypes are converted automatically as needed during the course of script execution.
In JavaScript, when we add two strings, we use the + (concatenation) operator. But when we combine a
string with a number in the form:
stringthing + numberthing
the number is converted to a string and the + operator then glues the two things together (concatenation).
then JavaScript attempts to convert the stringthing to a number and add it, numerically, to numberthing. If the
stringthing can be converted to a string, such as -10, then all goes well; if it cannot then an error result. This
illustrates the concept of implicit conversion in JavaScript. In JavaScript, we can say,
"This page has been accesses" + ctr + " times today"
without having to worry about the data type of the variable ctr. This construction will always give a valid string
and never an error.
JavaScript variables have to be declared in a var statement and each variable holds information of a
specific type. Internally, 3 and 3.00 and "3.00" are represented differently. JavaScript usually infers types from
context, does conversions automatically. For example,
"Sum = " + sum
1.12 OPERATORS
An operator is one that works on data items and performs some mathematical calculations or changes the data.
JavaScript operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise,
compound assignment, conditional and type.
x Assignment Operators. For example, =
x Compound Assignment Operators. For example, +=, =, *=, /=, %=
x Arithmetical Operators. For example, , +, *, /, %, ++,
x Relational Operators. For example, >, <, >=, <=, ==, !=
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.21
We shall discuss some of these operators one by one in the following section.
$VVLJQPHQW 2SHUDWRUV
The equal (=) sign is used for assigning a value to a variable. JavaScript, like all scripting languages, allows you
to assign values to variables. The syntax is:
variable = value;
In addition, JavaScript has a set of compound assignment operators of the forms. The compound assignment
operators combine the simple assignment operator with another binary operator. The compound assignment
operators are also called shorthand operators. The syntax is:
argument1 operator=argument2;
Or
expression1 operator=expression2;
can be understood as:
argument1 = argument1 operator argument2;
Or
expression1 = expression1 operator expression2;
An example program is shown below that demonstrates the different compound operators in JavaScript.
var prod_amt = 10
prod_amt = prod_amt + 2.5; // Add 2.5 to current production
Instead of the above expression, you should use JavaScripts compound addition operator by coding the
update in this way:
prod_amt += 2.5; // Add 2.5 to the current production
The += is called the addition assignment operator. Let us see other examples:
var y;
y *= 2; //same as (y = y * 2) // Compound multiplication
var b1 = true, b2 = false;
b1 &= b2; //same as (b1 = b1 & b2)
123456789012345678901234567890121234567890123456789012345
Table 1.7 Compound assignment operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Name Example Equivalent
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
+= Addition assignment i+=5; i=i+5
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
-= Subtraction assignment j-=10; j=j-10;
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
*= Multiplication assignment k*=2; k=k*2;
123456789012345678901234567890121234567890123456789012345
/= Division assignment x/=10;
123456789012345678901234567890121234567890123456789012345
x=x/10;
123456789012345678901234567890121234567890123456789012345
%= Remainder assignment a%=4; a=a%4;
The computational operators are used in performing arithmetic computations. JavaScript supports the common
mathematical operations for both integers and reals. Table 1.8 shows all the usable arithmetic operators.
123456789012345678901234567890121234567890123456789012345
Table 1.8 Computational or arithmetic operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Name Example Result (When x = 20, y = 10 s = 0)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
+ Addition x+y Sum of x and y.
123456789012345678901234567890121234567890123456789012345
For example, s = x + y is equivalent to 30
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Subtraction x y Difference of x and y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
For example, s = x y is equivalent to 10
123456789012345678901234567890121234567890123456789012345
* Multiplication x*y Product of x and y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
For example, s = x * y is equivalent to 200
123456789012345678901234567890121234567890123456789012345
/ Division x/y Quotient of x and y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
% Modulus x%y
For example, s = x / y is equivalent to 2
123456789012345678901234567890121234567890123456789012345
Remainder of x divided by y.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
For example, s = x % y is equivalent to 0
Other than this, the ++ (Preincrement, postincrement) and (predecrement, postdecrement) operators
are used with the variables as compound expression. The + operator is overload; it also has the extremely
important role of string concatenation.
5HODWLRQDO&RPSDULVRQ 2SHUDWRUV
The relational operators are used to determine if a given relationship exists between the pairs of values. These
operators are always used for comparing strings, numbers and objects, returning a true or a false Boolean
value. Each relational operator always appears with two constants, variables, expressions, or a mix of these
one on each side of the operator. Table 1.9 shows the relational operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Table 1.9 Relational operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operators Description Example (Assume that x = 10 and y = 20)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
== equal to x == y is not True.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
> greater than x > y is not True.
123456789012345678901234567890121234567890123456789012345
< less than x < y is True.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
>= greater than or equal to x >= y is not True.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
<= less than or equal to x <= y is not True.
123456789012345678901234567890121234567890123456789012345
!= not equal to x != y is True.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.23
The six operators in the above listing provide the foundation for comparing data in JavaScript. Each
operator always appears with two constants, variables, expressions, or a mix of theseone on each side of the
operators.
The comparison is straight forward if the two operands being compared are of the same type. When they
are not, the following rules apply:
x When comparing a number to a string, the string is automatically converted to a number.
x When only one of the operands is a Boolean, it is converted to 1 for true and 0 for false.
x When comparing an object to a string or a number, the object is converted to a string (via its toString
method) or a number (via its valueOf method). Failure to convert generates a run-time error.
The strict equality operators === and !== can be used if the operands must be of the same type. Let us see
the difference between == and === operators.
x == is an equal to operator. That is, when we compare two variables of different type, e.g., a boolean
with a string or a number with String using == operator, it automatically converts one type into another
and returns value based upon content equality. For example,
0 == false // true, because false is equivalent of 0
2=="2" // true, 2 string automatically converted into number
x === is an equal value and equal type operator. It only return true if both variable of same type and also
contains same value. For example,
0 === false // false, because both operands are of different type
2 === "2" // false, since both operands are not of same type
/RJLFDO 2SHUDWRUV
The logical operators are also called Boolean operators. With Boolean operators we perform logical operations.
These are most often used with if and while keywords. By combining logical operators with relational operators,
you can create more powerful data-testing statements ( for logical operators, see Table 1.6).
The following example tests the variables using if statement (which shall be discussed in succeeding
chapters).
If ((the variable a is less than the variable b) AND (the variable c is greater than the variable d)).
print results are invalid to the screen.
if ((a < b) && (c > d))
document.write("Result is invalid.");
%LWZLVH 2SHUDWRUV
Bitwise operators work with bits of a binary number. Table 1.10 shows the bitwise operators.
123456789012345678901234567890121234567890123456789012345
Table 1.10 Bitwise operators.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Operator Shorthand Expression Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
& And x&y Bits that are set in both x and y are set.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
| Or x|y Bits that are set in either x or y are set.
123456789012345678901234567890121234567890123456789012345
^ Xor x^y Bits that are set in x or y but not both are set.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
~ Not ~x Bits that are set in x are not set, and vice versa.
123456789012345678901234567890121234567890123456789012345
<< Shift left x <<y Shift the bits of x, y steps to the left.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
>> Shift right x >>y Shift the bits of x, y steps to the right.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.24 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Bitwise & (And) examines bit position in each of its operands. If both operators have a 1 bit in a given
position, then that bit will also be set to 1 in the result. In all other cases, the output bit position is zero.
8QDU\ 2SHUDWRUV
The operators we have discussed so far are all binary operators. JavaScript provides two unary operators for
which only one variable is required. You can use the addition (+) and subtraction () operators by themselves.
When you do, they are called unary operators. For example, to assign four variables with different values
containing positive or negative numbers, the statements are:
var a = -40; // Assign 'a' a negative 40
var b = +40; // Assign 'b' a positive 40 (The plus sign is not needed)
var c = -a; // Assign 'c' the negative of 'a' (40)
var d = +b; // Assign 'd' the positive of 'b' (the plus sign is not needed)
The unary operators (++ and ) are called prefix increment or decrement operators when the increment or
decrement operators appear before the operand. Let us illustrate it by using an example:
a = 10;
d = 12;
b = a++; // Statement (1)
c = ++d; // Statement (2)
After the execution of aforementioned statements, the value of b becomes 10 and the value of c becomes
13 because the precedence of = is greater than the unary operator. So, in Statement (1), a is assigned a value
and then, it is incremented. In Statement (2), d is incremented first and then it is assigned to c.
After the execution of Statement (1) and Statement (2), the values of a and d are also incremented by 1.
So, the value of a becomes 11 and the value of d becomes 13. Here, Statement (1) is equivalent to the
following statements:
b = a;
a = a + 1;
sum a sum
0 10 0
0 11 (after ++a) 11 [after sum + (++a) is a pre-increment]
0 10 0
sum a sum
0 10 0
first decrease the value of a as a = a 1 and then the new value of a (9) is added to the old value of
sum. So, the execution of the equation becomes,
sum = 0 + 9;
sum a sum
0 10 0
0 9 (after a) 10 [after sum + (a) is a post-decrement]
first add the value a (10) with the old value of sum and then decrease the value of a as 9. That is, for
the above line, the decrement value of a (9) does not affect the sum value. So, the execution of the
equation becomes,
sum = 0 + 10;
W\SHGHI 2SHUDWRU
The "typeof" operator in JavaScript allows you to probe the data type of its operand, such as whether a
variable is string, numeric, or even undefined. There are six possible values that typeof returns: "number,"
"string," "boolean," "object," "function" and "undefined." The parentheses are optional in the typeof syntax.
Table 1.11 lists the possible return values of typeof.
1234567890123456789012345678901
Table 1.11 typedef return values.
1234567890123456789012345678901
1234567890123456789012345678901
1234567890123456789012345678901
Evaluate to Indicates
1234567890123456789012345678901
1234567890123456789012345678901
"number" Operand is a number
1234567890123456789012345678901
1234567890123456789012345678901
"string" Operand is a string
1234567890123456789012345678901
"boolean" Operand is a Boolean
1234567890123456789012345678901
1234567890123456789012345678901
"object" Operand is an object
1234567890123456789012345678901
null Operand is null
1234567890123456789012345678901
1234567890123456789012345678901
"undefined" Operand is not defined
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.27
For example,
var Num = 5;
var result = (typeof Num === 'number'); // Returns true
var eBook = "Multimedia For Class-XI";
var result = (typeof eBook === 'string'); // Returns true
var Num;
var result = (Num === undefined); // Returns true
var result = (typedef Num === 'undefined'); // Returns true
&RQGLWLRQDO 2SHUDWRU
The conditional operator, ? is JavaScripts only ternary operator. A ternary operator requires three operands
instead of the single and double operands of unary and binary operators. The conditional operator is used to
replace if-else logic situations. The format of the conditional operator is:
conditional_expression ? expression1 : expression2;
Here:
x conditional_expression, expression1 and expression2 are expressions.
x If the value of conditional_expression is true, then the expression1 is evaluated and becomes the value
of the conditional_expression, otherwise expression2 is evaluated and becomes the value of
conditional_expression.
Example Consider the following three statements and write if-else statement for this:
x = 10; // ....1
y = 15; // ....2
z = (x>y ? x : y); // ....3
When JavaScript evaluates this assignment expression, it first looks at the expression to the left of the
question mark. If age is greater than 18, then expression between the question mark (?) and the colon (:) is
evaluated and used as the value of the entire ? expression. If age is not greater than 18, then the expression
after the colon (:) is evaluated and used for the value of the entire ? expression. The result produced by the ?
operator is then assigned to flag.
1XOO 9DOXH
The value of null has a very special role in the JavaScript language. It is the value of last resort, so to speak, for
every variable. For the beginning JavaScript programmer, its primary role will be initializing variables that do
not have any more meaningful initial value, e.g., to initialize y to some value, we should have actually written,
var y = null;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.28 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
This prevents JavaScript errors that arise when an uninitialized variable is accidentally used in an expression
that requires a value. It is important to realize that the value of null (not NULL) does not give the variable y and
implicit data type. Null also has the property that it may be converted to a form of all the other types. When it
is converted to a number it becomes 0, when it is converted to a string it becomes the empty thing " " and when
it is converted to a Boolean value it becomes false. This is the only case where it is permissible to change the
implicit data type of a variable after it is declared. Therefore, statements such as:
var ok = "Hello" + y;
var w = x + y;
result in ok having the value "Hello" (the same as ok) and w having the value to (the same as x). This is why the
value of null is an excellent way of initializing variablesit is guaranteed to be harmless.
prompt(message). The prompt command will display a window and ask visitor to enter some
data. We can collect the data entered by the user and store them in a variable. 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.
(ii) A default string to display in the text box.
This dialog box is with two buttons: OK and Cancel. If the user clicks on the OK button, the window
method prompt() will return entered value from the text box. If the user clicks on the Cancel button, the
window method prompt() returns null.
For example,
var myName = prompt("Enter your name : ");
alert("You have entered : " + myName);
When the above code is executed, we can show some default text while displaying the prompt. Here is
an example where a default message is displayed for the visitor to enter first name.
var myName = prompt("Enter your name : ", "your first name");
alert("You have entered : " + myName);
Example Write a program in JavaScript to enter your name as FirstName and SecondName and
display the name in an alert window. For example,
if you enter the FirstName as Harapriya and the SecondName as Parikar, then the alert
window will display: Hello Harapriya Parikar.
Solution The code is:
<html>
<title>Use of concatenation operator</title>
<body>
<P> Concatenation
<SCRIPT type="text/javascript">
var FirstName, SecondName, Result
FirstName = prompt("Enter first name")
SecondName = prompt("Enter last name")
Result = FirstName + " " + SecondName // + means "join" here
alert("Hello, " + Result) // and here
</script>
</body>
</html>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.30 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3RLQWVWR5HPHPEHU
1. A variable is a name for a memory location that is used to hold a value of a particular data type.
2. A variable can store only one value of its declared type.
3. Constants are similar to variables but they hold a particular value for the duration of their
existence.
4. The empty string is a string containing no characters.
5. Keywords (or reserved words) are reserved for use by JavaScript.
6. JavaScript is case-sensitiveuppercase and lowercase letters are different.
7. A constant is a meaningful name that takes the place of a number or string and never changes.
8. The prefix and postfix increment and decrement operators have subtle effects of programs,
because of differences, when they are evaluated.
9. Logical operators are a natural choice to implement a condition for a selection or repetition
statement because they return a Boolean value.
10. Logical operators are used to combine one or more than one relational expressions.
11. The comma enables us to put more than one expressions, separated by comma, on a single line.
12. Expressions are combinations of operators and operands used to perform a calculation.
13. JavaScript always performs multiplication, division and modulus first, then computes addition
and subtraction.
14. The arithmetic operators are binary operators because each operates on two operands.
15. The increment operator, ++ and the decrement operator , increase or decrease a variable by
1.
16. If the increment or decrement operator is prefixed to the variable, the variable is increased or
decreased by 1 first and then used in its expression.
17. If the increment or decrement operator is postfixed to the variable, the variable is used in its
expression, then increased or decreased by 1.
18. alert() function is used to display a message to a dialog box (also called alert box).
19. prompt() function asks the user to input some information and stores the information in a
variable.
20. confirm() function displays a confirm box to the visitor and asks their opinion. This confirm
window will have two buttons, one for OK and other for CANCEL.
SOLVED EXERCISES
1. What is JavaScript?
Ans. JavaScript is a scripting language designed primarily for adding interactivity to web pages and creating
web applications.
2. What are the advantages of the JavaScript ?
Ans. Following are the advantages of JavaScript:
x JavaScript is no more difficult to learn than HTML. It allows people with little or no programming
experience who are daunted by Javas complexity to create interactive and Web-based applications.
x JavaScript can be used to solve common problems, such as validating forms input and can also be
used to create dramatic and visually appealing content, which would be impossible with HTML.
x JavaScript is one of the Dynamic HTMLs available in both Netscape Navigator and Internet Explorer.
x As JavaScript lives inside the HTML document, it can either exist as a complete script that is
embedded in the <head> or <body> elements or it can consist of event handlers that are written
directly into the HTML code.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.31
x Characters subsequent to the first character in the variable name can be alphabetic letters, numbers
or underscores.
x Variables are case sensitive.
13. Which escape sequences represent the newline character and tab in JavaScript?
Ans. The escape sequences are : \n and \t
14. What is a logical expression?
Ans. A logical (or Boolean) expression is an expression that when evaluated returns a result of either true or
false.
15. What are the types of numeric values in JavaScrpt?
Ans. JavaScript has two kinds of numeric valuesintegers and floating point.
16. What is escape sequence?
Ans. Combination of characters is preceded by a code-extension character (also called the escape character).
The code-extension character indicates that the succeeding characters are interpreted differently. Escape
sequences are normally used to control printed or displayed output. The characters interpreted with a
backslash (\) are called escape sequences or escape characters.
17. What are operators? Name them.
Ans. Operators are special symbols that perform a particular function on operands. There are five general
types of operators: arithmetical, logical, comparison, assignment and bitwise operators.
18. Name two specific purposes for the + operator.
Ans. The + operator can be used for arithmetic addition and for string concatenation.
19. Explain about conditional operator with its syntax.
Ans. The conditional operator ? is JavaScripts only ternary operator. A ternary operator requires three
operands instead of the single and double operands of unary and binary operators. The conditional
operator is used to replace if-else logic situations. The format of the conditional operator is:
conditional_expression ? expression1 : expression2;
20. What are expressions?
Ans. Expressions are combinations of operators and operands used to perform a calculation. For example,
var SI; // Simple interest
// Evaluated expression SI.
SI = (principal * rate * interest) / 100
21. What is a literal?
Ans. A literal is a sequence of characters used in a program to represent a constant value. For example, A is
a literal that represents the value A, of type char, and 17L is a literal that represents the number 17 as a
value of type long. A literal is a way of writing a value, and should not be confused with the value itself.
22. What is string literal?
Ans. A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be
delimited by quotes of the same type; that is, either both single quotes or double quotes.
23. Explain an assignment statement giving an example. What are assignment statements used for?
Ansn. An assignment statement computes a value and stores that value in a variable. Examples include:
x = 17; // Assign a constant value to the variable x.
newRow = row; // Copy the value from the variable row into the variable newRow.
ans = 17*x + 42; // Compute the value of the expression 17*x + 42 and store that value in ans.
An assignment statement is used to change the value of a variable as the program is running. Since the
value assigned to the variable can be another variable or an expression, assignment statements can be
used to copy data from one place to another in a computer, and to do complex computations.
24. State the difference between = and ==.
Ans. The = (assignment operator) is to assign the value of the variables, whereas == (relational operator)
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Introduction to JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.33
REVIEW QUESTIONS
1. What are variables?
2. Describe the five categories of the JavaScript.
3. What is the use of SRC?
4. What attribute can the JavaScript <SCRIPT> tag accept?
5. What is the difference between single-line and multiline comments?
6. How many data types are available in the JavaScript?
7. What is the use of bitwise operator?
8. What are keywords?
9. What are the rules to be followed while naming the identifier?
10. Classify the following into valid and invalid identifier:
(i) Mybook (ii) Break (iii) _DK (iv) My.book
11. What are integer variables?
12. What are character variables?
13. What are float-point variables?
14. How will statements get terminated in JavaScript?
15. Write a statement to declare three integers and store them in the variables x, y and z.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.38 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
JavaScript F unctions
Functions
2
2.1 INTRODUCTION
The basic statements, expressions and operators that were discussed in previous chapter is what computer
scientists usually call primitives. Primitives are the building blocks from which more complex elements of a
program are constructed. Functions and objects represent the highest level of organization within the JavaScript
language.
2.2 FUNCTIONS
A function is a block of code that will be executed when "someone" calls it. In JavaScript, we can define our own
functions, called user-defined functions, or we can use built-in functions already defined in the JavaScript
language. We have already seen examples of built-in functions, such as:
x window.alert( )
x document.write( )
x parseInt( )
Below, we will show how to define our own user-defined functions. Functions are the central working units
of JavaScript.
'HILQLQJ )XQFWLRQ
A function definition is just a regular variable definition where the value given to the variable happens to be a
function. A function is a block of code that has a name. Whenever that name is used the function is called,
which means that the code within that function is executed. Functions may also be called with values, known
as parameters, which may be used inside the body of the function. Functions serve two purposes:
x A function is an organizational tool, in the sense that it permits you to perform the same operation
without simply copying the same code.
x The second purpose of JavaScript functions is to link actions on a Web page with JavaScript code.
Mouse clicks, button presses, text selection and other user actions can call JavaScript functions by
including suitable tags in the HTML source for the page.
JavaScript provides several ways of defining them:
x Function Declaration
x Function Expression
3.39
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.40 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
In the above program the function print_message() is invoked from JavaScript. Then the control passes
to print_message() function, and the body of the function gets executed. Simultaneously the execution
control returned back to JavaScript to execute the remaining statements.
Here from the function declaration, the JavaScript, which invokes the function print_message(), is called
the calling function and the function print_message() is the called function.
Example Write a JavaScript function to display the temperature value in an alert window. The code
should enter the temperature value in an HTML text box.
Solution Write the following code in Notepad editor and save as jfun02.html.
<html>
<head>
<title>Temperature in Fahrenheit</title>
</head>
<SCRIPT type="text/javascript">
function show_temp()
{
var Tval=frm.txt.value;
alert("The temperature in Fahrenheit is " + Tval + " degrees F.")
}
</script>
<FORM name="frm">
Enter Number in Degrees Fahrenheit:
<input type=text size="20" name="txt">
<input type="button" value='Temperature' OnClick="show_temp()">
</FORM>
</html>
Here, a FORM is used to hold a text entry box labeled txt and a push button labeled show_temp. When
the user clicks on this button, the associated JavaScript function show_temp() is invoked.
The statement,
var Tval=frm.txt.value;
inside the function show_temp() sets the variable and allows access to the text entry box txt. alert()
abd displays the temperature value by using concatenated strings operator +.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.42 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
x After typing, save the file with the name ...\Unit 3\Chapter 2\jfun02.html and browse in IE.
x In IE when you enter the details and press the Temperature button, the screen will look as shown
in Figure 2.2.
A JavaScript function can return a value using return statement. The value returned can be a valid JavaScript
type. A return statement determines the value the function returns. When control comes across such a
statement, it immediately jumps out of the current function and gives the returned value to the code that called
the function. The syntax is:
return (return value);
When using the return statement, the function will stop executing, and return the specified value.
</script>
<script language = "JavaScript">
// When the function is called, "Navya Singhal" is the argument passed to the function
welcome( "Navya Singhal" ); // Function argument
</script>
The function above will display the message box "Welcome Navya Singhal to my website!" when the
function is called in the webpage.
)RUPDO 9DULDEOHV3DUDPHWHUV
The variables (or parameters) which accept the actual variables inside the function are called formal variables.
Each function definition contains an argument list called the formal argument list. Items in the list are optional,
so the actual list may be empty or it may contain any combination of data types such as inteter, float and
character. For example,
// Formal arguments in function declaration
<SCRIPT type="text/javascript">
function welcome(myName)
{
alert( "Welcome " + myName + " to my website!" );
}
</script>
$FWXDO 9DULDEOHV3DUDPHWHUV
The variables which are associated with function name during function call are called actual variables. When
the program calls the function, an argument list is also passed to the function. This list is called the actual
argument list. For example,
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function calc_Avg(num1, num2, num3) // Formal parameters
{
var local_avg; // Holds average for these numbers
local_avg = (num1 + num2 + num3) / 3;
return (local_avg);
}
// Call the function, passing the numbers, and accept return value
var avg = calc_Avg(100, 235, 400); // Actual parameters
....
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.44 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
....
</script>
Here, 100, 235, and 400 are the actual arguments, which are passed into the calc_Avg() function.
Example Write a JavaScript function to find the average of three numbers. The three numbers should
be treated as parameter to the function. Also, function should return the average and all
details.
Solution Write the following code in Notepad editor and save as jfun01.html.
<HTML>
<HEAD>
<TITLE>JavaScript Function return Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function calc_Avg(num1, num2, num3) // Formal parameters
{
var local_avg; // Holds average for these numbers
local_avg = (num1 + num2 + num3) / 3;
return (local_avg);
}
var num1 = 100, num2 = 235, num3 = 400;
var avg; // Will hold the return value
// Call the function, passing the numbers, and accept return value
avg = calc_Avg(num1, num2, num3); // Actual parameters
document.write("The first number is : " + num1 + "<br>");
document.write("The second number is : " + num2 + "<br>");
document.write("The third number is : " + num3 + "<br>");
document.write("The average is : " + avg );
</script>
</BODY>
</HTML>
Open the jfun02.html file in IE, and see the output window as shown in Figure 2.3.
The calc_Avg() function above takes three numbers as parameters, and returns the average of the three
numbers. On Line,
avg = calc_Avg(num1, num2, num3);
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.45
when the calc_Avg() function is called, the value 245 is returned and then stored in the variable avg.
The above declaration is called function expression. When the JavaScript parser sees a function in the
main code flow, it assumes Function Declaration. When a function comes as a part of a statement, it is a
Function Expression.
You can also use the value returned by the calc_Avg() function without storing it as a variable. For
instance, we could call the function and use the return value in the document.write() line:
document.write("The average is : " + cal_Avg(num1, num2, num3);
Write a JavaScript function called Fullname() to concatenate two names and also display in
third textbox.
Solution Write the following code in Notepad editor and save as jfun03.html.
<html>
<head>
<title>Employees Payroll</title>
<SCRIPT type="text/javascript">
function Fullname()
{
var nName = frm.txt1.value + " " + frm.txt2.value;
frm.txt3.value = nName;
}
</script>
</head>
<body>
<h2>Real Value System - Employees Payroll</h2>
<form name="frm">
<TABLE cellPadding=2 width="60%" border=1 color="BLUE">
<tr>
<td>Enter first name</td>
<td><input type=text name="txt1" size="20"></td> </tr>
<tr>
<td>Enter last name</td>
<td><input type=text name="txt2" size="20"></td> </tr>
<tr align="center">
<td COLSPAN="2"><input type="button" value="Proceed"
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.46 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
onclick="Fullname()"></td></tr>
<tr> <td>Full name:</td>
<td><input type=text name="txt3" size="40" READONLY>
</td><td></td>
</table>
</form>
</body>
</html>
/RRS 6FRSHV
In the previous chapter, we declared different variables inside loops. Any variables created inside a loop are
treated as local scope or local variables to the loop. This means that once you exit the loop, the variable can no
longer be accessed. This includes any variables created in the loop signature. Let us see following two
examples:
Example 1:
Example 2:
var i;
for (i = 0; i <= 10; i++)
{
document.write(("\nloop scope variable " + i + "<br>");
}
In Example 1, i can only be used inside the for loop. In Example 2, you are free to use i inside the loop as
well as outside the loop because it was declared outside the loop (it has been declared as method scope).
/RFDO 6FRSHV
The variables which are declared inside a function/method are called local variables. You may use a local
variable completely within a function definition. Its scope is then limited to the function itself, i.e., it can be used
only within the declaring method. The variable is said to be accessible or visible within the function only and
has a local scope.
For example,
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function calc_Avg(num1, num2, num3)
{
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.47
Here in line,
document.write("The average is : " + local_avg);
Here, the integer variable a is declared twice, once in fun1() and once in fun2(), but the a in fun1() has
no effect on function fun2(). This is because a is known only to the code within the block in which it is
declared.
Local variables are deleted from memory as soon as the function is completed
x We can also declare local variables inside any code block that is nested inside another code block.
For example, consider the following function:
void fun() {
var age = prompt("Enter your age")
if (age == 18) {
document.write("Your age is accurate for voting");
}
}
Here, the local variable guess is created at the entry of the function fun() and so its scope remains until the
terminating curly brace of the function fun() is encountered. However, the local variable age is created upon
entry into the if code block and destroyed upon the exit from the if block. That is, age is known only within the
if block and cannot be referenced elsewhere within the outer block (i.e., of the fun()).
We can initialize the local variable to some value. Now, this value will be assigned to the variable each time
we will enter the block of code in which it was declared, no matter if the value is later modified in the block.
If you try to access the local variable outside the method, the compiler would flag it as an error. However,
the same variable name can be declared within several different methods without there being a conflict.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.48 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
A global scope variable is visible to all functions/methods and is To declare JavaScript global
declared outside the method, and all scripts and functions on the web variables inside function, you
page can access it. For example, need to use window object.
When you declare a variable
var i; // i is a global variable outside the function, it is added
There can be situations where a local variable with the same name in the window object internally.
is used in a function. Then the local variable hides the global variable, You can access it through
i.e., the function will give preference to the local variable as compared window object also. For
to the global variable. example:
Global variables, variables declared outside of a function, are
deleted when you close the page. The following example, describes var Num = 10;
both global and local variables in JavaScript program: function a(){
//accessing global variable
<SCRIPT type="text/javascript">
// Difference between Global and Local Variables alert(window.value);
// Declare the global variables }
var global_one = 32;
var global_two;
function test {
// This function has a local variable a global value is copied into it
// the local is then passed into a function as a parameter
var local_var; // Local variable
local_var = global_one; // Copy global
// into local
func_two(local_var);
}
function func_two(number) {
// create a local variable and copy a parameter into it
var local_var = number;
}
// copying a local variable into a global
// like this is not allowed
global_two = local_var
</script>
eval(). This function evaluates a string as a JavaScript statement or expression, and either executes
it or returns the resulting value. The syntax is:
eval(string)
escape(). This function encodes the string passed to it so that it can be used across any network,
say, for example, in query strings. The syntax is:
escape(string)
which prints:
testing%20escape%20function%21%21
escape() function leaves digits,latin letters and the characters + - * / . _ @ unchanged and replaces all
other characters with ASCII code of the original character preceded by % symbol.
unescape(). This method is used to decode the encoded strings and returns the ASCII string for the
specified value. The syntax is:
unescape(string)
For each distinct set of characters in the argument string of the following form
x "%integer", where integer is a number between 0 and 255 (decimal)
x "hex", where hex is a number between 0x0 and 0xFF (hexadecimal)
For example,
unescape("%26") // returns "&"
unescape("ab%21%23" // returns "ab!#"
isNaN(). This function determines whether the value of a variable is a legal number or not. This
function is remembered as short form is Is Not a Number. This function returns true if the data is string
and returns false if the data is a number. Here is one simple example to check one string. The syntax is:
isNaN(numValue)
The function is better use in if condition to check to display a message accordingly. For example,
var myString = prompt("Enter a number");
if (isNaN(myString)) {
alert("This is not a number ");
} else {
alert("This is a number ");
}
parseInt(). This function is used to convert strings to numbers. This function can only convert
strings which are in the form of numbers and it can't change any alphabet or strings. If there is no
number at the beginning of the string, "NaN" (not a number) is returned. The syntax is:
parseInt(numString, [radix])
For example,
document.write(parseInt("124.56")); // return 124.
document.write(parseInt("abc34")); // Returns NaN.
document.write(parseInt("25.5abc")); // Returns 25.
document.write(parseInt("216.0PLL")); // Returns 216.
parseFloat(). This function is used to convert strings to float numbers. Using this function, we can
only convert string numbers to numeric data but we can't convert alphabetic characters. The syntax is:
parseFloat(numString)
Here, numString is string that contains a floating-point number to convert into a number. The parseFloat
function returns a numerical value equal to the number contained in numString. If no prefix of numString
can be successfully parsed into a floating-point number, NaN (not a number) is returned.
For example,
document.write(parseFloat("124.56")) // return 124.56.
document.write("<br>");
document.write(parseFloat("abc34")); // Returns NaN.
document.write(parseFloat("25.5abc")); // Returns 25.5.
document.write(parseFloat("216.0PLL")); // Returns 216.
round(). This function is used to round off any number with decimal place to an integer value by
using round function. If the decimal portion of the number is equal or greater than .5 then the next
higher integer is returned or if the number is less than 05 then the number is rounded to next lowest
integer. The syntax is:
Math.round(number)
For example,
document.write (Math.round(22.75)); // print 23
document.write("<br>");
document.write (Math.round(17.05)); // print 17
document.write (Math.round(-22.75)); // print -23
document.write (Math.round(-18.15)); // print -18
document.write (Math.round(21.65)); // print 22
We can format math number by using round function. Here is an example to format upto two decimal
places.
var Num = 11.257;
document.write (Math.round(Num * 100) / 100);
ceil(). This function is used ceil of a number to the smallest integer that is greater than or equal to
given number. So by using this we can get the next higher integer of a given number. The syntax is:
Math.ceil(number)
For example,
document.write (Math.ceil(24.314)); // output 25
document.write (Math.ceil(20.56)); // output 21
document.write (Math.ceil(-13.564)); // output -13
floor(). This function is used to get the floor of a number or the largest integer which is equal to or
lower than the given number. So by using floor we can get the floor value of an number.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.52 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
For example,
document.write (Math.floor(24.314)); // output 24
document.write (Math.floor(20.56)); // output 20
document.write (Math.floor(-13.564)); // output -14
pow(number). This function is used to get the power of an integer. The syntax is:
Math.pow(x,y)
For example,
document.write(Math.pow(5,5)); // output is 3125
document.write(Math.pow(0,0)); // output is 1
document.write(Math.pow(0,1)); // output is 0
document.write(Math.pow(1,0)); // output is 1
document.write(Math.pow(1,1)); // output is 1
document.write(Math.pow(2,2)); // output is 4
document.write(Math.pow(2,-2)); // output is 0.25
document.write(Math.pow(-2,2)); // output is 4
max(number). This function is used to get highest value from a set of numbers. The syntax is:
Math.max(x1,x2,x3,.xn)
For example,
document.write(Math.max(23,12,24,15,17,5)); // output is 24
document.write("<br>");
document.write(Math.max(-5,16,-22,12,-20)); // output is 16
document.write("<br>");
document.write(Math.max(-12,-23,-3)); // output is -3
Math.sqrt(x);
For example,
document.write(Math.sqrt(4)); // output is 2
document.write("<br>");
document.write(Math.sqrt(64)); // output is 8
document.write("<br>");
document.write(Math.sqrt(9)); // output is 3
document.write("<br>");
document.write(Math.sqrt(27)); // output is 5.196152422706632
document.write("<br>");
document.write(Math.sqrt(0.36)); // output is 0.6
document.write("<br>");
document.write(Math.sqrt(-64)); // output is Nan
The Date object is a built-in JavaScript object that enables you to conveniently work with dates and times.
JavaScripts Date object follows the UNIX standard of storing date and time information internally as the
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.53
You have several optional parameters that we may send to the Date object as follows :
x variableName = new Date().
x variableName = new Date("month day, year hour:minutes:seconds").
x variableName = new Date(year, month, day).
x variableName = new Date(year, month, day, hours, minutes, seconds).
For example,
var BDay = new Date("May 18, 2004 03:00:00"); // Setting a new date
Once you have created a Date object, you can then use the many Date methods to get or set the month,
day, year, hours, minutes or seconds of this instance. As with most object methods, you simply call a Date
method as follows:
variableName.methodname(parameters)
For example,
today.setHours(7);
There are two exceptions to this rule with the Date object: The UTC and parse methods are static
methods and are always called with just the generic Date object name. For example,
Date.UTC(parameters)
Date.parse(parameters)
In Table 6.3, two methods are shown. One is get method and the other is set method. The get method allows
you to retrieve information from the current Date object. This information can be seconds, minutes, hours,
days of the month, days of the week, months or years. For example,
today = new Date("September 27, 1997")
document.write("Birthday is on " + today.getdate())
N ote
Similarly, the set method allows you to add or change attributes
of the Date object. You can change the dates, months, years, hours, The getMonth() returns a
minutes, seconds of the Date object. All of these methods require number between 0 and 11; if
integers. Although you will probably use the get methods more often, you want to show the month to
these methods are handy when you want to quickly create a date and your site's visitors, to be user-
timeperhaps for displaying on a page with a modification date. For friendly you should add 1 to the
example, month after using getMonth().
today = new Date("September 27, 1997")
today.setDate(4);
document.write(today.getDate());
Open the jfun04.html file in IE, and the see the output window as shown in Figure 2.4.
6WULQJ )LQFWLRQV
JavaScript contains some basic string manipulation functions which are useful for JavaScript query. As we
know, when we declare and manipulate strings in JavaScript, always write them with single quotes ' or double
quotes " around them. This tells the browser that it's dealing with a string.
For example,
var a = "Hello world!";
var b = 'I am a JavaScript hacker.'
Here, both a and b are two strings and declared in double quotes and single quotes. But be careful, don't mix
up the quotes.
The JavaScript String object is a wrapper for text values. In addition to storing text, the String object
includes a property and various methods to manipulate or gather information about text. The syntax of creating
String object using new keyword is given below:
charAt(). This function returns the character at the x position within the string. The syntax is:
str.charAt(x);
Here str is a string and x is the position where a character will extract. For example,
var str = "Multimedia and Web Technology, Class - XI";
document.write("Character at 7th place: ", str.charAt(7)); // Returns d
concat(). This function combines one or more strings (arguments str1, str2, etc.) into the existing
one and returns the combined string. Original string is not modified. The syntax is:
str.concat(str1, str2, ...);
For example,
var str1 = "CBSE";
var str2 = " Multimedia";
str1 = str1.concat(str2, ' Class - XI');
document.write("New string is: ", str1);
Here, str1 is the original string which holds the string of str1, str2 and Class - XI. The final result
of str1 will be: CBSE Multimedia Class - XI.
indexOf(). This function searches and (if found) returns the index number of the searched character
or substring within the string. If not found, -1 is returned. Start is an optional argument specifying
the position within string to begin the search. Default is 0. The syntax is:
str.indexOf(char/substring)
Here char/substring is a character whose position will be searched in string str. For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Index of M is: ", str1.indexOf('M'));
If not found, -1 is returned. Start is an optional argument specifying the position within string to
begin the search. Default is string.length-1. The syntax is:
lastIndexOf(substr, [start])
Here substr is a string or a character whose position will be searched in string str. For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Last index of a is: ", str1.lastIndexOf('a'));
For example,
var str1 = "CBSE Multimedia Class - XI";
var nStr = str1.substr(0, 15);
document.write("Substring is: " + nStr);
which will produce the result as:
Substring is: CBSE Multimedia
substring(). This function returns the characters in a string between from and to indexes, NOT
including to itself. To is optional, and if omitted, up to the end of the string is assumed. The syntax
is:
str.substring(from, to)
For example,
var str1 = "CBSE Multimedia Class - XI";
var nStr = str1.substring(0);
document.write("Substring is: " + nStr);
which will produce the result as:
Substring is: CBSE Multimedia Class - XI
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.58 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
toLowerCase(). This method is used to generate a new string with lowercase letters. The method
returns a new string containing the converted string and the original string is unchanged. The syntax
is:
str.toLowerCase()
For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Lowercase string is: " + str1.toLowerCase() + "<br>");
document.write("Original string is: " + str1);
toUpperCase(). This method is used to generate a new string with uppercase letters. Like
toLowerCase() method, toUpperCase() also returns a new string containing the converted string
and the original string is unchanged. The syntax is:
str.toLowerCase()
For example,
var str1 = "CBSE Multimedia Class - XI";
document.write("Uppercase string is: " + str1.toUpperCase() + "<br>");
document.write("Original string is: " + str1);
which will produce the result as:
Uppercase string is: CBSE MULTIMEDIA CLASS - XI
Original string is: CBSE Multimedia Class - XI
toString(). This method is used to convert a number to string. The syntax is:
str.toString()
For example,
<SCRIPT type="text/javascript">
var Num = 100;
document.write("Number is: " + Num + "<br>");
var Sum = Num + 10;
document.write("Sum is: " + Sum + "<br>");
var str1 = Num.toString(); // Converting number to string
document.write("Number with string is: " + str1 + "<br>");
var str2 = str1 + 100;
document.write("New string is: " + str2);
</script>
which will produce the result as:
Original string is: CBSE Multimedia Class - XI
Number is: 100
Sum is: 110
Number with string is: 100
New string is: 100100
From the above output, the list line displays,
New string is: 100100
because the line, var str2 = str1 + 100; concatenates str1 value 100 with another number 100.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.59
valueOf(). This method returns the primitive value of an object. These objects are:
For example,
<SCRIPT type="text/javascript">
var str1 = "CBSE";
document.write("Value of str1: " + str1.valueOf() + "<br>");
var Num = 100;
document.write("Value of Num: " + Num.valueOf() + "<br>");
var Flag = true;
document.write("Value of Flag: " + Flag.valueOf() + "<br>");
</script>
3RLQWVWR5HPHPEHU
1. A function is a block of code that will be executed when "someone" calls it.
2. A function which does not accept any values must have the name of the function followed by an
empty set of parentheses.
3. The parameters to a function behave like regular variables, but their initial values are given by
the caller of the function, not the code in the function itself.
4. A variable declared inside a function is local to that method and cannot be used outside it.
5. Variables that are declared inside an opening curly brace and a terminating curly brace are
termed as local variables.
6. A global variable is visible to all functions and is declared outside all functions.
7. The variables (or parameters), which accept the actual variables inside the function are called
formal variables.
8. The variables, which are associated with function name during function call, are called actual
variables.
9. Functions are invoked in a program by writing the name of the function followed by the arguments
of the method in parenthesis.
10. The argument of a method may be a constant, a variable or an expression.
11. Local variables, or variables declared within a function, are deleted when the function is completed.
12. Global variables, variables declared outside of a function, are deleted when you close the page.
13. In JavaScript, the lifetime of a variable starts when the variable is declared.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.60 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
SOLVED EXERCISES
1. What is a function?
Ans. A set of operations which is part of a program and can be executed independently is called a function.
2. What are the types of functions?
Ans. Functions are of two types. These are : user-defined and built-in.
3. What is a user-defined function?
Ans. This function which is written by the programmer according to its need is known as user-defined
function.
4. How many times can function be called?
Ans. Many times.
5. What are function arguments?
Ans. Arguments of a function is the data that the function receives when called from another function.
6. What is a local variable?
Ans. Variables that are declared inside an opening curly brace and a terminating curly brace are termed as local
variables.
7. What is a global variable?
Ans. Global variables are the variables that are known throughout the program and may be used by any part
of the program. They hold their value throughout the execution of the program.
8. What is formal variable?
Ans. Formal variables are listed of variables that will accept different types of values being supplied to the
function by the calling program. Formal parameters are declared after the function name and inside
parentheses.
9. What is an actual variable? How is it different from an actual argument list?
Ans. The variables which are associated with function name during function call are called actual variables.
When the program calls the function, an argument list is also passed to the function. This list is called
the actual argument list.
10. Explain the difference between an actual parameter and a formal parameter.
Ans. An actual parameter is the value or variable sent to a method when it is invoked. A formal parameter is the
corresponding variable in the definition of the method; it takes on the value of the actual parameter so
that it can be used inside the method.
11. Are objects passed by value or by reference?
Ans. JavaScript supports only pass by value. With objects, the object reference itself is passed by value and
so both the original reference and parameter copy refer to the same object.
12. What will be the output of the following two line code?
document.write(Math.round(2.3)+ "" + "<br>");
document.write(Math.pow(2, 3)+ "");
Ans. The output is:
2
8
13. What content do the following lines display in an web browser?
var Message = "A11 The Best";
document.write((Message.length - 6));
Ans. The content is: 6
14. Write an equivalent JavaScript statement for the given expression:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.61
23. Write a simple function to display your name with Hello <name>.
Ans. The function is:
<html>
<body>
<SCRIPT type="text/javascript">
function Hello(sName)
{
document.write("")
document.write("Hello " + sName)
}
Hello("Kumar")
</script>
</body>
</html>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
JavaScript Functions
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.63
24. Create a JavaScript function to add two parameterized numbers. Note that the two numbers will be
received as parameter to function.
Ans. The function is:
<script type="text/JavaScript">
function sum(number1, number2) {
var sum = number1 + number2
return sum
}
var total = sum(100,9)
document.write("Total is: " + total)
</script>
25. Write a JavaScript function to convert the temperature value from Celsius to Fahrenheit. Assume
that the temperature value is 100.
Ans. Write the following code in Notepad editor and save as fun06.html.
<HTML>
<HEAD>
<TITLE>JavaScript Function</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to find the average of 3 numbers
function convert(c_temp) // Return var and parameter are both float
{
var f_temp;
f_temp = c_temp * (9.0 / 5.0) + 32.0;
return (f_temp);
}
var c_temp = 100;
var f_temp = convert(c_temp); // Convert the temperature
document.write("The Fahrenheit value is : " + f_temp);
</script>
</BODY>
</HTML>
REVIEW QUESTIONS
1. What is a user-defined function?
2. What role do the arguments play in a function?
3. How will you call a function?
4. Name the statement that sends back a value from a function.
5. How many values can be returned by a function?
6. When is the execution of the function terminated?
7. Summarise the rules that must be followed during function call.
8. Give the output of the following program:
<SCRIPT type="text/javascript">
function display()
{
document.write(" program.");
}
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.64 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Branching in JavaScript
3
3.1 INTRODUCTION
Conditional statements allow you to control the flow of execution of a script or one of its sections. The flow of
activity through the program code is called the flow of control. In computer programming, there are three main
types of control flows that occur. These are:
if condition if condition
Statement 1
`
is false is true
condition
conditional code
`
`
Statement 2 condition
if condition
`
code
`
Statement 3
if condition
is false
123456789012345678901234567890121234567890123456789012345
Table 3.1 Decision making statements.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Statement Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
if statement An if statement consists of a Boolean expression followed by one or more
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
statements.
123456789012345678901234567890121234567890123456789012345
if...else statement
123456789012345678901234567890121234567890123456789012345
An if statement can be followed by an optional else statement, which executes
123456789012345678901234567890121234567890123456789012345
when the Boolean expression is false.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
nested if statement You can use one if or else if statement inside another if or else if statement(s).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
switch statement The switch statement is a multiway branching statement.
`
Here, if condition
is true
x Condition is a Boolean expression. condition
x The Condition includes any relational comparison
and must be enclosed within parentheses.
x If the Condition is true, then the statement is
`
executed. If the Condition is false , then the conditional code
if condition
statement is bypassed.
is false
x The statement(s) of the if, sometimes called the body
of the if statement, is usually indented a few spaces `
for readability.
`
For example, suppose you have declared a variable named MyPer and you want to print a message
Grade A when the value of MyPer is greater than and equal to 80. The JavaScript code for if ... endif
condition is:
var MyPer
MyPer = 91;
if (MyPer >= 80)
document.write("Grade A")
endif
b = 20;
document.write("Value of a is " + a + "<br>");
document.write("Value of b is " + b + "<br>");
if (a < b)
document.write("A is less than B");
endif
</script>
</body>
</html>
Save the file with ...\Unit 3\Chapter 2\ifendif.html and preview it in the browser as shown in Figure
3.3.
Although the (simple) if statement is used to check one condition, it can lead to executing multiple
dependent statements. If that is the case, enclose the group of statements between an opening curly bracket
{ and a closing curly bracket }.
float MyPer = 91;
if ( MyPer >= 80 )
{
document.write("My roll no. is 100 <br>");
document.write("Grade A");
}
The above code of if condition has two statements which are enclosed within curly ({ }) braces. This is
called a block. If the value in MyPer is greater than or equal to 80, the line of code in the block executes next.
Otherwise, JavaScript skips the entire block and continues with the program.
The if statement executes a number of operators. These are listed in Table 3.2.
123456789012345678901234567
123456789012345678901234567
Table 3.2 JavaScript equality and relational operators.
123456789012345678901234567
123456789012345678901234567
Operator Meaning
123456789012345678901234567
123456789012345678901234567
== equal to
123456789012345678901234567
123456789012345678901234567
!= not equal to
123456789012345678901234567
< less than
123456789012345678901234567
123456789012345678901234567
<= less than or equal to
123456789012345678901234567
123456789012345678901234567
> greater than
123456789012345678901234567
>= greater than or equal to
The condition includes any relational comparison and must be enclosed within parentheses. If the value of
the condition is non-zero, then the body of if gets executed. The block of one or more JavaScript statements
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.68 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
can be any legal JavaScript statement, such as an assignment or the document.write(" " + var) statement,
enclosed within braces or any operation. Some of valid if statements are:
x if (a > 0)
document.write(" " + a + " is a positive number");
x if (a) // Same as : if (a != 0)
document.write(" " + a + " is a non-zero number ");
x if (guess == num)
document.write("You guessed the right number ");
x if (a <= b)
document.write(" " + a + " is greater than " + b);
x if ((a < b) && (b > c))
document.write(" " + a + " < " + b + " < " + c);
x if ((a % b == 0) && (b != 0))
document.write(" " + (b + " is a divisor of " + a);
x if ((ch >= 0) && (ch <= 9)) // if ch is in between ASCII 0 and 9
document.write(" " + ch);
Example Write the JavaScript code for a web application to using HTML code to know whether you
are a minor or not. The application should enter your age and display the message:
"You are a minor. Your age not more than 18."
Example Write the JavaScript code to compare two numbers and print the numbers with their
comparison result.
Solution The code is (ifendif.html):
<html>
<head>
<title>if endif example</title>
</head>
<body>
<script type="text/JavaScript">
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.69
var a, b;
a = 10;
b = 20;
document.write("Value of a is " + a + "<br>");
document.write("Value of b is " + b + "<br>");
if (a < b)
document.write("a is less than b");
endif
</script>
</body>
</html>
`
Statements;
} if condition
else { condition
is true
Statements;
}
`
like Figure 3.4; one of two paths of action is taken, is false
conditional code
depending on the condition.
`
Save the file with ...\Unit 3\Chapter 3\chour.html and see the preview of the page in a browser.
Example Simran Kaushik developed web application using JavaScript to convert temperature from
Fahrenheit to Celsius and vice versa. The resulted web page is shown below:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.71
To satisfy the page, enter the degree to the Textbox and select option from combobox
(Celsius or Fahrenheit) and then calculate the temperature from Fahrenheit to Celsius and
vice versa using JavaScript code.
Solution Write the following code in Notepad editor and save as convert.html.
<html>
<head>
<title>Temperature in Fahrenheit</title>
</head>
<script type="text/javascript">
function Convert_Temp()
{
var opt = frm.myoption.value;
if(opt == "Fahrenheit")
{
var val = frm.txt.value;
if (isNaN(val))
{
alert("Not a Number");
}
else {
var tf=parseInt(val);
var tc= (tf - 32) * (5/9);
var res1 = Math.round(tf * 100)/100;
frm.txt1.value = res1+" C";
}
}
else
{
var val=frm.txt.value;
if (isNaN(val))
{
alert("Not a Number");
}
else {
var tc=parseInt(val);
var tf=(tc * (9/5)) + 32;
var res1 = Math.round(tf * 100)/100;
frm.txt1.value=res1+" F";
}
}
}
</script>
<form name="frm">
<TABLE cellPadding=2 width="70%" border=1 color="BLUE">
<tr>
<td>Enter the degree</td>
<td><input type=text name="txt" size="12"></td>
<td><select name="myoption">
<option name="Faren" value="Fahrenheit">Farenheit</option>
<option name="Cels" value="Celsius">Celsius</option>
</select></td>
<td><input type="button" value="Calculate" onclick="Convert_Temp()">
</td></tr>
<tr><td>Equal Value</td>
<td><input type=text name="txt1" size="12" READONLY>
</td><td></td>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.72 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
</table>
</form>
</html>
3.2.3 Nested if
Nested if/else structures test for multiple causes by placing if/else selection structure inside if/else selection
structure. The if/else selection structure uses the condition till three levels. This is very useful to test various
conditions using single if...else if statement. The syntax is:
If (Condition-1) {
Statements which will be executed if Condition-1 is true
}
else if (Condition-2) {
Statements which will be executed if Condition-2 is true
}
.
.
else if (Condition-n) {
Statements which will be executed if Condition-n is true
}
else {
Statements which will be executed if none of the conditions is true
}
As you can see in this if else if ladder, conditions are evaluated from top. First Condition-1 will be
evaluated and if this is true, the code inside the if block will be executed. If Condition-1 is false, Condition-
2 will be evaluated. If Condition-2 is true, the code inside that else if block will be executed. If Condition-
2 is false, Condition-3 will be evaluated. This will go on like this. If none of the conditions are true, the code
inside the else block will be executed.
Some of the valid nested if statements are:
x <script language = "JavaScript">
var average = 88;
if (average > 80)
document.write("Grade is A");
else if (average > 70)
document.write("Grade is B");
else if (average > 60)
document.write("Grade is C");
else if (average > 50)
document.write("Grade is D");
else if (average > 40)
document.write("Grade is E");
else
document.write("Grade is F");
You can add as many else if clauses as you need to provide alternative choices. For example, type the
following JavaScript code in Notepad window:
<html>
<head>
<title>Nested if example</title>
<SCRIPT type="text/javascript">
function greeting()
{
var CDate = new Date();
CHour = CDate.getHours() // Current hour of System
if (CHour < 10) {
document.write("Just started...!")
}
else if (CHour < 11) {
document.write("Hungry!")
}
else if (CHour < 12) {
document.write("Ah, lunch-time!")
}
else if (CHour < 16) {
document.write("It is very hot!")
}
else {
document.write("It time to go home")
}
}
</script>
</head>
<body onload="greeting()">
</body>
</html>
Save the file with ...\Unit 3\Chapter 3\nestif.html and preview it in the browser as shown in Figure
3.5.
Solution Write the following code in Notepad editor and save as greatest.html.
<HTML>
<HEAD>
<TITLE>JavaScript Nested if-else condition Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Print greatest among three numbers
var num1 = 340;
var num2 = 420;
var num3 = 611;
if ((num1 > num2) && (num1 > num3))
{
document.write("The bigger value is : " + num1);
}
else
if ((num2 > num1) && (num2 > num3))
{
document.write("The bigger value is : " + num2);
}
else
document.write("The bigger value is : " + num3);
</script>
</BODY>
</HTML>
The statement is a multiway branch statement. It provides an easy way to dispatch execution to different
parts of your code based on the value of an expression. The syntax for the switch statement is:
switch (expression)
{
case (value1):
// Java statements;
break;
case (value2):
// Java statements;
break;
:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.75
case (value3):
// Java statements;
break;
:
default:
// Java statements;
}
Here,
x The expression must be of integer, or character type and each of the values specified in the case
statements must be of a type compatible with the expression.
x The value1, value2, value3, etc. can be any other int or char constant.
x If the expression matches the first case, value1, the statements, that are usually under value1, execute.
If the expression matches the second case, value2, the statements that are usually under value2
execute. If none of the case expressions matches that of the switch expression, the default case
block executes.
x A break statement in switch causes control to skip all the statements after it and jumps to the next
statement just after the switch block.
x There is no need to use break statement in default case, because default is the last case and so
the switch has to terminate after it.
x In a switch structure when the default clause is listed last, the break statement is not required.
x The default line is optional.
The examples of switch statements are:
x var grade = prompt("Enter your grade").toUpperCase();
switch (grade)
{
case 'A' : document.write("Secure more than 80%");
break;
case 'B' : document.write("Secure more than 70% and less than 80");
break;
case 'C' : document.write("Secure more than 60% and less than 70");
break;
case 'D' : document.write("Secure more than 50% and less than 60");
break;
default : document.write("Secure more than 50% and less than 60");
}
For example, to check for vowel characters, spaces and consonants, the switch structure is:
var ch = prompt("Enter your choice");
var vowels, spaces, consonants;
switch (ch)
{
case 'A' :
case 'a' :
case 'E' :
case 'e' :
case 'I' :
case 'i' :
case 'O' :
case 'o' :
case 'U' :
case 'u' : vowels++;
break;
case ' ' :
spaces++;
break;
default : consonants++;
break;
}
The switch statement can be used to combine cases and executed as one. To do this, you can type two or
more cases together.
In the above example, if the value of letter is either A, a, E, e, I, i, O, o, U or u then number of
vowels is incremented. If the value of letter is , then number of spaces is incremented. If none of these is true
then the default condition is executed, that is, the number of consonants is incremented.
<script type="text/javascript">
d=weekday(date)
Select Case d
Case 1
document.write("Sleepy Sunday")
Case 2
document.write("Monday again!")
Case 3
document.write("Just Tuesday!")
Case 4
document.write("Wednesday!")
Case 5
document.write("Thursday...")
Case 6
document.write("Finally Friday!")
Case else
document.write("Super Saturday!!!!")
End Select
</script>
</body>
</html>
Example Write the JavaScript code to enter the month number and display respective month name
and days.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.77
Solution Write the following code in Notepad editor and save as days.html.
<HTML>
<HEAD>
<title>switch...case example</title>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Variable hold the month number.
var mon = parseInt(prompt("Enter month no. (1-12): "));
var day = 0; // Month days
var cmonth;
switch (mon) {
case 1: day = 31;
cmonth = "January";
break;
case 2: day = 28;
cmonth = "February";
break;
case 3: day = 31;
cmonth = "March";
break;
case 4: day = 30;
cmonth = "April";
break;
case 5: day = 31;
cmonth = "May";
break;
case 6: day = 30;
cmonth = "June";
break;
case 7: day = 31;
cmonth = "July";
break;
case 8: day = 31;
cmonth = "August";
break;
case 9: day = 30;
cmonth = "September";
break;
case 10: day = 31;
cmonth = "October";
break;
case 11: day = 30;
cmonth = "November";
break;
case 12: day = 31;
cmonth = "December";
break;
default: cmonth = "Invalid input";
}
document.write("Your choice is: " + mon + " Month: " + cmonth + " and " + day + "
days" );
</script>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.78 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Save the file with ...\Unit 3\Chapter 3\days.html and preview it in the browser. If you enter the
month no. as 7, then it will display the details of month no. 7 as shown in Figure 3.6.
3RLQWVWR5HPHPEHU
SOLVED EXERCISES
1. What is a Boolean variable?
Ans. A variable is referred to as Boolean if it can hold a value that is either true or false.
2. What is a block?
Ans. A block is the simplest type of structured statement. Its purpose is simply to group a sequence of
statements into a single statement. The format of a block is:
{
statements
}
That is, it consists of a sequence of statements enclosed between a pair of braces, { and }.
3. What is an if statement? Give its syntax.
Ans. An if statement tells the computer to take one of the two alternative courses of action, depending on
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.79
whether the value of a given Boolean-valued expression is true or false. It is an example of a branching
or decision statement. if statement has the form:
if (Boolean-expression)
statement;
else
statement;
4. How can the switch statement be replaced with a series of if-else statements?
Ans. A switch statement can always be rewritten as a series of if-else statements by creating an if condition
for each case value in the switch. The statements associated with each case value are executed in the
appropriate if statement. It is very difficult to rewrite a switch statement that does not use a break
statement at the end of each case.
5 What is the purpose of default clause in a switch statement?
Ans. Default clause is used to handle the case when no match of any case in the switch statement is found.
6. What is the purpose of break statement in a loop?
Ans. Break statement is used to terminate the loop.
7. What is the purpose of break keyword while using Switch Case Statement ? Illustrate with the help of
an example.
Ans.. A break statement in switch causes control to skip all the statements after it and jump to the next
statement just after the switch block. For example:
switch (opt)
{
case 1: document.write("I am in case 1");
break;
case 2: document.write("I am in case 2");
break;
case 3: document.write("I am in case 3");
break;
default:
document.write("\nInvalid option selected");
}
8. The following is a segment of program.
var x = 1, y = 1;
if (n > 0) {
x = x + 1;
y = y 1;
}
What will be the value of x and y, if n assumes a value
(i) 1
(ii) 0?
Ans. (i) If n = 1, then x = 2 and y = 0
(ii) if n =0, then x = 1 and y = 1
9. Find the error in each of the following code segments and explain how to correct it.
switch (ctr) {
case 1:
document.write("The number is 1");
case 2:
document.write("The number is 2");
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.80 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
break;
default:
document.write("The number is not 1 or 2");
break;
}
Ans. Error: Missing break statement in the statements for the first case.
Correction: Add a break statement at the end of the statements for the first case. Note that this is not
necessarily an error if you want the statement of case 2: to execute every time the case1: statement
executes.
10. Give the output of the following code fragment:
when (i) opn = b (ii) opn = x (iii) opn = a
switch (opn) {
case 'a':
document.write("Platform Independent");
break;
case 'b':
document.write("Object Oriented");
case 'c':
document.write("Robust and Secure");
break;
default:
document.write("Wrong Input");
}
Ans. The output is:
(i) Object Oriented
Robust and Secure
(ii) Wrong Input
(iii) Platform Independent.
11. What will be the corresponding output of the following code segment if the Num value is 30.
switch(Num) {
case 10: document.write("Ten only"); break;
case 20: document.write("Twenty only");
case 30: document.write("Thirty only");
case 40: document.write("Forty only"); break;
default: document.write("Not enough money"); break;
}
Ans. The output is: ThirtyonlyForty only.
12. Write JavaScript statements to accomplish the following:
Test if the value of variable ctr is greater than 10. If it is, display Ctr is greater than 10.
Ans. The statement is:
if (ctr > 10)
document.write("Ctr is greater than 10");
13. Convert the following code segment using switch-case construct:
var num = parseInt(prompt('Enter any number'));
var txtRes;
if (num>=2 && num<=5)
txtRes = "Prime";
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.81
if(C != 200)
{
document.write(TEMP + " " + B + " " + C);
}
}
var M = 90;
Execute(M);
document.write(" " + M + "<br>");
M = 10;
Execute(M);
document.write(" " + M);
</script>
Ans. The output is (outpute.html):
190 280 100 90
110 120 100 10
19. Give the output of the following program:
<SCRIPT type="text/javascript">
function max(x, y)
{
if (x > y)
return(x);
else
return(y);
}
var A = 10, B = 13;
var fx = 0, sx = 0;
document.write("A = " + A + ", " + "B = " + B + "<br>");
fx = max(B, A)
document.write("Maximum is: " + fx);
</script>
Ans. The output is (outputf.html):
A = 10, B = 13
Maximum is: 13
20. Point the errors in the following code and write the correct script.
<SCRIPT type="text/javascript">
var A = 10;
var B = 6;
switch (A%B)
{
case 0;
document.write("The input is :")
break;
case 1:
document.write("The color is :")
break;
else
document.write("You didnt choose")
}
</SCRIPT>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.84 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
num = parseInt(num)
if (num > 0) {
alert(num + " is positive")
} else if (num < 0) {
alert(num + " is negative")
} else {
alert(num + " is zero")
}
</script>
</BODY>
</HTML>
REVIEW QUESTIONS
1. What is the difference between selection and repetition?
2. What is a block statement? How are block statements used in JavaScript programs?
3. What is the purpose of if statement? Describe the different forms of if statement.
4. Describe switch statement. What is the difference between if and switch statements?
5. What is the purpose of default clause in a switch statement?
6. Write the statements for the following situations:
(a) X is greater than equal to Y.
(b) X is not equal to Y.
(c) X is equal to Y.
(d) X is less than Y and X is less than Z.
(e) Either X is greater than Y or X is less than Z.
(f ) If X has a value greater than 20 then increment the value of the J by 1 otherwise decrement the value
by 2.
7. Using the JavaScript statement, answer the following :
(a) If statement to compare the value of an integer called sum against the value 65 and if it is less, print
the text string Sorry, try again.
(b) If total is equal to the variable good_guess, print the value of total, else print the value of good_guess
using if statement.
(c) If sum is equal to 10 and total is less than 20, print the text string incorrect. using if statement.
(d) If flag is 1 or letter is not an X, then assign the value 0 to exit_flag, else set exit_flag to 1.
if ((flag == 1) || (letter != X) )
exit_flag = 0;
else
exit_flag = 1;
8. Identify and correct the errors in each of the following. [Note: There may be more than one error in each
piece of code.]
If (yourAge >= 65);
document.write("Your age is greater than or equal to 65");
else
document.write("Your age is less than 65)";
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.86 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
9. Find the error for the following: [Note: There may be more than one error. The following code should
print whether integer nVal is odd or even:
switch (nVal %2) {
case 0:
document.write("Even integer");
case 1:
document.write("Odd integer");
}
10. What will be the output of the following program segment?
(a) var a = 3;
a = a + 1;
if (a > 5)
document.write("" + a.toString());
else
document.write("" + a.toString() + 5);
(b) What will be the corresponding outputs of the following code fragment if the input is:
(i) a (ii) c (iii) d (iv) h (v) b
var ch = prompt('Enter choice');
switch (ch)
{
case 'a' : document.write("It is a. <br>");
case 'b' : document.write("It is b. <br>");
case 'c' : document.write("It is c. <br>");
break;
case 'd' : document.write("It is d. <br>");
break;
default : document.write("Not a b c d. <br>");
}
11. Write equivalent switch statement for the following:
(a) if (code == 's')
document.write("season is summer ");
else
if (codee == 'r')
document.write("season is rainy");
else
if (code == 'w')
document.write("season is winter ");
else
document.write("wrong code");
(b) if (a == 1)
x++;
else
if (a == 2)
y++;
else
if (a == 3)
z++;
else
w++;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Branchin in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.87
Write a JavaScript program based on the above criteria, to input amount of purchase and the type of
purchase (Laptop or Desktop) by a customer. Compute and print the net amount to be paid by a
customer along with his name and address.
(Hint: discount = (discount rate / 100) * amount of purchase Net amount = amount of purchase
discount).
16. Write a JavaScript program that asks the user to enter two integers, obtains the numbers from the user
and displays the larger number followed by the words is larger in an alert message dialog. If the
numbers are equal, print the message These numbers are equal.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.88 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
17. Write a JavaScript program that reads an integer and determines and prints whether it is odd or even
(Hint. Use the modulus operator. As even number is a multiple of 2. Any multiple of 2 leaves a reminder
of zero when divided by 2.)
18. Write a JavaScript program that takes the number of seconds as input. The program converts this value
to the corresponding number of hours, minutes, and seconds and displays these values.
19. Write a JavaScript program that accepts the length and width of a rectangle as inputs. The program
should calculate the rectangles area and perimeter, and display the values rounded to the nearest length
of a foot.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.89
Looing in JavaScript
4
4.1 INTRODUCTION
Looping is also called as repetition structure. A repetition structure allows the programmer to perform an action
that to be repeated until the given condition is true. Figure 4.1 is the general form of a loop statement in most of
the programming languages.
JavaScript supports three types of looping statements:
x A while loop, in which the loop-controlling Boolean
expression is the first statement in the loop.
x A do-while loop, in which the loop-controlling `
Boolean expression is the last statement in the loop.
x A for loop, which is usually used as a concise format
in which to execute loops.
conditional code
In JavaScript, the above three loops are specifically `
`
3.89
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.90 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
`
x It contains a Condition called Boolean expression within
parentheses.
x The program statements are called the body of the loop, ` condition
if condition
which can be a single statement or a block of statements is false
surrounded by curly brackets.
`
if condition
Figure 4.2 shows the execution style of a while loop. is true
`
The while loop is also called the entry-controlled loop because
in this loop the condition is checked first and if that condition is true, conditional code
then the block of statement in the loop body will be executed.
`
Figure 4.2 while loop structure.
Example Write the JavaScript code to enter a number in a text box and display all the numbers for 1
to till that number using while loop.
Solution Write the following code in Notepad editor and save as number.html.
<HTML>
<html>
<head>
<title>Displaying natural numbers</title>
</head>
<SCRIPT type="text/javascript">
function Display_Numbers()
{
var number = frm.txt.value;
var ctr = 1;
document.write("Numbers are...<br>");
while( ctr <= number ) {
document.write(ctr + "<br>");
ctr++;
}
}
</script>
<form name="frm">
Enter a number: </td>
<input type=text name="txt" size="12"></td>
<input type="button" value="Display" onclick="Display_Numbers()">
</form>
</html>
Open the number.html file in IE, and see the output window as shown in Figure 4.3 on the next page.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.91
The while loop can accept expressions and not just conditions. The following are all legal expressions:
x while (x = x + 1)
x while (n)
x while (count += i)
For these types of expressions, when the result of x = x + 1, n or count += i, evaluates to 0, then only the
while condition will fail and the loop will exit. Some other examples of while loop are:
var num = 5;
while (num != 0)
{
document.write(num + "<br>");
num--;
}
This loop prints a num starting from 5 and going down to 1, until the num becomes 0 which is the
terminating condition of the loop.
while (i++ < n);
this loop counts i up to n.
var num = 5;
while (num)
{
document.write(num + "<br>");
num;
}
Here, the while (num) is same as saying while (num != 0).
Let us study a sample logic to find the factorial of a number using while loop (fact.html):
// Factorial function
function factorial(N)
{
var num = 1;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.92 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
var fact = 1;
while (num <= N)
{
fact = fact * num;
num++;
}
return (fact);
}
N = 10;
document.write("The factorial of 10 is " + factorial(N));
From the above factorial logic, the counter num increases till N and multiply with fact for finding the
factorial of N. When the above steps are executed it will find the factorial as:
The factorial of 10 is 3628800.0
do if condition
{ is true
condition
program statements;
} while (Condition);
do {
document.write(N + " ");
N--;
}while (N >= 1);
</script>
</BODY>
</HTML>
Open the rnum.html file in IE, and the see the output window as shown in Figure 4.5.
`
The expression that alters or updates the loop control variable.
Each part is separated with a semicolon (;). Figure 4.6 shows the execution
condition False
style of for loop. evaluated
For example:
`
initializing loop Checking Incrementing loop
control variable condition control variable initialization
`
`
`
increment
for ( ctr = 1 ; ctr <= 10 ; ctr = ctr + 1 )
`
document.write(ctr + " ");
Figure 4.6 for loop
execution style.
From the above example, when you execute the for statement, you will see 10 natural numbers in jTextArea1
as given below:
1 2 3 4 5 6 7 8 9 10
for (ctr = 1 ;
which initializes the value of ctr to 1. The for loop continues whilst the condition ctr <= 10 is evaluated as
true. As the variable ctr has just been initialized to 1, this condition is true and so the program statement:
document.write(ctr + " ");
is executed, which prints the value ctr to the screen, followed by a space character. Next, the remaining
statement of the for is executed:
ctr = ctr + 1;
which adds one to the current value of ctr. Control now passes back the conditional test:
is executed. ctr is incremented again, the condition is re-evaluated and this continues until ctr reaches a value
of 11. When this occurs, the conditional test:
ctr <= 10;
Eventually, when ctr is not less than or equal to 10, the for loop ends, and the program continues with any
statements that follow the for loop.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.95
As a final example, lets say that we want to use a for loop that prints out just the even numbers between
2 and 20, that is: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. There are several ways to do this. Just to show how even a very
simple problem can be solved in many ways, here are four different solutions given below:
1. // There are 10 numbers to print.
// Use a for loop to count 1, 2, ..., 10. The numbers we want to print are:
// 2*1, 2*2, ... 2*10.
for (N = 1; N <= 10; N++)
{
document.write( 2*N + " " );
}
4. // Irritate the professor with a solution that follows the letter of this silly
// assignment while making fun of it.
for (N = 1; N <= 1; N++)
{
document.write("2 4 6 8 10 12 14 16 18 20");
}
Example Write the JavaScript code using function to find the sum of first 10 natural numbers.
Solution Write the following code in Notepad editor and save as nsum.html.
<HTML>
<HEAD>
<TITLE>Sum of natural numbers</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var answer;
// Function to find the sum of natural numbers
function sum_number()
{
var result = 0; // hold the result
var N = 10, ctr;
Open the nsum.html file in IE, and the see the output window as shown in Figure 4.7
Open the mtable.html file in IE, and the see the output window as shown in Figure 4.8 on the next page.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.97
JavaScript provides three branching statements break, continue and return. In this section we will learn break,
continue and uses of label with break and continue. The return statement will be discussed in the next chapter.
7KHEUHDN6WDWHPHQW
The break statement in JavaScript is used to break the loop and transfer control to the line immediately
outside of loop. In JavaScript, the break statement has three uses:
x First, as you have seen, it terminates a statement sequence in a switch statement.
x Second, it can be used to exit a loop.
x Third, it can be used as a civilized form of goto.
Instead of exiting an entire program, we can use the break statement to exit the current loop. The format
of break is:
break;
However, break typically appears in the body of a while or do-while loop so that we can leave the loop
early.
Example Write a JavaScript program to test the break statement while finding your school name for
five times.
Solution Write the following code in Notepad editor and save as break.html.
<HTML>
<HEAD>
<TITLE>JavaScript break loop Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Printing your school name five time
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.98 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
var x = 1;
while (true)
{
document.write("CBSE Schools<br>");
if (x >= 5)
{
document.write("Loop breaked");
break;
}
x++;
}
</script>
</BODY>
</HTML>
Open the break.html file in IE, and the see the output window as shown in Figure 4.9.
From the above example, the while loop will execute and print the school name five time. But each time, the
variable x is checked till less than 5. When the variables value will be more than 5, then the while loop will be
terminated.
Example Write a JavaScript program to test the break statement while finding the sum of odd numbers
till the sum reaches 50.
Solution Write the following code in Notepad editor and save as break1.html.
<HTML>
<HTML>
<HEAD>
<TITLE>JavaScript break loop Example</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Printing sum of odd numbers using break statement
var x = 1;
var xoddsum = 0;
var xtmp = 0;
var lastx = 0;
while (true)
{
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.99
xtmp = xoddsum + x;
if (xtmp > 50)
break;
xoddsum += x;
x += 2;
}
lastx = x;
document.write("The sum of odd numbers before " + lastx + " is: " + xoddsum);
</script>
</BODY>
</HTML>
Open the break1.html file in IE, and the see the output window as shown in Figure 4.10.
x The test clause of this while is true, which you might well suspect is always true.
x This means that there is no way for this loop to terminate unless it is forced to do so by a break
statement.
x In statement xtmp = xoddsum + x, a temporary sum is formed in the variable xtmp.
x This sum is tested against the limit 50 in statement if (xtem > 50).
x If xtmp exceeds it then the break statement is executed and the loop terminates.
x If the test fails (xtmp is still less than 50) then the real sum is formed in statement xoddsum += x;
x Next, x is incremented by 2.
x Similarly, it keeps adding up numbers, odd numbers in fact, until the sum is less than 50.
x When the next sum would have exceeded 50, the if test succeeds, the break is executed and the flow of
control of the program reaches the first statement after the entire while block, i.e., lastx = x;
x This statement saves the last value of x in a different variable lastx.
x You can easily determine for yourself that the value of lastx must be 15. Since 1 + 3 + + 13, while
1 + 3 + + 13 = 50 exactly, while 1 + 3 + + 15 = 64 > 50.
The continue statement is used to escape current execution (iteration) and transfer control back to the start
of the loop. However, instead of jumping out of the loop altogether, it jumps back to the beginning of the loop
and continues with the next iteration. The format of continue is:
continue;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.100 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
{
Statements that
document.write("" + i + " "); comes under continue
if (i % 2 == 0)
continue;
document.write("" + i + " ");
`
This is similar to the previous break statement. The numbers 1 through 4 print out first. The continue
statement executes on the fifth time through the loop because count is equal to 5, which causes the number 5
not to be printed. Unlike the break statement, however, the for loop continues and the numbers 6 through 10
print.
Example Write a JavaScript program to demonstrate the continue statement for above example.
Solution Write the following code in Notepad editor and save as continue.html.
<HTML>
<HEAD>
<TITLE>JavaScript continue statement</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Printing number using continue statement
for (var count = 1; count <= 10; count++)
{
if (count == 5)
{
document.write("Continue without 5<br>");
continue;
}
document.write(count);
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.101
Open the continue.html file in IE, and the see the output window as shown in Figure 4.12.
4.6 ARRAYS
An array is a way to hold more than one value at a time. It's like a list of items. An array variable does not actually
store the arrayit is a reference variable that points to an array object. It12345678901234567890
can be defined as one-dimensional or
multi-dimensional arrays. 12345678901234567890
12345678901234567890
What is an array?
12345678901234567890
2QH'LPHQVLRQDO $UUD\ 12345678901234567890
12345678901234567890
An array is a collection of
12345678901234567890
homogeneous data elements
12345678901234567890
A one-dimensional array is a list of variables that are of the same type
12345678901234567890
described by a single name, and
12345678901234567890
and are referenced through a common name. An individual variable in each element in an array is
the array is called an array element. Arrays provide a convenient method 12345678901234567890
12345678901234567890
referred by the array name with
12345678901234567890
the subscript or index enclosed
to handle groups of related data. Let us see Figure 4.13 to explore more
about array: 12345678901234567890
12345678901234567890
in square brackets [ ] .
Num - Name
12345678901234567890
Indexes
of the array
Num[0]
123456789012
4
123456789012
123456789012
Array objects Num[1] 12
123456789012
with index
123456789012
123456789012
position Num[2] 2
Num[3] 34
Num[4] 17
Here, the numbers are called index values or subscripts to the array. The term subscript is used because
as a mathematical sequence, the array would be written with subscripts: a0, a1, a2, .... These numbers locate the
elements position within the array, thereby giving direct access into the array.
As we know that every array object holds space in memory. Like int, float, char, the linear list elements also
hold space in the memory. They take space as memory address according to their individual data values. Let us
consider our previous example of array Num. Each index position creates a different location in memory with
same individual object of array Num.
For example if Num[0] holds a position at memory address 4022, then Num[1] will hold at 4024, Num[2]
will hold at 4026, and so on as shown in Figure 4.14.
123456789012 Num[0]
`
4 4022
123456789012
123456789012
12345678
12345678
Array objects Num[1]
123456789012 12345678
`
12 4024
Memory
123456789012
with index 12345678
123456789012 Num[2]
` 12345678
address
123456789012
position 2 4026
Num[3]
`
34 4028
Num[4]
`
17 4030
where, array_name is the name of the array and [item1, item2, ...] are the array elements. For example,
var mAr1 = [21, 63, 75, 43, 19] // an array with 5 elements
var mAr2 = [5] // an array with 1 element
You can also create an array using JavaScript constructur Array(). The Array() constructor syntax has
three different forms:
x If you call the constructor with two or more arguments, the arguments initialize the array elements.
x If you only supply one argument to the Array constructor, the argument initializes the length of the
new array; the new arrays elements are not initialized.
x Finally, if you call the constructor without arguments, the new arrays length is set to zero, and its
elements are not initialized.
Here are examples:
var myAr1 = new Array(21, 63, 75, 43, 19) // an array with 5 elements
var myAr2 = new Array(100) // an empty array of length 100
var myAr3 = new Array() // an empty array of length 0
var Num = new Array(5) // an empty array of length 5
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.103
The new keyword is the way of telling JavaScript that the function
N ote
to the right of it is an object constructor and JavaScript treats it
accordingly. The subscript of the array
Let us look at the last array declaration Num which creates an begins with zero and ends with
array of 5 elements. Also, according to Figure 4.15, the Num array tells size-1. The rules for naming an
the interpreter that array are same as for other
variables but the size of the
x Num is the name of the array.
array will always be positive
x It is one-dimensional (linear). integer constant or an
x The number of elements in the array is 5, i.e. its size is 5. But it expression that evaluates a
can add or delete elements dynamically. positive integer constant at
x Array Num allocates a contiguous address in memory block. compilation time.
the valid range of subscript is 0 to 4, i.e. lower bound is 0 and upper bound is the value one less than is specified
by the dimension specified in the declaration statement.
To access an element of an array, the subscripted variables are used which are formed by affixing each
subscript in brackets to the name of an array.
The first element of array named Num is accessed as Num[0], third as Num[2], ... , and the last element as
Num[4]. In general, the ith element is num[i1].
To initialize values to the various positions in an array, you do it in the normal way:
Num[0] = 4;
Here, a value of 4 is being assigned to position 0 in the array called Num. Again, the square brackets [ ] are
used to refer to each position. If you want to assign a value of 12 to array position 1, the code would be this:
Num[1] = 12;
stud_age[0] = 13 1234567890
of the array
1234567890
stud_age[0]1234567890
stud_age[1] = 15 13
stud_age[2] = 14 1234567890
stud_age[3] = 13
1234567890
stud_age[1]1234567890
15
stud_age[4] = 15 1234567890
stud_age[2]1234567890
initializes 5 different ages into stud_age array as shown in Figure
1234567890
14
1234567890
stud_age[3]1234567890
4.16.
1234567890
13
1234567890
stud_age[4]1234567890
15
Example Write a JavaScript to assign five friends names and print them on the screen using array.
Solution Write the following code in Notepad editor and save as array01.html.
<HTML>
<HEAD>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.105
<TITLE>JavaScript Array</TITLE>
</HEAD> N o te
<BODY>
<SCRIPT type="text/javascript"> When you use a loop for
// Print five names using array processing elements of an
var FriendNames = new Array(5); array, loop counters value must
FriendNames[0] = "Mr. Vikash" be 1 less than the size of the
FriendNames[1] = "Ms. Sangeeta"
FriendNames[2] = "Mr. Sudhir"
array. All array subscripts begin
FriendNames[3] = "Ms. Sneha" with 0, not position 1.
FriendNames[4] = "Mr. Ranvhir"
document.write("The names are : <br>");
document.write("<hr>");
for(var count = 0; count < 5; count++)
document.write(FriendNames[count] + "<br>");
</script>
</BODY>
</HTML>
Open the array01.html file in IE, and see the output window as shown in Figure 4.18.
JavaScript has some usable methods which help to process array elements. These are:
concat(). This method is used to joins two or more arrays, and returns a copy of the joined arrays.
The syntax is:
array1.concat([item1[, item2[, . . . [, itemN]]]])
For example
<SCRIPT type="text/javascript">
var Week1 = ["Sunday", "Monday", "Tuesday"];
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.106 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
join(). This method joins the elements of an array into a string, and returns the string. The elements
will be separated by a specified separator. The default separator is comma (,). The syntax is:
arrayObj.join([separator])
For example
<script language = "JavaScript">
var Weeks = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday");
var WeekDays = Weeks.join()
document.write("Week days are: " + WeekDays);
var NWeekDays = Weeks.join("-") // Using seperator
document.write("<br>");
document.write("Week days are: " + NWeekDays);
</script>
sort(). This method is used to sort the items of an array in its own place. No new array is created. The
sort order can be either alphabetic or numeric, and either ascending (up) or descending (down). The
syntax is:
arrayObj.sort()
For example
<SCRIPT type="text/javascript">
var Weeks = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday");
Weeks.sort();
document.write("Week days are: " + Weeks);
document.write("<br>");
var EMarks = new Array(45.6, 67.6, 87.5, 34.5, 73.5, 77.6);
EMarks.sort();
document.write("Marks: " + EMarks);
</script>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.107
reverse(). This method is used to reverses the order of the elements in an array in its own place. No
new array is created. The syntax is:
arrayObj.reverse()
For example
<SCRIPT type="text/javascript">
var Weeks = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday");
Weeks.reverse();
document.write("Week days are: " + Weeks);
document.write("<br>");
var EMarks = new Array(45.6, 67.6, 87.5, 34.5, 73.5, 77.6);
EMarks.reverse();
document.write("Marks: " + EMarks);
</script>
When you open the array02.html file in a browser, you will see array num is initialized with 10 elements
and its positional values are printed as shown below:
The element at 0 position is : 8
The element at 1 position is : 0
The element at 2 position is : 11
The element at 3 position is : -14
The element at 4 position is : 17
The element at 5 position is : 22
The element at 6 position is : 14
The element at 7 position is : 10
The element at 8 position is : 19
The element at 9 position is : 25
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.108 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Example Write a program to find the average of 6 students English marks in an initialized array
EMarks.
Solution Write the following code in Notepad editor and save as array03.html.
<HTML>
<HEAD>
<TITLE>Average of students marks</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var s_name = "DAV Model School"
var EMarks = new Array(45.6, 67.6, 87.5, 34.5, 73.5, 77.6);
var average = 0;
// Calculate the total of scores
for(ctr = 0; ctr < 6; ctr++)
average = average + EMarks[ctr];
// calculate the average
average = average / 6;
document.write("At " + s_name + ". Your class average is : " + average);
</script>
</BODY>
</HTML>
When you will execute the program, you will see the school name and class average as shown below:
At DAV Model School. Your class average is : 64.38333333333333
6RUWLQJDQ$UUD\ZLWKRXWXVLQJVRUWPHWKRG
A solution to the sorting problem is the bubble sort algorithm, which re-arranges the values by iterating over
the list multiple times, causing larger values to bubble to the top or end of the list.
The basic idea underlying the bubble sort is to pass through the file sequentially several times. If Num is
an array, each pass consists of comparing each element in the file with its successor (Num[i] with Num[i +
1]) and interchanging (swap) the two elements if they are not in proper order.
Consider Figure 4.19:
10 51 2 18 4 31 13 5 23 64 29
0 1 2 3 4 5 6 7 8 9 10
Figure 4.19 Unsorted values in an array (Num).
If you want the array in ascending order sequence, the following comparisons are made on the first pass:
Num[0] with Num[1] (i.e., 10 with 51) no interchange
Num[1] with Num[2] (i.e., 51 with 2) interchange
Num[2] with Num[3] (i.e., 51 with 18) interchange
Num[3] with Num[4] (i.e., 51 with 4) interchange
Num[4] with Num[5] (i.e., 51 with 31) interchange
Num[5] with Num[6] (i.e., 51 with 13) interchange
Num[6] with Num[7] (i.e., 51 with 5) interchange
Num[7] with Num[8] (i.e., 51 with 23) interchange
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.109
Figure 4.20 illustrates the swaps performed during the first pass of the algorithm when applied to an array
(Num) containing 11 integer values.
Figure 4.20 After first interchange which places 64 in its correct position.
In Figure 4.20, black boxes represent values being compared; arrows indicate exchanges. Notice that after
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.110 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
this first pass, the largest element (in this case 64) is in its proper position within the array. In general, Num[n-
i+1] will be in its proper position after iteration i. The method is called the bubble sort because each number
slowly bubbles up to its proper position.
The efficiency of the bubble sort algorithm only depends on the number of keys in the array and is
independent of the specific values and the initial arrangement of those values.
To determine the efficiency:
x You must determine the total number of iterations performed by the inner loop for a sequence containing
n values.
x The outer loop is executed n 1 times since the algorithm makes n 1 passes over the sequence.
x The number of iterations for the inner loop is not fixed, but depends on the current iteration of the outer
loop.
x On the first pass over the sequence, the inner loop executes n 1 times; on the second pass, n 2
times; on the third, n 3 times, and so on until it executes once on the last pass.
x The total number of iterations for the inner loop will be the sum of the first n 1 integers.
After the second pass the array will place the second largest element in its position as shown in Figure
4.21 as:
Figure 4.21 After second interchange which places 51 in its correct position.
Notice that 51 has now found its way to the second highest position. Since each iteration places a new
element into its proper position, a sequence of n elements requires no more than n 1 iterations. After completion
of the outer loop execution (i.e., n 1 times), the final sorted list of ascending order list will be stored in the array
as shown in Figure 4.22.
Example Write a program to accept or assign any number of numbers into an array, and arrange all
the elements in ascending order using bubble sort method.
Solution Write the following code in Notepad editor and save as array04.html.
<HTML>
<HEAD>
<TITLE>Sorting array elements</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Sorting elements
var num = new Array(10, 51, 2, 18, 4, 31, 13, 5, 23, 64, 29);
var i, j, temp;
N = num.length;
document.write("The array initialized values are : ");
for (i = 0; i < N; i++)
document.write(num[i] + " ");
document.write("<br>");
for (i = 0; i < N; i++)
for (j = 0 ; j < N-1; j++)
if (num[j] > num[j+1]) {
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
document.write("The sorted values are : ");
for (i = 0; i < N; i++)
document.write(num[i] + " ");
</script>
</BODY>
</HTML>
When you will open the array04.html file in a browser like IE, you will see bubble sort elements as
shown in Figure 4.23.
len = num.length;
var max = num[0]; // Initialize the default value to max and min
var min = num[0];
for (var i = 0; i < len; i++)
{
if (num[i] > max) max = num[i];
if (num[i] < min) min = num[i];
}
document.write("The array elements are : ");
for (i = 0; i < len; i++)
document.write(num[i] + " ");
document.write("<hr>");
document.write("The maximum value in the list is : " + max + "<br>");
document.write("The minimum value in the list is : " + min);
</script>
</BODY>
</HTML>
When you will open the array05.html file in a browser like IE, you will see the maximum and minimum
value as shown in Figure 4.24.
JavaScript automatically passes arrays to methods using simulated call-by-reference. The called methods can
modify the element values in the callers, the original arrays. The values of the name of the array are the address
of the first element of the array. Because the starting address of the array is passed, the called method knows
precisely where the array is stored. Therefore, when the called method modifies array elements in its method
body, it is modifying the actual elements of the array in their original memory locations.
To pass an array argument to a method, specify the name of the array without any brackets. For example,
if an array hourlyTemp has been declared as:
var hourlyTemp = new Array();
passes array hourlyTemp and its size to method modifyArray(). For example, the method header for method
modifyArray() might be written as:
indicating that modifyArray() accepts to receive an array of integers in parameter b and the number of array
elements in parameter arraySize.
Example Write a program to pass an initialized array and an individual array element into a method
and multiply each array element by 4 and display it.
Solution Write the following code in Notepad editor and save as array06.html.
<HTML>
<HEAD>
<TITLE>JavaScript Array</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to pass the array by reference
function modifyArray(NewArray, N)
{
document.write("The modified array elements are : ");
for (i = 0; i < N; i++)
document.write(Num[i] * 4 + " ");
}
var Num = new Array(20, 18, 13, 24, 9, 25);
xlen = Num.length;
document.write("The original array elements are : ");
for (i = 0; i < xlen; i++)
document.write(Num[i] + " ");
document.write("<hr>");
modifyArray(Num, xlen)
</script>
</BODY>
</HTML>
When you will open the array06.html file in a browser like IE, you will see pass-by-reference techniques
of array elements to a method output as shown in Figure 4.25.
<HEAD>
<TITLE>Second maximum and minimum in an array</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Function to find second largest element
function SecondLargest(Num, N) {
var m, m2;
if (Num[0] > Num[1]) {
m = Num[0];
m2 = Num[1];
} else {
m = Num[1];
m2 = Num[0];
}
for (x = 2; x < N; x++) {
if (Num[x] > m2) {
if (Num[x] > m) {
m2 = m;
m = Num[x];
} else
m2 = Num[x];
}
}
document.write("The second largest element is: " + m2);
}
// Function to find second smallest element
function SecondSmallest(Num, N) {
var m, m2;
var m, m2;
if (Num[0] < Num[1]) {
m = Num[0];
m2 = Num[1];
} else {
m = Num[1];
m2 = Num[0];
}
for (x = 2; x < N; x++) {
if (Num[x] < m2) {
if (Num[x] < m) {
m2 = m;
m = Num[x];
} else
m2 = Num[x];
}
}
document.write("The second smallest element is: " + m2);
}
var Num = new Array(100, 20, 450, 143, 321, 241, 325, 76, 150, 120);
Num.sort();
len = Num.length;
document.write("Original array elements are : ");
for (i = 0; i < len; i++)
document.write(Num[i] + " ");
document.write("<hr>");
SecondLargest(Num, len);
document.write("<hr>");
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.115
SecondSmallest(Num, len);
</script>
</BODY>
</HTML>
When you will open the array07.html file in a browser like IE, you will see the second maximum and
minimum values as shown in Figure 4.26.
3RLQWVWR5HPHPEHU
1. A repetition structure specifies that an action is to be repeated while some condition remains
true.
2. The format for the while repetition structure is:
while (condition)
Statements;
3. A do statement executes its loop body at least once.
4. The do-while repetition structure tests the loop-continuation condition at the end of the loop,
so the body of the loop will be executed at least once. The format for the do-while structure is:
do
statement
while (condition);
5. A for statement is usually used when a loop is executed a set number of times.
6. The for repetition structure handles all the details of counter-controlled repetition. The general
format of the for structure is:
for (expession1; expression2; expression3)
statement
where expression1 initialized the loops control variable, expression2 is the loop-continuation
condition and expression3 increments or decrements the control variable.
7. A break statement is necessary at the end of each case alternative in a switch statement to
jump to the end of the switch.
8. The break statement, when executed in one of the repetition structures (for, while and do-
while), causes immediate exit from the structure.
9. The continue statement, when executed in one of the repetition structures (for, while and do-
while), skips any remaining statements in the body of the structure and proceeds with the test
for the next iteration of the loop.
10. An array is a variable containing several homogeneous data types.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.116 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
SOLVED EXERCISES
1. What is the use of while statement?
Ans. A while statement allows a program to execute a statement many times.
2. What is body of the loop?
Ans. The set of statements repeating again and again is called the body of the loop.
3. What is a for statement?
Ans. The for statement encloses one or more JavaScript statements that form the body of the loop. The
statements in the for loop repeat continuously a certain number of times.
4. What is the difference between the break and continue statements?
Ans. A break statement will terminate the execution of the body of the switch or loop. A continue statement
begins the next iteration of the loop in which it is contained.
5. Differentiate between selection statement and looping statements?
Ans. In selection statement, a particular statement is selected from the group of statements, while in the
looping statement, group of statements will be executed number of times.
6. What are the three expressions given in the for statement?
Ans. The three expressions given in the for loop are: initial value, final value and incremented / decremented
value.
7. How will you get out of a loop?
Ans. We can get out of the loop using the break statement.
8. What is the use of continue statement in JavaScript?
Ans. We use the continue statement when data in the body of the loop is bad, out of bounds or unexpected.
Instead of acting on the bad data, we might want to return to the top of the loop to get another data
value.
9. How does the while loop execution occur?
Ans. The while loop execution first examines the Condition. If the Condition is true, then it executes the
Statement. After executing the Statement, the Condition is checked again. As long as the Condition is
true, it will keep on executing the Statement.
10. Differentiate between while and do-while loop.
Ans. The differences are:
x A while loop checks that the condition is true before executing the loop and continues to execute
the loop until the condition becomes false whereas a do-while loop executes the loop first and then
checks the condition to see if it should execute again.
x A while loop is executed zero or more times whereas a do-while loop will always execute at least one
time.
11. State the difference between entry controlled loop and exit controlled loop.
Ans. In entry controlled loop, the test condition is checked first and if that condition is true then the block of
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.117
statement in the loop body will be executed, while in exit controlled loop the body of loop will be
executed first and at the end the test condition is checked, and if condition is satisfied then the body of
the loop will be executed again. For example:
while (Condition)
{
program statements;
}
is in entry controlled loop and
do
{
program statements;
} while (Condition);
is an exit controlled loop.
12. What is an array? How does it differ from ordinary variables?
Ans. An array is a collection of variables of the same type under one name. Arrays are defined in the same
manner as ordinary variables, except that each array name must be accompanied by a size specification
(i.e. the number of elements).
13. What is subscript?
Ans. The element number in [ ] is called subscript.
14. What is the other name for subscript?
Ans. Indices.
15. What is the purpose of subscript in an array?
Ans. The term subscript is used because as a mathematical sequence, an array would be written with
subscripts 0, 1, 2, 3. These numbers locate the elements position within the array, thereby giving direct
access to the array.
16. Which element is num[9] of the array num?
Ans. num[9] is the 10th element of the array num.
17. If an array Ar = [1, 9, 8, 5, 2];[ICSE 2008]
(i) What is Ar.length?
(ii) What is Ar[2]?
Ans. (i) The Ar.length() is 5.
(ii) The Ar[2] is 8.
18. Write an appropriate for or while loop for the situations described below:
(a) A loop is to be repeated 20 times.
(b) A loop is to be repeated 100 times, except the loop is to be terminated if the value of the variable P
becomes 50.
(c) A loop is to be processed till 200 starting from 100. Print all even numbers between the loop.
Ans. (a) for (i = 0; i< 200; i++)
(b) for (P = 0; i< 100; p++)
if (P == 50)
break; # Terminates the loop
(c) ctr = 100
while (ctr <= 200)
System.out.println (ctr);
ctr+=2;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.118 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
19. Write a JavaScript statement or a set of JavaScript statements to accomplish the following:
Sum of odd integers between 1 and 100 using a for structure. Assume the integer variable N and ctr
have been declared.
Ans. Sum = 0;
for (int ctr = 1; ctr <= 100; ctr += 2)
Sum += ctr;
20. Point the errors in the following JavaScript code and write correct script.
<SCRIPT type="text/javascript">
var sum=0;
while (c <10 step 2)
{
if c%3 == 0
sum = sum + c;
c++;
}
window.write(sum);
</SCRIPT>
Ans. The errors are:
<SCRIPT type="text/javascript">
var sum=0;
while (c <10 step 2) // Error 1, Error 2
{
if (c%3 == 0) // Error 3
sum = sum + c;
c++;
}
window.write(sum); // Error 4
</SCRIPT>
Where,
x Error 1. The while condition does not support the step clause. It must be a condition: while (c < 10)
x Error 2. The variable c must be declared and initialized.
x Error 3. The condition of if statement must be enclosed within parenthesis, i.e., if (c%3 == 0)
x Error 4. The JavaScript, to produce the output, write Document.Write instead of Window.Write.
The correct JavaScript code is (outputh.html):
<SCRIPT LANGUAGE = "JavaScript">
var sum=0;
var c = 0;
while (c <10)
{
if (c%3 == 0)
sum = sum + c;
c++;
}
document.write(sum);
</SCRIPT>
21. Give the output of the following code:
<SCRIPT type="text/javascript">
var Comment = " ";
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.119
var Remainder = 0;
var Exitno = 3;
var Check = 27;
for (count = 1; count <= 3; count++)
{
Remainder = Check % count;
if (Remainder == Exitno)
{
break;
}
Comment = Check + "divided by " + count + " leaves a remainder of " + Remainder;
document.write(Comment + "<br>");
}
</SCRIPT>
Ans. The output is (outputi.html):
27divided by 1 leaves a remainder of 0
27divided by 2 leaves a remainder of 1
27divided by 3 leaves a remainder of 0
22. Write the output of the following JavaScript program:
<SCRIPT type="text/javascript">
var a = 10, b = 8;
for (var i = 0; i <= a; i++)
document.write(i + " ");
for (var j = 0; j <= a; j++)
document.write(j + " ");
b = a;
++a;
b++;
document.write(a + "<br>" + b + "<br>" + b);
</script>
Ans. The output is (outputj.html):
0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 11
11
11
23. Rewrite the below given program using JavaScript for ( ) loop:
<SCRIPT type="text/javascript">
var i, sum = 0, i = 1;
while (i <= 10)
{
sum = sum + i;
i++;
}
document.write(sum);
</script>
Ans. The code using for () loop is:
<SCRIPT type="text/javascript">
var i, sum = 0;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.120 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
c=c-2;
} while (c>=10);
30. Given the output of the following code fragment:
var i;
for(i = 1, j = i + 10; i < 5; i++, j = i * 2) {
document.write("i= " + i + " j= " + j + "<br>");
}
Ans. The output is:
i = 1 j = 11
i=2j=4
i=3j=6
i=4j=8
31. Identify and correct the errors in each of the following:
while (ctr <= 5) {
table += ctr;
++ctr;
Ans. Error: Missing the closing right curly brace of the while body.
Correction: Add a closing right brace after the statement ++ctr;
32. Find the error in each of the following code segments and explain how to correct it.
a = 1;
while (a <= 10);
a++;
}
Ans. Error: The semicolon after the while header causes an infinite loop and there is a missing left brace.
Correction: Replace the semicolon by a { or remove both ; and the }.
33. Find the error in each of the following code segments and explain how to correct it.
for (x = .1; y != 1.0; y+= .1)
document.write(x);
Ans. Error: Using a floating-point number to control a for repetition structure may not work because floating-
point numbers are represented approximately by most compilers.
Correction: Use an integer and perform the proper calculation in order to get the value you desire.
for (x = 1; y != 10; y+= 1)
document.write(x);
34. What is wrong with the following while repetition structure?
while (x >= 0)
Sum += x;
Ans. The value of the variable x is never changed in the while structure. Therefore, if the loop-continuation
condition (x >= 0) is true, an infinite loop is created. To prevent the infinite loop, x must be decremented
so that it eventually becomes less than 0.
35. Find the error in each of the following code segments and explain how to correct it. The following code
should print the value from 1 to 10 in a web browser.
ctr = 1;
while (ctr < 10)
document.write(ctr++);
Ans. Error: Improper relational operator used in the while repetition-continuation condition.
Correction: Use <= rather than < or change 10 to 11.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.123
36. Analyse the following program segment and determine how many times the loop will be executed and
what will be the output of the program segment?
var p = 200;
while(true) {
if (p < 200)
break;
p = p - 20;
}
document.write(p);
Ans. The loop will execute 6 times and the output is: 180
37. Rewrite the following program segment using while instead of for statement.
var f=1, I;
for (i=1;i<=5;i++) {
f*=i;
document.write(f);
}
Ans. The code is:
var f=1, i;
i= 1;
while (i<=5) {
f*=i;
document.write(f);
i++;
}
38. Rewrite the following program segment using the if...else statement
comm = sale > 15000 ? sale * 5/100 : 0;
Ans. The if...else statement is:
if (sale > 15000)
comm = sale * 5/100;
else
comm = 0;
39. How many times will the following loop execute? What value will be returned?
var x = 2, y = 50;
do {
++x;
y -= x++;
} while (x <= 10);
return y;
Ans. The loop will execute 5 times. The returned value is 15.
40. What is the final value of ctr when the iteration process given below executes?
var ctr = 0, i, j;
for (i = 1; i <= 5; i++)
for (j = 1; j <= 5; j+=2)
++ctr;
Ans. The final value of ctr is 15.
41. What will be value of x after executing following JavaScript code.
var a=10, b=12, x=5, y=6;
while (a<=b) {
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.124 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
if (a%2==0)
x=x + y;
else
x=x-y;
a=a+1;
document.write(""+x);
}
Ans. The final value of x is 11.
42. Find the errors from the following code segment and rewrite the corrected code underlining the
correction made.
var a ,b;
c = a + b;
for(;i<=5;i++) {
Display c;
c=c+1
]
Ans. The underlined correct code is:
var a=0 , b=0, c, i=1;
c = a + b;
for(;i<=5;i++) {
document.write(""+c);
c=c+1;
}
43. Rewrite the following code using do-while loop.
var x;
for(x=0;x<10;x++) {
document.write(x);
}
Ans. The do-while code is:
var x=0;
do {
document.write(x);
x=x+1;
} while(x<10);
44. How many times does the following loop get executed?
var x = 5, y = 35;
while (x <= y) {
x += 8;
}
Ans. The loop will execute 4 times.
45. What will be the output of the the following code?
var num = 1;
do {
document.write("" + num.toString() + "<br>");
num = num + 2;
}while (num <= 10);
Ans. The output is:
1
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.125
3
5
7
9
46. Predict the value of prod of the following JavaScript construct:
var m=5, prod=1, i=1;
while(i<=5) {
prod=prod+prod*(m%2);
--m; ++i;
}
Ans. The output of prod is 8.
47. Write a JavaScript Program to print the following Pattern:
(i) (ii)
6 A
55 AAA
444 AA A AA
3333 A A AA A A A
22222 AAAAAAAAA
111111
Ans. (i) The code is (outputn.html):
for(i=6; i>=1;i--) {
for(j=6; j>=i; j--)
document.write(" "+i);
document.write("<br>");
}
(ii) The code is (outputo.html):
for(i=1; i<=5;i++) {
for(j=4; j>=i; j--)
document.write(" ");
for(k=1; k<=(2*i-1); k++)
document.write("A" + " ");
document.write("<br>");
}
48. What will be the value of A and B after execution of the following code:
var A = 100, B;
for(B = 10; B <= 12; B++) {
A+= B;
}
document.write("A: " + A + " B: " + B);
Ans. The values are: A: 133 B: 13
49. How many times does the following while loop get executed?
var K=5, L=36;
while (K<=L) {
K+=6;
}
Ans. The while loop will execute 6 times.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.126 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
50. What will be the values of variables P and Q after the execution of the following code?
var P, Q=0;
for (P=1; P<=4; P++) {
Q+=P;
Q ;
}
Ans. The value of variable P = 5 and variable Q = 6
51. How many times the following loop will execute the statements inside it? Which one of them is Entry
Control and which one is Exit Control?
Loop 1 1 Loop 2
var j=8, total=0; var j=8, total=0;
while (j > 1) do
{ {
total += j; total += j;
j -= 2; j -= 2;
} } while (j > 1);
Ans. Loop 1 will execute 4 time and Loop 2 will execute 4 times.
Loop 1 is the Entry Control loop and Loop 2 is the Exit Control loop.
52. What will be the output of the following code?
var Total = 0, End = 10;
for (Turn = 1; Turn <= End; Turn += 2)
Total++;
document.write("Total " + Total + "<br>");
document.write("Turn " + Turn + "<br>");
Ans. The output is:
Total 5
Turn 11
53. Rewrite the following program code using a while loop statement:
var Last = parseInt(prompt('Enter any number'));
for (C = 1; C <= Last; C++)
document.write(C + " ");
Ans. The while loop statements are:
var Last = parseInt(prompt('Enter any number'));
C = 1;
while (C <= Last) {
document.write(C + " ");
C++;
}
54. Observe the following code carefully and find which statement will never get executed in the code.
int Count=1; //Statement 1
do //Statement 2
{ //Statement 3
if (Count<15) //Statement 4
document.write("Jump"); //Statement 5
else //Statement 6
document.write("Stop"); //Statement 7
Count+=4; //Statement 8
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.127
} //Statement 9
while(Count<=15); //Statement 10
Ans. Statement 7
55. What will be the values of variables agg and agg1 after the execution of the following loops?
Loop 1: Loop 2:
var a=9, agg=9; var b=9, agg1=0;
while (a>10) do
{ {
agg+=a; agg1+=b;
a-=2; b-=2;
} } while (b>10);
Ans. The value of agg is 9 and agg1 is 9
56. What will be the output of the following code:
var G=1;
do
{
document.write(G++ + "<br>");
G=G+1;
}while(G<=5);
Ans. The output is:
1
3
5
57. What will be the values of x and y after execution of the following code:
var x, y=0;
for (x=1; x<=5; ++x)
y=x++;
--y;
Ans. The value of x = 7 and y = 4
58. Rewrite the following program code using a for loop:
var i = 1, sum = 0;
while (i<10)
{
sum += i;
i += 2;
}
Ans. The code using for loop is:
var i, sum = 0;
for (i = 1; i < 10; i+=2)
sum += i;
59. Write a JavaScript function to find the sum of odd numbers up to 10.
Ans. The function is as (sumodd.html):
<SCRIPT type="text/javascript">
function odd_sum()
{
var i;
var sum = 0;
for (i = 1; i <= 10; i++)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.128 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
if ((i%2) == 1)
sum = sum + i;
document.write("The sum of odd numbers upto 10 is " + sum);
}
odd_sum();
</script>
60. Write a JavaScript program to find the area of circle. The program should enter no. of time the value
of radius of a circle throug a prompt window. You can only exit when you press the Cancel button in the
prompt window.
Ans. The JavaScript program is (radius.html):
<HTML>
<HEAD>
<TITLE>Area of circle</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
var rad, area;
rad = prompt("Enter radius")
while (rad != null) {
area = 3.14 * rad * rad
document.write("<P> radius = " + rad + ", area = " + area)
rad = prompt("Enter radius")
}
</script>
</BODY>
</HTML>
61. Write a JavaScript program to print the first 12 terms of Fibonacci series (i.e., sum of previous two
numbers is the next number), e.g.; 1 1 2 3 5 8 13
Ans. The JavaScript program is (fibn.html):
<SCRIPT type="text/javascript">
var i, j, k, l;
i = 0;
j = 1;
document.write("The Fibonacci series is.... <br> ");
document.write(i + " ")
document.write(j + " ")
for(l=0; l<10; l++)
{
k = i + j;
i = j;
j = k;
document.write( k + " ");
}
</script>
62. Write a JavaScript program to print the mathematical table from 1 to 3.
Ans. The JavaScript program is (mtable3.html):
<SCRIPT type="text/javascript">
var i, j, k, l;
i = 0;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.129
j = 1;
for (i=1; i<=3; i++)
for(j=1; j<=10; j++)
{
k = i * j;
document.write(i + "*" + j + "=" + k + "<br> ")
}
</script>
63. Write a JavaScript code to swap two numbers without using third variable.
Ans. The JavaScript code is (swap.html):
# This program swaps two numbers without using third variable
<HTML>
<HEAD>
<TITLE>Swapping two numbers</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// This program swaps two numbers without using third variable
var a = parseInt(prompt("Enter first number: "));
var b = parseInt(prompt("Enter second number: "));
a=a+b
b=a-b
a=a-b
document.write("After swapping a is > " + a + "<br>");
document.write("After swapping b is > " + b + "<br>");
</script>
</BODY>
</HTML>
64. Write a JavaScript with function having two value parameters X and Y with result type float to find
the sum of series given below.
1+ X1/2! + X2/3! + ..+ XN/(N+1)!
Ans. The function is (seriesxy.html):
<SCRIPT type="text/javascript">
function sum_series(X, N)
{
var sum = 1, temp = 1; // Initialize the series first value 1
for (var i = 2; i <= N+1; i++) // Starting series value is 2
{
temp = temp * (X/i); // (4/2!) and so on
sum += temp;
}
return (sum);
}
var X = 4;
var N = 5;
var result = sum_series(X, N);
document.write("The series value is : " + result);
</script>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.130 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
<SCRIPT type="text/javascript">
// Search an element
var flag = 0;
var pos;
var num = new Array(10);
num[0] = 100;
num[1] = 20;
num[2] = 450;
num[3] = 143;
num[4] = 321;
num[5] = 241;
num[6] = 325;
num[7] = 76;
num[8] = 150;
num[9] = 120;
document.write("The array elements are...<br>");
for (var i = 0; i <= 9; i++) {
document.write(num[i] + " ");
}
var s_num = parseInt(prompt("Enter search no."))
for (var i = 0; i <= 9; i++) {
if (num[i] == s_num )
{
flag = 1;
pos = i+1;
}
}
if ( flag == 1)
document.write("<br>The element is present at location: " + pos);
else
document.write("<br>The element is not present ");
</script>
</BODY>
</HTML>
69. Write a function to find the sum of series.
(1) + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) . upto N terms.
Ans. The function is (newseries.html):
<SCRIPT type="text/javascript">
function sumseries(n)
{
var i, sum = 0, sum1 = 0;
for(i = 1; i <= n; i++) {
sum = 0;
for(var j =0; j<=i; j++)
sum = sum + j;
sum1 = sum1 + sum;
}
return(sum1);
}
var n = 5;
var result = sumseries(n);
document.write("The value of the series is : " + result);
</script>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.132 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
72. Write a JavaScript function with HTML program to find the square of numbers from 1 to 10 as shown
the following figure:
REVIEW QUESTIONS
1. What is conditional statement?
2. Differentiate between while and do...while loop.
3. What is the purpose of for loop?
4. What is the role of control variable in for statement?
5. How break and continue statements work in repetitive statements?
6. Why is continue statement called a jumping statement?
7. Use of continue statement should be avoided in programming. Why?
8. What are the ways to create arrays in JavaScript? How are array cells indexed?
9. Find the output of the following code:
(a) var i = 1;
while (i < 5) {
document.write(i + " ");
i = i*2;
}
(b) var total = 0, sum = 0;
for (i=0; i<=10;i++)
sum = sum + 1;
document.write(total);
(c) var N = 1;
while (N <= 32) {
N = 2 * N;
document.write(N + " ");
}
(d) var x = 5, y = 1;
while (x > 0) {
x = x - 1;
y = y * x;
document.write(y + " ");
}
(e) var U = 10, V = 20;
for (I = 1; I <= 2; I++) {
document.write("[1]=" + U++ + " & " + V + 5 + "<br>");
document.write("[2]=" + ++V + " & " + U + 2);
}
10. What is the output of the following program segment?
(a) i = 0;
for (i = 1; i <= 20; i++) {
document.write(i + " ");
i = i + 2;
}
(b) i = 0, x = 0;
while (i < 10) {
if ((i % 2) == 0) {
x = x + i;
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Looping in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.135
29. Write a JavaScript for loop which sums all values between 10 and 100 into a variable called total. Assume
that total has NOT been initialized to zero.
30. Write a JavaScript that will read a sequence of positive real numbers entered by the user and will print the
same numbers in sorted order from the smallest to the largest. The user will input a zero to mark the end
of the input. Assume that at most 100 positive numbers will be entered.
31. Write a JavaScript code to find all the duplicate elements in an array and remove them.
32. Write a JavaScript for loop to print out the character set from A to Z.
33. Find the syntax error(s), if any, in the following JavaScript program :
<script language = "JavaScript">
var x y = 15;
x = 5;
for (i = 0; i < 10; ++i)
{
if (i = x)
break;
document.writ(y);
document.write(x y);
}
</script>
34. Give the output of the following JavaScript program segment:
<script language = "JavaScript">
var i, j;
for(i = 1; i <= 10; ++i)
{
for(j = 1; j <= i; ++j)
document.write(" ");
for(j = 9; j > 1; i)
{
for(j = 1; j <= i; ++j)
document.write("*");
document.write("\n");
}//for - j
}//for - i
</script>
35. Give the output for the following JavaScript program segment:
(a) for(var i = 10; i > 6; i = i2)
document.write(i + "<br>");
(b) for(var i = 5; i < 8; i )
document.write(i + "<br>");
(c) for(var i = 3, sum = 0; i < 11; i++)
sum++;
document.write(sum)
36. Find the output of the following JavaScript code:
(a) a = 1;
b = 5;
b++;
if(b == 5)
document.write("value is five");
else
document.write("value is not five");
(b) var i = 1;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.138 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
while(i < 5 )
{
document.write(i);
i = i*2;
}
(c) var total = 0, sum = 0;
for(var i = 0; i <= 10; i++)
sum = sum + i;
document.write(total);
37. What happens if you dont include an else statement with an if condition and if condition is false?
38. Consider the following JavaScript:
for (x=0; x<7; ++x)
{
y = x;
}
What will be the value of y when the loop is executed for the first time?
39. In the following JavaScript example, what is the final value of y?
for (x=0; x<5; x++)
{
if (x == 4)
continue;
y += x;
}
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.139
Objects in JavaScript
5
5.1 INTRODUCTION
We learnt about the JavaScript functions in our previous chapter, which are used to provide a uniform method
or organizing code. At its most basic level, object-oriented programming is a style of programming in which
related concepts are grouped together. If you have five data elements and three functions that manipulate
those elements, then you group those elements and functions together into a generic container known as an
object. Objects serve the same purpose for data. This is the common ground shared by all object-oriented
programming languages.
Upto this point, the only data items we have seen are simple variables declared with var. Each of these
typeless quantities can only hold a single value of some sort at a time. Objects provide the ability to hold
multiple values, so that a group of related data elements can be associated with one another.
0HWKRGV
A method is a function associated with an object, or, simply put, a method is a property of an object that is a
3.139
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.140 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
function. Methods are defined the way normal functions are defined, except that they have to be assigned as
the property of an object.
Let us say that you wanted to use an object that represented an automobile. There are several basic
functions that someone driving an automobile can perform: push the gas pedal, push the brake, steer the wheel
right and steer the wheel left. This functionality would be made available to the use of the object through its
methods:
x pushGas()
x pushBrake()
x steerRight()
x steerLeft()
Because these are methods and not functions, they could not be called by themselves. Instead, to call a
method you must prefix it with the name of the object with a simple dot-notation. For example,
myCar.steerRight()
Here, this statement calls the steerRight() method of myCar object, causing the car to turn right.
3URSHUWLHV
A JavaScript object has properties associated with it. A property of an object can be explained as a variable that
is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for
the attachment to objects. The properties of an object define the characteristics of the object. When methods
are called, those method usually act on some sort of data contained in the object. That data is called properties.
You access the properties of an object with a simple dot-notation:
objectName.propertyName
Or
objectName[propertyName]
Like all JavaScript variables, both the object name (which could be a normal variable) and property name
are case sensitive. You can define a property by assigning it a value. For example, let's create an object named
myCar and give it properties named make, model, and year as follows:
var myCar = new Object();
myCar.make = "Indian";
myCar.model = "HigherXLV";
myCar.year = 2016;
To define an object, it is better to write a function that contains all the properties and methods of that object.
You then set the properties inside the object with this statement, e.g., let us consider an employee object with
name, age and salary properties as given:
function employee(name, age, salary)
{
this.name = name;
this.age = age;
this.salary = salary;
}
From the above example, we created a function that makes the objects. But the use of this with the
properties create a constructor. Notice the use of this to assign values to the object's properties based on the
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.141
values passed to the function. So, if you wanted to create an employee object with data, then create an object
variable using new keyword as:
var myEmployee = new employee("Sudhir Rana", 25, 35500);
This statement creates myEmployee and assigns it the specified values for its properties. Then the value
of myEmployee.name is the string "Sudhir Rana", myEmployee.age is the integer 25, and so on.
Then you could reference the object properties as follows:
empName = myEmployee.name;
empAge = myEmployee.age;
empSalary = myEmployee.salary;
You can create any number of car objects by calls to new. For example,
var Emp1 = new employee("Joyti Kalra", 28, 25700);
var Emp2 = new employee("Dinesh Singh", 30, 32800);
Otherwise, you can use a shorthand way to access this object. To do this, you use the with statement,
followed by the name of the object to be used by default when referencing properties and a block of statements
that use this object. For example,
with (myEmployee)
{
empName = name;
empAge = age;
empSalary = salary;
}
Now that the myEmployee object is being used in the with statement. JavaScript automatically assumes
the references to empName, empAge and empSalary properties to be properties of the myEmployee object.
Example Demonstrate the object to print the employee detail of above object myEmployee.
Solution Write the following code in Notepad editor and save as object01.html.
<HTML>
<HEAD>
<TITLE>JavaScript Object Example </TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Accessing element using object
function employee(name, age, salary)
{
this.name = name; // Properties
this.age = age;
this.salary = salary;
}
myEmployee = new employee("Sudhir Rana.", 25, 35500);
empName = myEmployee.name;
empAge = myEmployee.age;
empSalary = myEmployee.salary;
document.write("Employee name : " + empName + "<br>");
// You can write : myEmployee.name instead of empName
document.write("Employee age : " + empAge + "<br>");
document.write("Employee salary : " + empSalary);
</script>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.142 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
When you will open the object01.html file in a browser like IE, you will see the object properties result
as shown in Figure 5.1.
Example Modify the above example for calculating a 10% of bonus using JavaScript object method.
Solution Write the following code in Notepad editor and save as object02.html.
<HTML>
<HEAD>
<TITLE>JavaScript Object Example </TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// Accessing element using object
var num = new Array(10);
function employee(name, age, salary)
{
this.name = name; // Properties
this.age = age;
this.salary = salary;
this.bonus = cal_Bonus; // the cal_Salary method */
}
/*
This function is the cal_Bonus of an employee
*/
function cal_Bonus() // no argument
{
if (empSalary > 5000)
myEmployee.bonus = empSalary * (10/100);
return myEmployee.bonus;
}
myEmployee = new employee("Sudhir Rana.", 25, 35500);
empName = myEmployee.name;
empAge = myEmployee.age;
empSalary = myEmployee.salary;
document.write("Employee name : " + empName + "<br>");
// You can write : myEmployee.name instead of empName
document.write("Employee age : " + empAge + "<br>");
document.write("Employee salary : " + empSalary + "<br>");
document.write("Employee bonus : " + cal_Bonus());
</script>
</BODY>
</HTML>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.143
When you will open the object02.html file in a browser like IE, you will see the object properties result
as shown in Figure 5.2.
JavaScript has number of built-in objects. These built-in objects are available through both the client-side
JavaScript (inside the Netscape Navigator on your desktop) and through LiveWire (Netscapes server-side
application).
The JavaScript object model and its very interesting set of built-in objects, methods and functions
provide what we would expect from any modern programming language. They provide control structures,
encapsulation, functions, mathematical operations and so forth. Since JavaScript is designed to work with and
on the World Wide Web, there must also be a linkage between it and the contents of HTML pages. Built-in
objects include:
x The String Object
x The Window Object
x The Document Object
x The Location Object
x The History Object
x The Form Object
These objects are referred to as built-in because they really do not have anything to do with Web pages,
HTML, URLs, the current browser environment or anything visual.
object.'formatting_method'( )
For example,
"Multimedia and Web Technology".bold().blink()
would return:
<blink><b>"Multimedia and Web Technology"</b></blink>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.144 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Similarly, you call a strings method by the same dot notation you would in other objects. For example,
"Hello Friends!".italics()
this code returns "Hello Friends!", as displayed by your Web browser. Table 5.1 shows the properties and
methods of the string object.
123456789012345678901234567890121234567890123456789012345
Table 5.1 Properties and methods of the String object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description Example
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
length The number of characters in the string Hello.length()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
Example
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
anchor Converts string to an HTML anchor
123456789012345678901234567890121234567890123456789012345
big Encloses string <big>. . .</big>
hello.anchor(anchortext)
hello.big()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
blink Encloses string in <blink>. . .</blink> hello.blink()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
bold Encloses string in <b>. . .</b> hello.bold()
123456789012345678901234567890121234567890123456789012345
fixed Encloses string in <tt>. . .</tt> hello.fixed()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
fontcolor Encloses string in <font hello.fontcolor(green)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
fontsize
color=somecolor>. . .</font>
123456789012345678901234567890121234567890123456789012345
Enclose string in <font hello.fontsize(-1)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
size=somesize>. . . </font>
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
italics Encloses string in <i>. . . </i> hello.italics()
123456789012345678901234567890121234567890123456789012345
link Converts string into a hyperlink hello.link(linktext)
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
small Encloses string in <small>. . .</small> hello.small()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
strike Encloses string in <strike>. . .</strike>
123456789012345678901234567890121234567890123456789012345
sub Encloses string in <sub>. . .</sub>
hello.strike()
hello.sub()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
sup Encloses string in <sup>. . .</sup> hello.sup()
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
toLowerCase Converts uppercase to lowercase HELLO.toLowerCase
123456789012345678901234567890121234567890123456789012345
toUpperCase Converts lowercase to uppercase hello.toUpperCase
Example Demonstrate some of the properties and methods of string objects on the string "Multimedia
and Web Technology".
Solution Write the following code in Notepad editor and save as object03.html.
<HTML>
<HEAD>
<TITLE>JavaScript String Object Example </TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
// JavaScript String object
var course = "Multimedia and Web Technology" // String
document.write("<center>"
+ "String Property and Methods".fontsize("5").fontcolor("red")
+ "</center>" + "<br>");
document.write("<hr size='4'>" + "<br>");
document.write("Original String: " + course + "<br>");
document.write("<hr size='4'>" + "<br>");
document.write("1. The length of " + " "+ course + " ' "+ " is : "
+ course.length + "<br>"); // length property
// anchor method
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.145
When you will open the object03.html file in a browser like IE, you will see the String object methods
result as shown in Figure 5.3.
Navigator
Window
Submit Reset
Radio Checkbox
Select Hidden
123456789012345678901234567890121234567890123456789012345
Table 5.2 Properties and methods of the Window object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
defaultStatus The default message in the status bar.
123456789012345678901234567890121234567890123456789012345
document The current document contained in the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
frames An array that describes all of the frames in the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
frame A frame object.
123456789012345678901234567890121234567890123456789012345
length Reflects the number of frames in the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
name The name of the window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
parent Synonymous with the name of the window. Contains the frameset tags.
123456789012345678901234567890121234567890123456789012345
self Synonymous with the name of the window and refers to the current window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
status Value appears in the windows status bar. Usually only lasts a moment
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
before overwritten by some other event.
123456789012345678901234567890121234567890123456789012345
top Synonymous with the name of the window and represents the topmost
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
window.
123456789012345678901234567890121234567890123456789012345
window Synonymous with the name of the window and refers to the current window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
location A string specifying the URL of the current document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
alert Brings up an alert dialog box (where you just click OK).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
close Closes the window.
123456789012345678901234567890121234567890123456789012345
confirm Brings up a dialog box with Yes or No button and a user-specified message.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
open Opens a new browser window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
prompt Brings up a window with user-specified text and an input box that allows
123456789012345678901234567890121234567890123456789012345
the user to type in information.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
setTimeout Sets a time in milliseconds for an event to occur.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
clearTimeout Resets value set by setTimeout.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.148 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
Table 5.3 Properties and methods of the Document object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
alinkColor Reflects the ALINK attribute in the <body>tag.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
anchors An array listing all of the HTML anchors in the document <a name>.
123456789012345678901234567890121234567890123456789012345
anchor An anchor object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
bgColo Set the value of BGCOLOR attribute.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
cookie Set the value of Netscape cookie.
123456789012345678901234567890121234567890123456789012345
fgColor The value of TEXT attribute in <body> tag.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
forms An array listing all the forms in the document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
form A form object.
123456789012345678901234567890121234567890123456789012345
history An object containing the current browser history (links visited, number
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
of links visited and link URLs.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
lastModified The date on which the document was last modified.
123456789012345678901234567890121234567890123456789012345
linkColor Set the LINK attribute of the <body> tag.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
links An array of all HTML link in the document <a href>.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
link A link object.
123456789012345678901234567890121234567890123456789012345
location The URL of the document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
referrer The URL of the document that called the current document.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
title Sets the title of the document.
123456789012345678901234567890121234567890123456789012345
vlinkColor Set the color listed in the VLINK attribute.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
clear Clears the window of all content.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
close After an open causes the string buffer to be written to the screen.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
open Begins a string to be written on the screen.
123456789012345678901234567890121234567890123456789012345
write Writes some expression to the current window.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
writeln Same as write but adds a newline character at the end.
For example, to change the document's background color, you'd set the document's bgcolor property.
window.document.bgcolor = "red"
123456789012345678901234567890121234567890123456789012345
Table 5.4 Properties and methods of the Location object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
href Display the entire URL of the current page.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
protocol It retrieves the URL for IE Web page, the protocol is http:
123456789012345678901234567890121234567890123456789012345
host The hostname is the name of the host machine on which the current URL
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
is located.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
hostname The name of the host machine on which the current URL is located.
123456789012345678901234567890121234567890123456789012345
hash The hash property includes the section of the URL following the hash
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
character (#), if any.
123456789012345678901234567890121234567890123456789012345
search The search property includes the section of the URL following the question
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
mark character (?), if any.
123456789012345678901234567890121234567890123456789012345
port If a specific port is specified in the URL, its value is located in the port
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
property.
123456789012345678901234567890121234567890123456789012345
pathname This contains the path to the specified location on the host. For the IE
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
example, this is ie.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
reload It simply causes the current page to be reloaded.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
replace It causes the browser to replace the current document with the one at that
123456789012345678901234567890121234567890123456789012345
URL.
For example, the most common usage of Location is simply to use it to automatically navigate the user to
another page:
<HTML>
<HEAD>
<TITLE>JavaScript Location hostname</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
window.location="http://www.google.com"
document.write("Page hostname is " + window.location.hostname);
</script>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345
Table 5.5 Properties and methods of the History object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
length It specifies how many URLs are contained in the current history object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
back() This method enables the browser to be moved backward in the history list
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
programmatically.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.150 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
forward() This method enables the browser to be moved forward in the history list
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
programmatically.
123456789012345678901234567890121234567890123456789012345
go(where) This method enables you to go to a specific place in the browser history
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
by passing an argument indicating where you want to go.
For example, the following shows different usages of history object over URL:
window.history.back(); // for previous page
window.history.forward(); // for next page
window.history.go(2); // for next 2nd page
window.history.go(-2); // for previous 2nd page
In addition, the window object is always the default object when script. Therefore, if you like you can leave
off the window object reference:
history.back();
Similarly, if you knew that you had been the part of the IE site and wanted to go back to where you were,
you would call the go() method in the following manner:
window.history.go("http://www.microsoft.com/ie");
or
history.go("http://www.microsoft.com/ie");
This would take you to the URL in the history list that contains "http://www.microsoft.com/ie".
To simulate the browser's back button, for example, you can use the History object:
<a href="javascript:history.go(-1)">Go back</a>
For example, to go to the previous URL entry in the history list. This does the same thing as the browser
back button. The following HTML code creates a back button:
<FORM>
<INPUT TYPE="button" VALUE="Go Back" onClick="history.back()">
</FORM>
123456789012345678901234567890121234567890123456789012345
Table 5.6 Properties and methods of the History object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
action Sets the HTML ACTION attribute of the <form> tag.
123456789012345678901234567890121234567890123456789012345
button A button object (<input type = button>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
checkbox A checkbox object (<input type = checkbox>).
123456789012345678901234567890121234567890123456789012345
elements An array listing all elements in a form.
123456789012345678901234567890121234567890123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.151
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
encoding The value of the ENCTYPE attribute.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
hidden A hidden object (<input type + =hidden>).
123456789012345678901234567890121234567890123456789012345
length The number of elements in the form.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
method The METHOD attribute of <form>.
123456789012345678901234567890121234567890123456789012345
password A password object (<input type + =password>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
radio A radio object (<input type = radio>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
reset A reset button object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
select A select object (<select> . . .<select>).
123456789012345678901234567890121234567890123456789012345
submit A submit button object.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
target
text
The TARGET attribute of <form>.
123456789012345678901234567890121234567890123456789012345
A text object (<input type = text>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
textarea A textarea object (<textarea></textarea>).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Method Name Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
submit() Submits the form to the location in the ACTION attribute.
123456789012345678901234567890121234567890123456789012345
reset() Used to reset the form elements to their default values.
Once you have created an object, you can address its properties and methods in the following ways:
x formName.propertyName.
x formName.methodName(parameters).
x forms[index].propertyName.
x forms[index].methodName(parameters).
Forms on the page are represented in JavaScript via the form object, and can be accessed in one of the 3
standard ways below:
document.yourformname //where yourformname is the name of your form.
document.form.yourformname
document.forms["yourformname"]
JavaScript places each form it finds in a page in an array called forms. You can access each form by either
its index in this array (with the first form at 0, the next at 1 and so on) or by its name. For example,
<form name = "thisform">
<input type = text name = "input" value = "Hello!">
</form>
By doing this you create an object called thisform which also exists as:
Document.forms[0];
You can access individual fields in a form where you can either read that field directly or send a new value
to that fieldwhich might dynamically change on the screen. To access information about this form, you can
use the following:
x formName.actionFrom the ACTION argument.
x formName.elementsTo get to the input fields.
x formName.encodingFrom the ENCTYPE argument.
x formName.methodFrom the METHOD argument.
x formName.targetFrom the TARGET argument.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.152 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
For example,
<SCRIPT type="text/javascript">
<form name = "thisForm"
action = "hello.html"
ENCTYPE = "text/ascii"
Method = "GET">
</form>
<!- - hide this code
document.form[0].method = "POST"
document.write(document.thisForm.method)
- ->
</script>
3RLQWVWR5HPHPEHU
1. JavaScript object is an entity having state and behavior (properties and method).
2. A method is a function associated with an object.
3. The JavaScript Window Object is the highest level JavaScript object which corresponds to the
web browser window.
4. The JavaScript Document object is the container for all HTML HEAD and BODY objects
associated within the HTML tags of an HTML document.
5. The location object holds information about the current URL of the browser.
6. The history object is used to refer to the history list of previously visited URLs or represents an
array of URLs visited by user.
7. The JavaScript Form Object is a property of the document object.
SOLVED EXERCISES
1. What is an object?
Ans. A JavaScript object is made up of a set of component parts, which are called its properties or members.
That is, JavaScript refers to the items collected within an object as its properties.
2. How an instance object is created in JavaScript? Write its syntax.
Ans. An instance object is created by using new keyword. The syntax is:
var objectname=new Object();
3. What is window object?
Ans. 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.
4. How many types of objects are present in JavaScript?
Ans. Two types of objects are present in JavaScript :
x User-defined objects
x Built-in Objects
5. What is method?
Ans. A method is just a function that is contained inside of an object.
6. What are properties?
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Objects in JavaScript
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.153
Ans. When methods are called, those methods usually act on some sort of data contained in the object. That
data is called properties.
7. Name three methods of window object?
Ans. The three methods are alert(), confirm() and prompt().
8. What is JavaScript history object?
Ans. The JavaScript history object represents an array of URLs visited by the user. By using this object, you
can load previous, or forward any particular page. There are three methods of history object:
x history.back()
x history.forward()
x history.go(number): number may be positive for forward, negative for backward.
9. Define a user-defined object Customer with name, age, address and salary.
Ans. The object is:
function Customer(name, age, address, salary) {
this.name = name;
this.age = age;
this.address = address;
this.salary = salary;
}
10. Define a user-defined object Emp with EmpID, Ename, Esalary and assign the instance attributes as
A101, Amit Sinha, 25700, respectively. Also print the details of Emp object.
Ans. The object is as:
<script language="JavaScript">
var Emp = new object();
Emp.EmpID = "A101";
Emp.Ename = "Amit Sinha";
Emp.Esalary = 25700;
}
11. What is the following line called?
NewEmp = new Emp("A101", "Simral Kaushik", 26000);
Ans. NewEmp is declared as constructor object.
12. List some built-in objects in JavaScript.
Ans. Built-in objects are:
x The String Objects
x The Window Object
x The Document Object
x The Location Object
x The History Object
x The Form Object
13. What is the use of string object?
Ans. This object is very useful because you can use its methods to modify and add HTML modifications
without changing the string itself.
14. Which property of the Windows Object is used for frame handling?
Ans. frames property.
15. Explain the significance of any two predefined objects of JavaScript.
Ans. Let us consider the two predefined objects : history and document.
Location object. This object is a list that contains the locations of all the URLs that you have visited.
You can move backward and forward through the history list with history.back and history.forward. You
can also move around in the list in a relative fashion with history.go().
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.154 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Document object. This object encapsulates all JavaScript objects that correspond to the HTML
elements. It is the parent of forms, links and anchors. These objects occur as arrays and are accessed as
document.Forms[xx], document.Links[xx] and document.anchors[xx], where xx is an array index.
The document object also has several other useful properties such as background color, text color and
link colors.
16. Create a JavaScript to find the area and diameter of a circle using two different methods called CArea()
and CDiameter(). Using user-defined object methods and properties find the area and diameter of the
circle.
Ans. The code is (circle.html):
<HTML>
<HEAD>
<TITLE>Area and diameter of a circle</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function CArea(){
var area = this.radius*this.radius*3.14
return area
}
function CDiameter(){
var diameter = this.radius*2
return diameter
}
//the below creates a new object, and gives it the two methods defined earlier
function circle(r){
this.radius = r //property that stores the radius
this.area = CArea
this.diameter = CDiameter
}
var C = new circle(20)
document.write("Radius of circle: " + C.radius + "<br>")
document.write("Area of circle: " + C.area() + "<br>")
document.write("Diameter of circle: " + C.diameter() + "<br>")
</script>
</BODY>
</HTML>
REVIEW QUESTIONS
1. What is window object?
2. Explain about the document object.
3. Differentiate between location object and form object.
4. Explain any five form objects in JavaScript.
5. Which method you will use to reload a current page in JavaScript?
6. What do you call the type of JavaScript command that document.write represents?
7. What method can be used to determine the length of a variable string?
8. If document is an object, what is write in document.write?
9. What string method would you use to create a link to a new HTML document?
10. Create a new object function called player that creates the properties name, hits, strikeouts, at bats and
home runs.
11. Add a method to the above player object definition that computes the batters batting average (hits/
at bats).
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.155
JavaScript has number of control objects like button, reset, submit, checkbox, radio, select, password, text and
textarea. These control objects are used in JavaScript to handle different inputs and events. Before discussing
about the controls, let us start the general concepts of event and event handler.
6.2 EVENT
HTML forms have gradually changed that model to increase the level of interaction. A form can have a variety
of ways of accepting input, including text fields, buttons, checkboxes and multiple choice selections. One of
the primary goals of JavaScript is to localize most of its processes and perform the form validation within the
users browser. It would not be possible to actually submit an order locally, but it will be possible to make sure
that the form is properly filled out locally and thereby avoid forcing the user to redo the form. JavaScript
realizes this goal through event handlers.
Most of the time, you will be building scripts that do such things as store information, display data in a
certain format, perform some calculations or respond to user actions called events. Event handlers are JavaScript
statements (usually functions) that are called whenever something happens. Essentially, functions are stored
chunks of code that are executed at some intervaleither immediately, when the document is loaded or in
response to some triggered event. JavaScript functions can be called when a form is submitted or they can be
called whenever the user does anything to the form. When JavaScript encounters an event, it passes it to an
event handler. Event handlers are tags that point to the specific functions to be executed. All event handlers
begin with on.... Table 6.1 shows events and event handlers in JavaScript.
123456789012345678901234567890121234567890123456789012345
Table 6.1 Events and even handlers in JavaScript.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Event Event Handler To Trigger Event
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
blur onBlur In a form element, user clicks (tabs) away from element.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
click onClick In a form element or link, user clicks element.
123456789012345678901234567890121234567890123456789012345
change onChange In a form text, text area or select object, user change value.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
focus onFocus In a form element, user clicks (tabs) to element.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
load onLoad It happens when page is loaded.
123456789012345678901234567890121234567890123456789012345
mouseover onMouseOver It happens when mouse is passed over links or anchors.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
select onSelect In a form, user selects input field.
123456789012345678901234567890121234567890123456789012345
submit onSubmit In a form, user submits a form (clicks the Submit button).
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
unload onUnload It happens when user leaves the page.
3.155
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.156 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
In the previous section, we learnt about the events and event handlers. The event handler is a command that
is used to specify actions in response to an event. Let us look at an example of how you might add an even
handler to your existing HTML code. The syntax is:
<TAG eventHandler = "JavaScript code">
Here,
x the TAG is some HTML tag.
x eventHandler is any of the event handlers as shown in Table 6.1.
x the JavaScript code can be any valid JavaScript code but is usually a call to a function that you
loaded earlier in the document.
For example,
<A HREF= "#" onClick = "alert('Yes! It works!');">Click here for a message!</A>
From the above code, when you click the link, a dialog box displays the text, followed by an OK button for
you to click to return to the page. Also,
x No URL is found in the HREF attribute. When you click on the link, not only is the onClick activated
but the browser attempts to go to the location specified in the HREF. In this case, you are using this link
for its onClick event handler and not its hypertext reference. An alternative would be to type:
<a href = "javascript:alert('Yes! It works!');">Click here</a>
x onClick has mixed case. Although HTML is not case sensitive, JavaScript is. This is important to
remember when you are creating functions and variables.
x alert(.) is the standard function for bringing up an alert dialog box on the screen. Notice how this
function and all JavaScript functions, behave similarly to Java in that they use parentheses to contain
their arguments. In this case, the argument is the string 'Yes! It works!'
x The JavaScript code in quotation marks"alert('Yes! It works!');"ends in a semicolon.
Above all JavaScript event handler does not work independently, it must use some HTML object like
button, checkbox, radio button, submit, etc. These HTML objects are called control objects.
The button object is a new type of INPUT tag that allows you to create general purpose buttons in a form. You
can use these buttons to activate any function or to open a new URL or perform any other action that
JavaScript can initiate. The button object syntax is:
<INPUT
TYPE = "button"
NAME = "nameInside"
VALUE = "nameOnButton"
[onclick = "handlerText"]>
This is an extremely useful object and you will probably find yourself using this often to create buttons to
run scripts, open new windows or even cause the browser to leave your Web site altogether. You must use this
inside a set of <FORM>. . . </FORM> tags.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.157
RQ&OLFN (YHQW
The onClick event handler is activated by a click on a form element. This can mean a radio or check button, but
also submit, reset, or a user-defined button. For example,
<script>
function Hello()
{
alert("I am a JavaScript programmer!")
}
</script>
<form>
<input type="button" name="test" value="Click me" onclick="inform()">
</form>
From the above script, the function hello() is invoked when the user clicks the button.
Example Write a JavaScript code to demonstrate event handler for an alert message.
Solution Write the following code in Notepad editor and save as event01.html.
<HTML>
<HEAD>
<TITLE>JavaScript Event Handler</TITLE>
<SCRIPT type="text/javascript">
<!-- hide me from other browsers
function dontclickme()
{
alert("Please don't click me");
}
// end hiding from other browsers -->
</SCRIPT>
</HEAD>
</BODY>
<FORM METHOD = "POST" ACTION = "mailto:gbsahoo@yahoo.com">
<INPUT TYPE = "button" NAME = "mycheck" VALUE = "Click Me" onClick = "dontclickme()">
</FORM>
</BODY>
</HTML>
Open the event01.html file in a browser like IE, you will see the event handler result as shown in Figure
6.1 on the next page.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.158 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
and then read that file into your browser. You will notice that the initial appearance of the HTML page
is exactly as before. No errors have been reported.
x If you attempt to click the button labeled "Click", your browser reports and error and the alert dialog
box appear as shown in Figure 6.1. This is dynamic binding at work.
From above event handler declaration looks exactly like ordinary HTML attributes. Each attribute name
begins with the word on and is followed by the event name (Table 6.1), so that onClick is the attribute that
would be used to declare an event handler for the click event. The full declaration of an event handler looks
like :
onEvent = "javascriptcode"
The value of the attribute is a set of JavaScript code. The code may be included literally (known as inline
JavaScript) or it may reference a JavaScript function. We can completely remove the dontclickme() function of
previous example Event01.html and write the button statement as:
<INPUT TYPE = "button" NAME = "mycheck" VALUE = "Click"
onClick = "alert('Please dont click me');">
Example Write a JavaScript code with function using a button form element.
Solution Write the following code in Notepad editor and save as event02.html.
<HTML>
<HEAD>
<TITLE>JavaScript button object</TITLE>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.159
<SCRIPT type="text/javascript">
<!-- hide me from other browsers
function hello()
{
alert("Yes! You pushed the button");
}
// end hiding from other browsers -->
</SCRIPT>
<FORM>
<h1>Click below for an alert!</h1>
<INPUT TYPE = "button" NAME = "alertbutton" VALUE = "Click Me!" onClick = "hello()">
</FORM>
</BODY>
</HTML>
Open the event02.html file in a browser like IE, you will see the button result as shown in Figure 6.2.
Let us see another example that adds the onclick event inside form radio buttons:
<input type="radio" name="C1" onclick="document.bgColor='lightblue'">Light Blue
<input type="radio" name="C1" onclick="document.bgColor='lightyellow'">Light Yellow
<input type="radio" name="C1" onclick="document.bgColor='lightgreen'">Light Green
<td width="34%">
<p><input type="radio" name="C1" onclick="document.bgColor='lightgreen'">
Light Green</p></td>
</tr>
</table>
</form>
</body>
</html>
Open the change.html file in a browser like IE, you will see the onClick event changes the background
color of page in three different colors shown in Figure 6.3.
The checkbox object is created inside a form and appears as a small box with or without a mark (usually an x)
inside it. Think of a checkbox as an On/Off switch.
A user can flip this switch on or off by clicking his mouse inside this box. Clicking here can also trigger an
onClick event on your script. The syntax for checkbox object is:
<INPUT = "checkbox"
NAME = "checkboxName"
VALUE = "checkboxValue"
[CHECKED}
[onClick = "handlerText"]
textToDisplay
Accessing the properties of this object is very similar to accessing the properties of the button object. The
properties are:
x CHECKED indicates true or false to specify if the checkbox is checked.
x DEFAULT indicates whether or not the checkbox was marked checked upon page load.
x NAME indicates the name of the checkbox.
x VALUE indicates the value that is returned by the form if the checkbox is checked. This default is On.
Example Write a JavaScript code with function using a checkbok object in a form.
Solution Write the following code in Notepad editor and save as event03.html.
<HTML>
<HEAD>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.161
Open the event03.html file in a browser like IE, you will see the checkbok click result as shown in Figure
6.4.
This object allows a user to make a choice of a single selection from many. Usually this is a list of related items
from which you wish the user to pick only one choice.
The radio object is very similar to the checkbox object, except that a series of radio objects with the same
NAME attribute toggle all of the radio buttons off except for the one that was picket. In other words, when you
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.163
click one radio button in a group of related buttons, all of them will be off except for the one you clicked. The
syntax is as:
<INPUT
TYPE = "radio"
NAME = "radioName"
[CHECKED]
[onClick = "handlerText"]>
textToDisplay
Accessing information from the radio object is slightly different than that from the checkbox object. Since
all of the radio buttons of a given group have the same NAME attribute, you access individual radio buttons by
adding an index value to the NAME. The format for doing this is as follows:
x radioName[index1].propertyName.
x radioName[index1].methodName.
x formname.elements[index2].propertyName.
x formname.elements[index2].methodName.
You can click a specific radio button in JavaScript by using the following:
radioName[index1].click
Open the event05.html file in a browser like IE, you will see the radio button click result as shown in
Figure 6.6.
Figure 6.6 Event handler radio button object form element in JavaScript.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.164 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
In JavaScript all the text fields are managed through the HTMLs INPUT tag. The text-based input fields is in an
HTML form and shows how you can use JavaScript to enhance these input fields usefulness to you as a script
writer and few of them are:
x The password Object
x The text Object
x The textarea Object
We can access the properties and methods of this object by using the following :
x passwordName.propertyName.
x passwordName.methodName(parameters).
x formname.elements[index].propertyname.
x formname.elements[index].methodname(parameters).
The password object uses the focus, blur and select event handlers as methods. Let us say you want to
check the validity of a password before a user actually sends it back to the server for a login. You can create a
function that checks the password and notifies the user if he entered an invalid password.
Example Write a checkpass() function to check the password on the form using JavaScript.
Solution Write the following code in Notepad editor and save as event06.html.
<HTML>
<HEAD>
<TITLE>JavaScript password object</TITLE>
<SCRIPT type="text/javascript">
<!--
function checkPass(mypass)
{
if (notpass)
{
alert("You have entered an invalid password. Try again.");
mypass.focus();
mypass.select();
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
</BODY>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.165
Open the event06.html file in a browser like IE, you will see the password object result as shown in
Figure 6.7.
The text input field in an HTML document is your workhorse for inputting many types of information. Most
other types of input in forms are derivations of this kind of input.
The text input field is simply a small box of a set size that contains a cursor when you click it. It allows a user
using the form to type in information such as a name, a date or any other kind of information. If the text a user
types is too long for the box, it scrolls to the left to accommodate the additional text. In JavaScript, this field
serves a new and exciting purpose. Not only can a user using the form enter information into this field, but the
script itself can enter information as well. The syntax is:
<INPUT
TYPE = "text"
NAME = "textName"
VALUE = "textValue"
SIZE = integer
[onBlur = "handlerText"]
[onChange = "handlerText"]
[onFocus = "handlerText"]
[onSelect = "handlerText"]
For example,
<FORM>
<INPUT TYPE = "text" NAME = "todaysdate" value = " " SIZE = "5" onBlur = "getDate()"
onChange = "setDate()" onFocus = "alert('Set the date')"
onSelect = "alert('Really change?')">
</FORM>
The text object properties reflect the information you provide in the tag when you create the object. Table
6.2 shows text object properties, methods and event handlers.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.166 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345
Table 6.2 Text objuect properties methods and event handlers.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Example Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
defaultValue myText.defaultValue The value of the input tag at page load time.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
name myText.name The NAME argument.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
value formName.elements[0].value The VALUE argument.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
Property Name Example
123456789012345678901234567890121234567890123456789012345
Description
123456789012345678901234567890121234567890123456789012345
focus myText.focus() Equivalent to clicking this field.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
blur myText.blur()
123456789012345678901234567890121234567890123456789012345
Equivalent to clicking another field after
using this one.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
select myText.select()
123456789012345678901234567890121234567890123456789012345
Equivalent to dragging the mouse across
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
all the text in this fieldselecting it.
123456789012345678901234567890121234567890123456789012345
Eent Handler Example Description
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onBlur <input type = text Runs "alert()" when focus leaves this field.
123456789012345678901234567890121234567890123456789012345
onBlur = "alert('blur!')">
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onChange <input type = text
123456789012345678901234567890121234567890123456789012345
onChange = "alert('changed') ">
Runs "alert()" if the text has changed when
focus leaves this field.
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onFocus <input type = text Runs "alert()" when user clicks in (or
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onFocus = "alert('start typing!')"> otherwise gives focus to) this field.
123456789012345678901234567890121234567890123456789012345
onSelect <input type = text Runs "alert()" once some text in this field is
123456789012345678901234567890121234567890123456789012345
123456789012345678901234567890121234567890123456789012345
onSelect = "alert('text selected!')"> selected.
Example Write a JavaScript for text object event handler to demonstrate the text object. That is,
using event handler pass information to a text field.
Solution Write the following code in Notepad editor and save as event07.html.
<HTML>
<HEAD>
<TITLE>JavaScript text object</TITLE>
<SCRIPT type="text/javascript">
<!--
var num = 0;
function showLink(num)
{
if (num == 1) {
document.forms[0].elements[0].value = "one";
}
if (num == 2) {
document.forms[0].elements[0].value = "two";
}
if (num == 3) {
document.forms[0].elements[0].value = "three";
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.167
Open the event07.html file in a browser like IE, you will see the text object result as shown in Figure 6.8.
When you need a user to input more than just one line of text in a form you use the textarea input type. This is
the case if you are providing to the user an e-mail feedback form and want to allow space for the user to type in
a lengthy note. The syntax is:
<TEXTAREA
NAME = "textareaName"
ROWS = integer
COLS = integer
WRAP = on|off|physical|virtual
"onBlur = "handlerText"]
"onChange = "handlerText"]
"onFocus = "handlerText"]
"onSelect = "handlerText"]
TextToDisplay
</TEXTAREA>
A textarea object uses essentially the same attributes, methods and properties as does the text object. You
can use provide default text to display in this field by adding text between the TEXTAREA /TEXTAREA tags.
Example Write a JavaScript for textarea object event to check either a text contains a character f or
not using a checkF() function.
Solution Write the following code in Notepad editor and save as event08.html.
<HTML>
<HEAD>
<TITLE>JavaScript textarea object</TITLE>
<SCRIPT type="text/javascript">
<!--
function checkF()
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.168 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
{
var inputstr = document.myform.mytarea.value;
var lowerstr = inputstr.toLowerCase();
if (lowerstr == " ")
{
return;
}
if (lowerstr.indexOf("f") >= 0)
{
alert("You have got an F in there!");
}
else
{
if (lowerstr.length <= 20)
{
alert("Nice try, but too brief");
}
else
{
alert("Congratulations!");
}
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<P>The novel <I>Madding Crowd</I> does not contain a single "f".<BR>
Enter your new text given below :</P>
<HR>
<FORM NAME = "myform" METHOD = "POST" ACTION = "mailto:gbsahoo@yahoo.com">
<TEXTAREA NAME = "mytarea" ROWS = "4" COLUMNS = "80" onBlur = "checkF()">
</TEXTAREA>
</FORM>
<HR>
</BODY>
</HTML>
Open the event08.html file in a browser like IE, you will see the textarea object result as shown in Figure
6.9.
Open the event09.html file in a browser like IE, you will see the a test condition result as shown in Figure
6.10 on the next page.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.170 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
As we have discussed number of objects in our previous sections, all these are used on the Web to display text
or select options on form. There are other two form-based objects, submit and reset, which are accompanied
with an example of a simple mail-in form that checks the input before it is sent back to you.
The submit button was originally intended in HTML to be the final button a user would click to set a form back
to the server. It would submit information, set feedback or present a structured request for new information.
With JavaScript, you can now use this button to also send all of the information collected in a form to another
window on your browser or to the same window itself, which causes the contents of the window to change in
some way. An example of this is changing the background color of the window based on the users preference
on a form. The syntax is:
<INPUT
TYPE = "submit"
NAME = "submitName"
VALUE = "buttonText"
[onClick = "handlerText"]>
From the above syntax, you can access this objects properties and methods by the following:
x submitName.propertyName.
x submitName.methodName(parameters).
x formName.elements[index].propertyName.
x formName.elements[index].methodName(parameters).
When you click a submit button, it always loads a new pageeven if that page is the same page you were
already on. This is useful in that you can use a form to change attributes of the current page and see them
change when you submit the form. The submit object uses the onClick event handler and can be clicked by
using the submitName.click method.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.171
The reset button allows a user to completely reset a forms input field to their defaults. The syntax is:
<INPUT
TYPE = "reset"
NAME = "resetName"
VALUE = "buttonText"
[onClick = "handlerText"]>
From the above syntax, you can access this objects properties and methods by the following:
x resetName.propertyName.
x resetName.methodName(parameters).
x formName.elements[index].propertyName.
x formName.elements[index].methodName(parameters).
The reset button uses the same onClick event handler and click method as the submit object.
Example Write a JavaScript program to demonstrate the submit and reset button using three text
input values.
Solution Write the following code in Notepad editor and save as event10.html.
<HTML>
<HEAD>
<TITLE>JavaScript submit and reset objects</TITLE>
<SCRIPT type="text/javascript">
<!--
function first()
{
if (document.forms[0].elements[0].value == " ")
{
alert("Please put a name in the first field!");
}
}
function second()
{
if (document.forms[0].elements[2].value.length < 10)
{
alert("Please input at least 10 characters");
}
}
function third()
{
if (document.forms[0].elements[4].value == "No")
{
alert("Please change the third field value!");
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<center>
<h2>Enter the field values</h2>
</center>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.172 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
<HR>
<INPUT TYPE = "text" NAME = one VALUE = " "> Input your name (any text)
<INPUT TYPE = "button" NAME = check VALUE = checkme onClick = "first()"><p>
<INPUT TYPE = "text" NAME = two> Input at least 10 characters
<INPUT TYPE = "button" NAME = checktwo VALUE = checkme onClick = "second()"><p>
<INPUT TYPE = "text" NAME = three VALUE = "No"> Change this to something else
<INPUT TYPE = "button" NAME = three VALUE = checkme onClick = "third()"><p>
</FORM>
</BODY>
</HTML>
Open the event10.html file in a browser like IE, you will see the working of submit and reset buttons
result as shown in Figure 6.11.
When we design interactive form, the viewers probably also find our requests easier to understand in multiple
choice format. Understanding this aspect of form design, we have probably used radio buttons and checkboxes.
These are excellent devices for presenting a limited or fixed number of choices. But when we present the viewer
with a large number of choices, we use the SELECT object. This enables us to present a large list without
cluttering up our page. A good use would be geographical lists, such as states or countries in address forms.
Remember, SELECT is an element within a form, so it must be between the <FORM>. . . </FORM> tags.
The syntax is:
<SELECT
NAME = "selectName"
[SIZE = "integer"
[MULTIPLE]
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.173
[onBlur = "handlerText"]
[onChange = "handlerText"]
[onfocus = "handlerText"]
<OPTION VALUE = "optionValue" [SELECTED]> textToDisplay
[ . . . <OPTION> textToDisplay]
</SELECT>
The onLoad event handler is used to call the execution of JavaScript after a page, frame or image has completely
loaded. The onLoad events for the body, window and document objects are the same. They fire after all
objects in the DOM (Document Object Modelling) hierarchy have finished loading and the document object
has been built up. Let us look at three different possibilities onload event:
x <body onload="hello()">
Here, the execution of the code will begin after the page has loaded.
x <frameset onload="hello()">
Here, the execution of the code will begin after the current frame has loaded.
x <img src = "nation.gif" onload="hello()">
Here, the execution of the code will begin after the image has loaded.
Let us take another example
<html>
<head><title>Onload event example</title>
</head>
<body onload="alert('This page has finished loading!')">
Welcome to my home page
</body>
</html>
Example Write a JavaScript program to demonstrate the onload event for the body element to change
the background color of web page.
Solution Write the following code in Notepad editor and save as onloada.html.
<HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.174 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
<head>
<script type="text/javascript">
function bgcolor() {
alert ("The document has been loaded.");
document.body.style.backgroundColor = "aqua";
}
</script>
</head>
<body onload="bgcolor()">
</body>
</HTML>
When the above scripts executed, it first shows an asert message and then the background color of the
body will be changed.
The onUnLoad executes JavaScript immediately after someone leaves the page. A common use (though not
that great) is to thank someone as that person leaves your page for coming and visiting. onUnLoad occurs
when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser
window, etc.) For example,
<head>
<script type="text/javascript">
function OnUnLoadMe() {
alert ("The current document will be unloaded!");
}
</script>
</head>
<body onunload="OnUnLoadMe()">
<b>Close this window or press F5 to reload the page.</b>
</body>
The above code will display an alert window with message "The current document will be unloaded!",
when leaving the page.
onChange event is raised when the text in a select, text, or textarea form item is altered by the user. The
onChange is the most common event that you monitor in SELECT. It looks for change from one selection to
another. When the event is triggered, your code executes.
For example, let us take the countries in world. When we change a country selection from India to
Bangladesh, then onChange triggers a JavaScript function that changes the currency type from Rupees to
Taka. However, if you did not change the selection, the event would not trigger.
Example Write a JavaScript program to demonstrate the onChange event of SELECT object for
above problem specification.
Solution Write the following code in Notepad editor and save as event11.html.
<HTML>
<HEAD>
<TITLE>JavaScript onChange event of SELECT object</TITLE>
<SCRIPT type="text/javascript">
<!--
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.175
function changeCurrency(form)
{
form.currency.value=form.country.options[form.country.selectedIndex].value
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<P>Demonstrating <I>onChange</I> event :</P>
<B>Select your country</B><BR>
<SELECT NAME = "country" onChange = "changeCurrency(this.form)">
<OPTION VALUE = "Indian Rupees">India
<OPTION VALUE = "Bangladeshi Taka">Bangladesh
<OPTION VALUE = "US Dollars">USA
<OPTION VALUE = "UK Pound">United Kingdom
</SELECT>
<P><B>Prices are displayed in : </B><BR>
<INPUT TYPE = "text" NAME = "currency">
</FORM>
</BODY>
</HTML>
Open the event11.html file in a browser like IE, you will the onChange event of SELECT object result as
shown in Figure 6.12.
The onBlur event is a good way to verify proper selections. This event looks for when the focus is no longer
on the SELECT object. In other words, it looks for when you click somewhere other than the current element.
When the event is triggered, you could execute a verification function. Although you can use the onBlur event
to verify selections, using onBlur might ensure the viewers choice. This is because the onBlur event triggers
JavaScript code even if a change has not occurred. In other words, when the item loses focus, the onBlur event
is raised.
Verification is not always simply an either/or choice. For example, you might have a selection with some
uncommon, but acceptable answers. This might be an unusual color for a piece of merchandise. For this
circumstance, you might verify that this is indeed the correct selection, even if the user made no change in his
selection.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.176 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Example Write a JavaScript program to demonstrate the onBlur event of SELECT object. The script
will select an option and display appropriate message in the alert box.
Solution Write the following code in Notepad editor and save as event12.html.
<HTML>
<HEAD> <TITLE>JavaScript onBlur event of SELECT object</TITLE>
<SCRIPT type="text/javascript">
<!--
function checkEggs(form)
{
form.eggs.value=form.quantity.options[form.quantity.selectedIndex].value
// document.write(form.eggs.value);
var qty = form.quantity.selectedIndex;
if (qty == 0)
{
alert("Order generally placed as a dozen!");
}
}
<!-- end script -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<P>Demonstrating <I>onBlur</I> event. After you select a quantity, the number on-hold
is not updated until you click somewhere else.</P>
<B>Select the quantity</B><BR>
<SELECT NAME = "quantity" onBlur = "checkEggs(this.form)">
<OPTION VALUE = "6">Half dozen
<OPTION VALUE = "12">Dozen
<OPTION VALUE = "24">Two dozen
</SELECT>
<P><B>We are holding this many eggs for you :</B><BR>
<INPUT TYPE = "text" NAME = "eggs">
</FORM>
</BODY>
</HTML>
Open the event12.html file in a browser like IE, you will get the onBlur event of SELECT object result as
shown in Figure 6.13.
The onFocus is just opposite of onBlur. The onFocus is an excellent way to assist the viewer in completing
your form. It looks for the viewer moving the cursor to the SELECT element and then triggers code prior to any
entry by the viewer.
For example, each question in your form can include particular instructions that assist the viewer in making
a proper selection. When onFocus is triggered, your code could display in a separate window or frame the
instructions related to that question. Or if you require a numeric answer to be calculated, why not pop up a
calculator in a new window ? Let us start an example for demonstrating the onFocus event.
Example Write a JavaScript program to demonstrate the onFocus event of SELECT object.
Solution Write the following code in Notepad editor and save as event13.html.
<HTML>
<HEAD>
<TITLE>JavaScript onFocus event of SELECT object</TITLE>
<SCRIPT type="text/javascript">
<!--
function dispAns(form)
{
var opt = form.answer.selectedIndex;
if (opt == 2)
{
alert("Delhites forget metro trains run on two tracks.");
}
}
var result = 0;
function callCalculator(form)
{
if (result == 0)
{
result = 1;
alert("You are focused");
}
}
<! end scripts >
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<P>Demonstrating <I>onFocus</I> event.</P>
<B>Select the quantity</B><BR>
<P><B>DMRC railroad track is ordered for three sections of track. The first is 12 kilometers
long. The second is 24 milometers long and the third is 10 kilometers long. How many
kilometers of track needs to be order to complete construction ?
</B></P>
<P><B>What is your answer : </B></P>
<SELECT NAME = "answers" onFocus = "callCalculator(this.form)" onBlur =
"dispAns(this.form)">
<OPTION VALUE = "12">22
<OPTION VALUE = "24">28
<OPTION VALUE = "10">98
</SELECT>
</FORM>
</BODY>
</HTML>
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.178 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Open the event13.html file in a browser like IE, you will see the onFocus event of SELECT object result
as shown in Figure 6.14.
Write the code using JavaScript to display appropriate message on the windows status bar
as shown in the above figure. For example, if you
x click on text box, then it will display,
You have placed the cursor in the one-line text field!
x click on textarea box, then it will display,
You have placed the cursor in multipleline text field!
x click on option box, then it will display,
You have placed the cursor in Field of choice field!
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.179
Solution Write the following code in Notepad editor and save as onfocus.html.
<html>
<head>
<title>OnFocus example</title>
<SCRIPT type="text/javascript">
<!--
function message(field){
window.status="You have placed the cursor in the " + field + " field!"
}
//-->
</script>
</head>
<body>
<form>
<input type="text" onFocus="message('one-line text')">
<textarea rows=4 cols=20 wrap=virtual onFocus="message('multipleline text
')"></textarea>
<select onFocus="message('Field of choice')">
<option>Hill side
<option>River side
<option>Ocean side
<option>Heaven side
</select>
</form>
</body>
</html>
Example A web page used multiple objects with an alert window for Send button as shown below:
//-->
</script>
</head>
<body>
<form>
<input type="radio" name="Radio" onClick="Display('Radio Button1')">Option 1<br>
<input type="radio" name="Radio" onClick="Display('Radio Button2')">Option 2<br>
<input type="checkbox" onClick="Display('Check Button')">Check Button<br><br>
<input type="submit" value="Send" onClick="Display('Send Button')">
<input type="reset" value="Reset" onClick="Display('Reset Button')">
<input type="button" value="Personal" onClick="Display('Personal Button')">
</form>
</body>
</html>
With JavaScript, it is possible to execute some code at specified time intervals. This is called timing events. It
is very easy to time events in JavaScript.
VHW7LPHRXW 0HWKRG
The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
It allows code to be executed a set time after some trigger, such as when the page has loaded or a button is
pressed. This post looks at how to trigger events after a set time with Javascript and also how to clear the
timeout. The syntax is:
setTimeout("expression", delaytime)
Here, "expression" is the function/statement you want delayed, and delaytime is the delay time, in
milliseconds. Note that to get "1" second, we used "1000". (1 millisecond*1000) equals 1 second.
For example,
<input type="button" value="click me" onclick="setTimeout('window.alert(\'Hello!\')', 2000)" />
Here, the above code pop up an alsert box 2 seconds after the button is clicked.
Let us take another example, which calls a function instead when the button is clicked (timeout.html).
<HTML>
<HEAD>
<TITLE>Timeout example</TITLE>
<SCRIPT type="text/javascript">
<!--
function timeout_trigger() {
window.alert('Sorry for waiting me for 2 seconds!');
}
function timeout_init() {
setTimeout('timeout_trigger()', 2000);
}
<!-- end scripts -->
</script>
</HEAD>
<input type="button" value="Click Me" onclick="timeout_init()"/>
</HTML>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.181
Open the timeout.html file in a browser like IE, you will see the a Click Me button as shown in Figure
6.15.
Remember, the format of hours in JavaScript is from 0 to 23, not 1 to 24. So, display "12"
whenever hours=0.
Solution Write the following code in Notepad editor and save as timer.html.
<html>
<head>
<title>Live clock</title>
</head>
<form name="Timer">
<input type="text" size="12" name="Clock">
</form>
<SCRIPT type="text/javascript">
function showClock(){
var CDate = new Date() // Current date
var hours = CDate.getHours() // returns the hour (Starts from 0-23)!
var minutes = CDate.getMinutes() // returns the minutes
var seconds = CDate.getSeconds() // returns the seconds
var ampm = "AM"
if (hours > 12){
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.182 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
ampm = "PM"
hours = hours - 12// The hours written out is in 12-hour format,
// instead of the default 24-hour format.
}
if (hours == 0)
hours = 12 // this is so the hours written out when hours=0
// (meaning 12a.m) is 12
if (minutes <= 9)
minutes = "0" + minutes
if (seconds <= 9)
seconds = "0" + seconds
document.Timer.Clock.value = hours + ":" + minutes + ":" +
seconds + " " + ampm
setTimeout("showClock()", 1000)
}
showClock()
</script>
<html>
The basic concept is to continuously write to a form field every 1 second, using the updated time from your
own computer.
FOHDU7LPHRXW 0HWKRG
The clearTimeout() method is used to stop the execution of the function specified in the setTimeout() method.
The syntax is:
clearTimeout(setTimeout_variable)
Here, setTimeout_variable it the time which is the waiting time and set by setTimeout() method.
For example,
timeout = setTimeout('timeout_trigger()', 3000);
clearTimeout(timeout);
3RLQWVWR5HPHPEHU
1. Event handlers are JavaScript statements (usually functions) that are called whenever something
happens.
2. onClick event is raised when the user clicks on an object, e.g., button, image, hyper link etc.
3. onChange event is raised when the text in a select, text, or textarea form item is altered by the
user.
4. onBlur event is raised when a select, text, or textarea form item is acted upon and then moved
off of by the user.
5. onFocus event is raised when a select, text or textarea items is selected on an HTML form.
6. onSelect event, as its name implies, is raised when some text in a text box or text area is
selected.
7. onSubmit is an important event that is raised when the submit button on an HTML form is
clicked to submit the form data to the web server.
8. setTimeout, a method of the window object, basically delays the execution of a function or
statement until the specified time has passed.
9. The clearTimeout() method is used to stop the execution of the function specified in the
setTimeout() method.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.183
SOLVED EXERCISES
1. What are events?
Ans. Events are the actions or the happening of something on the machine and in the environment where the
program executes, e.g., the submission of a web form, clicking of a button, focusing an element,
hovering mouse over something, etc.
2. Differentiate between onload and onunload events.
Ans. The onLoad event is triggered when the user enters a webpage whereas the onUnload event is triggered
when the user leaves a webpage.
3. Define onfocus event.
Ans. The onfocus event fires when the user clicks on an element, usually <input> or <textarea> elements, and
the mousover event fires when the pointer mouses over any element on the page.
4. Write an HTML code using the JavaScript to enter the name and display the message "Hello " + name
as shown in following web page:
</FORM>
</BODY>
</HTML>
5. Write an HTML code using the JavaScript to enter the first name and last name and display the full
name uppercase in a textbox, i.e., first name + second name as shown in the following web page:
6. ABC Electronic Shop handles its sales on Internet and the company provides easy installments to his
customers. Consider the following web page layout:
The company appoints a lady for his front office to meet the customers need. The lady manages the
product and the payment mode as:
x The payment mode is either as cash or installment.
x If you choose cash down, then you will avail 5% discount.
x If you choose installment, then for 1 year the rate of interest is 5% and for the subsequent years an
additional 2 % will increase from the previous year.
Write an interactive HTML program with JavaScript to calculate the cash down price or monthly installment
price for same product.
Ans. The HTML coding is as : (eshop.html)
<HTML>
<TITLE>ABC Electronic Shop</TITLE>
<SCRIPT type="text/javascript">
function open1(form)
{
var amount = 0;
var opt = form.list.selectedIndex;
var opt1 = form.list1.selectedIndex;
//var opt1 = form.payment.value;
if (opt == 0)
{
amount = 10000;
}
else
if (opt == 1)
{
amount = 14000;
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.186 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
}
else
if (opt == 2)
{
amount = 5600;
}
if (document.frm1.payment[0].checked)
{
document.frm1.txt1.value = amount amount *.05;
document.frm1.txt2.value = " ";
}
if (document.frm1.payment[1].checked)
{
if (opt1 == 0)
{
document.frm1.txt1.value = amount + amount *.05;
document.frm1.txt2.value = Math.round((document.frm1.txt1.value)/12);
}
if (opt1 == 1)
{
document.frm1.txt1.value = amount + amount *.07;
document.frm1.txt2.value = Math.round((document.frm1.txt1.value)/24);
}
if(opt1 == 2)
{
document.frm1.txt1.value = amount + amount *.09;
document.frm1.txt2.value = Math.round((document.frm1.txt1.value)/36);
}
}
}
</SCRIPT>
<BODY>
<center>
<H1> A B C Electronics Shop </H1>
</center>
<HR ALIGN = "CENTER" SIZE = 5 WIDTH = 450 NOSHADE>
<H4>Select the item from the list</H4>
<FORM NAME = "frm1">
<SELECT NAME = "list" SIZE = 3>
<OPTION>TV!!
<OPTION>AC!!
<OPTION>Microwave!!
</SELECT>
<INPUT TYPE = "radio" NAME = "payment" VALUE = "1" CHECKED> Cash
<INPUT TYPE = "radio" NAME = "payment" VALUE = "2" > Installment
<SELECT NAME = "list1" SIZE = 3 >
<OPTION>One Year!!
<OPTION>Two Years!!
<OPTION>Three Years!!
</SELECT>
<INPUT TYPE = "button" NAME = checktwo VALUE = Tell_Amount
onClick = "open1(this.form)"><p>
<h5> Total Amount to be paid:</H6>
<INPUT TYPE = text" NAME = "txt1" VALUE = " " >
<h5> Monthly Installment:</H6>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.187
document.location = "http://www.rediff.com";
}
}
</SCRIPT>
<BODY>
<H4>Select a location from the list</H4>
<FORM>
<SELECT NAME = "list" SIZE = 3 onChange = "open1(this.form)">
<OPTION>Go to Yahoo!!
<OPTION>Go to Hotmail!!
<OPTION>Go to Rediff!!
</SELECT>
</FORM>
</BODY>
</HTML>
9. Consider the following web page layout:
Write the JavaScript code that needs to be embedded in the above HTML code to do the following:
x The click event of the first button should call a function bcolor() which will change the background
color entered by the user in textbox txt1.
x The click event of the second button should select a function imgselect() which will display the
image selected by the user in the file textbox txt2 in the space of the image img1.
Ans. The functions are : (colorimage.html)
<HTML>
<HEAD>
<TITLE>Background colorl</TITLE>
</HEAD>
<SCRIPT type="text/javascript">
<!--
// for changing the background color
function bcolor() {
var col = document.frm1.txt1.value;
document.bgColor = col;
}
function imgselect() {
var imgd = document.frm1.txt2.value;
document.write("<img" + " " + "name = " + "img1" + " " + "SRC = " + imgd + ">");
}
<!--end scripts -->
</SCRIPT>
<BODY>
<FORM name = "frm1">
<P>Enter background color:
<INPUT TYPE = "text" NAME = "txt1">
<INPUT TYPE = "button" VALUE = "Click to change color" onClick = "bcolor()"><BR>
Select image file:
<INPUT TYPE = "file" NAME = "txt2">
<INPUT TYPE = "button" VALUE = "Click to see image" onClick = "imgselect()"><BR><BR>
<IMG NAME = "img1" SRC = " " ALT = "Image will be loaded here" WIDTH = 200 HEIGHT =
200>
</FORM>
</BODY>
</HTML>
10. Consider the following page layout:
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.191
11. Pizza Hut company provides online services to his customer regularly with following details as shown
in the figure given below:
Write the JavaScript code for PlaceAnOrder() function which will be embedded in the above HTML
code for the click event of the button which will display the alert message with all details of the customer.
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.193
Write the JavaScript code for calculate() function which will be embedded in the above HTML code for
the click event of the button which will display the conversion value of Euro to its patner countries and
vice versa.
Ans. The JavaScript code is: (erocalculator.html)
<SCRIPT type="text/javascript">
<!--
var a = 0
function calculate(){
if (a == 0){
document.forms[0].euro.value=Math.round(document.forms[0].amount.value /
document.forms[0].currency[document.forms[0].currency.selectedIndex].value * 100) / 100
}
if (a == 1){
document.forms[0].amount.value=Math.round(document.forms[0].euro.value *
document.forms[0].currency[document.forms[0].currency.selectedIndex].value * 100) / 100
}
}
//-->
</script>
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.195
REVIEW QUESTIONS
1. What is an event?
2. What is an event handler? Write its syntax.
3. What is button object?
4. What is checkbox object?
5. What is the purpose of Radio object?
6. What is the use of password object?
7. Differentiate between text and textarea object.
8. What is the purpose of submit object?
9. What is select object?
10. What is onBlur event? Why is it called so?
11. What is onFocus event?
12. What is date object?
13. Write an HTML program using JavaScript to input your percentage of marks and display the grade as
explained below:
if StPer >= 90
document.write("Grade is A")
else
if StPer >= 80 Then
document.write("Grade is B")
else
if StPer >= 70 Then
document.write("Grade is C")
else
if StPer >= 60 Then
document.write("Grade is D")
else
document.write("Grade is F")
14. A government lab wants to install a security check system at the gate and only authorised personnel
may enter the office, using their security codes. The following are valid security codes:
100 200 Technicians
201 400 Custodians
401 600 Special Services
601 800 Chief Scientist
801 1000 Scientists
As an added security measure, the keypad treats any access more than 1000 as a panic code by
displaying the message in red colour. Once an access code is entered, access is either granted or denied.
If access is granted, then the Welcome message with blue background and group (i.e., scientist,
custodian, etc.) are written to the window. If access is denied, then the message Not Allowed with black
background will be displayed on the window.
15. The state electricity board generates monthly electricity bill to be computed as follows:
Minimum : Rs. 200 for first 100 units.
Plus Rs. 1.00 per unit for the next 100 units.
Plus Rs. 0.75 per unit for the next 100 units.
Plus Rs. 0.50 per unit for any unit beyond 300.
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
3.196 Saraswati Multimedia and Web Technology (XI)
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234
Write a program in Visual Basic which calculates the monthly bill for a customer based on the number of
units consumed selected by the user displayed using the radio button. Also implement this program
using the list option.
16. NHPC has different categories of workers, who are paid different hourly rates (R). Wages are then
determined after accepting the number of hours (H) one works during the week. The different classes are
paid as follows:
Category `)
Hourly Rate(`
Unskilled 25.00
Semi-skilled 35.00
Skilled 45.00
Write a program to input the hours of a worker and weekly wages using Option button.
17. Write an HTML program using JavaScript to select the name of the cricket player from the list and display
its record like Total runs, Number of 50s, 100s etc.
18. Read the following case study and answer the question that follows:
Mr. Nath of ABC Software Corporation has got requirement of a Software Project from a Customer in
Tours and Travel Business. He performed the preliminary analysis and found that software application
should be based on Client/Server technology. We had taken the excerpt from his analysis and present
you one of the forms to enquire about railway reservation.
Carefully observe the following picture.
Write a JavaScript function to check for the validity of the entered date value. Clear the textboxes for
invalid date value and set the focus on txtDD.
19. Sumeet Electronics has the following products with their list prices given. The store gives a 10%
discount on every product. However, at the time of festival seasons, the store gives a further 7% festival
discount after 10%.
Product List Price (Rs.) Discount Price
Washing Machine 12000 ---
Colour Television 17000 ---
Refrigerator 18000 ---
OTG 8000 ---
CD Player 4500 ---
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345
Working with Control Objects
3456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345 3.197
Write an HTML program using JavaScript to with a function to calculate the net price for a product. Enter
product name, list price and select either festival or not by clicking an option button as shown in the
form.
20. Write an HTML program using JavaScript to display the colors name using radio object and as the user
select any of the colour the background will be changed with that colour.
21. Write an HTML program using JavaScript to enter the URL of any site in the textbox and the program will
open that site as the user click on the Go button.
22. Write an HTML program using JavaScript to generate a simple calculator which will find the result when
you click on the = button.
23. Write a JavaScript (and the HTML page) that asks for the users name and then tells the user how many
characters are in his/her name.
24. Write a script and page that show an alert box when the user clicks an anchor link.
25. Write a JavaScript that determines whether or not a number entered in a textbox is 786.
26. Write an HTML application in which is displayed the code of the courses in the list and student will enter
their marks in the text and use JavaScript to know whether the student is eligible for the course or not.
27. Akash International Tourism arranges tours for its customers in India. He manages his tour in two
service packages: Normal and De Luxe. Consider the following page layout: