Beginning HTML

CHAPTER 1
Beginning HTML
12345678901234567890123456789012123
12345678901234567890123456789012123
1.0
Objectives
12345678901234567890123456789012123
12345678901234567890123456789012123
1.1
Introduction
12345678901234567890123456789012123
1.1.1 What is HTML
12345678901234567890123456789012123
12345678901234567890123456789012123
1.1.2 The HTML Specification
12345678901234567890123456789012123
12345678901234567890123456789012123
1.2
Creating
an HTML Document
12345678901234567890123456789012123
12345678901234567890123456789012123
1.2.1 Structure of an HTML Document
12345678901234567890123456789012123
1.2.2 HTML Tags
12345678901234567890123456789012123
12345678901234567890123456789012123
1.3
The First Web Page
12345678901234567890123456789012123
12345678901234567890123456789012123
1.4
Summary
12345678901234567890123456789012123
12345678901234567890123456789012123
1.5
Check Your Progress-Answers
12345678901234567890123456789012123
1.6
Questions
for Self-Study
12345678901234567890123456789012123
12345678901234567890123456789012123
1.7
Suggested Readings
12345678901234567890123456789012123
12345678901234567890123456789012123
1.0 Objectives
After studying this Chapter you will be able to understand the definition of HTML
and terminologies like hypertext, markup etc.
- Study what an HTML page is made up of the Head section and the Body section
- Study what are tags, understand start tags and end tags, and empty and non empty
tags, tag attributes and attribute values - to create a first sample HTML page
1.1 Introduction
An international network of computers which exchange information is the Internet.
It is a way for computers to communicate. It can also store information in different
ways. The foundation of the Internet was laid in the mid 1960s as a project of the
Defence Department of the United States. They devised a way of communication
between the various research institutions. In order to achieve this they developed
protocols i.e. a set of rules for computers to communicate with each other. The internet
as we see today is also based on these protocols.
The concepts of a client and server exist on the Internet. A server is a computer
which provides the information (service provider), while a client is a computer which
requests or seeks information (service requester).
The Features of the Internet are :
Email : This is a very popular activity made possible by the computer
communications. E mail is a very useful form of communication between people the
world over. With email you can send mail, receive mail, forward mails which you have
received, create an electronic address book and many more things.
FTP(File Transfer Protocol): This is a way of exchanging files. A file (it can be
text, programs, images etc.) is put on the server. Using the FTP client, anyone can
call the FTP server and request that file.
NNTP (Network News Transfer Protocols) : There is a facility for you to read
and write articles in a newsgroup. Messages can be distributed on a worldwide bulletin
board on almost any topic. The name of this bulletin board is Usenet.
To Connect to the Internet:
In order to be able to view and use the vast amount of information available on
the Internet you have to connect to the internet. To connect to the Internet you need:
TCP/IP (Transfer Control Protocol/Internet Protocol) : This protocol routes
information from the Internet to your computer, and from your computer to the Internet.
Beginning HTML / 1
ISP Internet Service Provider: It offers access to the internet. Your ISP
account includes an email id and an account with some storage space on a computer
on the net. Your storage space is given the same name as your user name.
A modem (Modulator and Demodulator): It is a device that modulates an
analog carrier signal to encode digital information, and demodulates the signal to
decode the transmitted information. You make use of the modem to dial your ISP, and
with the associated software you get connected to your ISPs computer. Thus you log
in to your account. From this point on, you can start using the Internet.
The modem receives and transmits information using telephone lines. The TCP/
IP routes the information to the destination.
Some common terms and their meanings :
Let us now see some common terms used in connection with the Internet:
The World Wide Web (WWW): WWW is not the Internet but a service available
on the Internet. The WWW is a vast network of HTTP servers sending files across the
Internet. HTTP (Hypertext Transfer Protocol) is nothing but a Internet protocol.
Web Browsers : You need tools to access the information on the Internet.
These internet tools are the web clients and are known as browsers. The two most
popular browsers are the Netscape’s Navigator and Microsoft’s Internet Explorer.
Web Page : A Web page is a special type of file written in HTML. You can
create your own web pages. In order that people all over the world can see your web
page, you have to publish the Web page. This means that you transfer your web page
to a place from where it will be served by an HTTP server.
1.1.1 What is HTML?
HTML or Hypertext Markup Language is used to create web pages. HTML is
relatively easy to learn. Anyone can learn HTML and create attractive web pages.
A scripting language differs from the programming languages like C or Pascal.
In a programming language, both application files and data files are involved. However,
in HTML the content (information to be displayed on the Web Page) and the instructions
(how to display the content) are contained in the same file (HTML document).
A markup language is a language which classifies the different parts of a
document according to their functions. i.e it clearly indicates which part is the title,
which part is a subheading, which part is to be highlighted etc. HTML uses a set of
tags which tell the browser what to display and how to display. The web browser
interprets these HTML tags (commands) and displays the HTML document on your
computer.
An HTML document is commonly called as a web page.
A web page is made up of:
(i) the content: i.e the text and images in the page.
(ii) the instructions : these are the HTML tags which instruct the browser
the way in which to display the content.
HTML has been designed to work on a wide variety of platforms. A platform is
the combination of your hardware and the operating system that you are using. HTML
works on ordinary PC platforms like IBM PCs and Macintosh and also on graphical
workstations, network computers and hand held devices.
1.1.2 The HTML specification :
Having understood the definition of HTML let us now just see what is the HTML
specification. The official technical rules of HTML are known as the HTML specification.
These include the definitions and usage of the complete tag set, the tag attribute set
and character reference entities. This HTML specification is maintained by the World
Wide Web Consortium (W3C).
Advanced Web Designing / 2
1.1
Fill
a)
b)
c)
d)
e)
Check Your Progress.
in the blanks.
An HTML document is normally called as a .........................
HTML is a......................... language.
The HTML document is made up of the .................... and the.........................
The HTML specification is maintained by the ..........................
The .........................is a combination of your hardware and the software
that you are using.
1.2 Creating an HTML Document
Equipped with this background we shall now see how to create an HTML document.
An HTML document can be created using any text editor, wordprocessor or a special
HTML editor. An HTML document has to be in ASCII format. ASCII format is also
called as plain text or DOS text format.
1.2.1 Structure of an HTML document:
An HTML document is made up of two sections :
(i) The Head Section : The head section contains information related to the web
page eg. the title of the document. Any data which is provided in the Head section will
not appear in the viewing area of the web browser.
(ii) The Body Section : All information contained in the body section is displayed
in the browser. The way in which this information is to be displayed is instructed to the
browser with the help of HTML tags.
1.2.2 HTML Tags :
A tag is a unit of markup. It is also called an element. Every tag in HTML has
a meaning. Tags are the most essential elements of HTML necessary to create web
pages. These tags define the structure and the behaviour of the different parts of the
HTML document.
l Tag Syntax :
HTML tags have a specific syntax. Tags start with a less than (<) sign, followed
by the keyword (tag element) and end with the greater than (>) sign. When the tags
are to be used in the HTML document, they have to be written in this specific manner.
Tags written in any other way are not understood by the browser.
l Start Tags and End Tags :
Start tags : Start tags are used to begin an effect. A start tag begins with (<)
sign followed by the tag element and ends with the (>) sign.
End tags :The end tags are used to end the effect. An end tag also begins with
(<) sign, it has an additional forward slash (/) immediately after the less than (<) sign.
This is followed by the keyword and the tag is closed with the greater than (>) sign.
eg.
Start Tag : <TITLE>
End tag : </TITLE>
It is in between the start tag and the end tag that you have to
insert the text to which the effect of the tag is to be applied.
eg. <TITLE>The Beginning of My Course in HTML</TITLE>.Thus the effect of the
TITLE tag will be applied to the text “The Beginning of My Course in HTML”.
l Empty and Non-Empty Tags :
Beginning HTML / 3
Non empty tags are those tags which have both the opening (start) and closing
(end) tags with the text in between. There should be no spaces between the opening
tag and the first word of the text as well as between the last word of the text and the
closing tag. Thus non empty tags are in the form of a tag set. Empty tags on the other
hand are stand alone single elements. They are not in the form of a tag set.
l Tag Attributes : Tag attributes (parameters) are elements which modify the
effect or behaviour of a tag. A tag attribute is placed within the start tag immediately
after the tag element with a single space in between the tag and the attribute.
Not all HTML tags have attributes and some tags have multiple attributes.
l Attribute values:
The attribute of a tag takes values. These attribute values of the tag can be
specified either as a relative value (eg. percentages or direction) or absolute values.
It is important to note that the tags are not displayed on the web page. Instead
their effect is applied to the text and the text with the applied effects is displayed. The
browser simply ignores any tags and attributes which are unknown. It does not indicate
any errors. Tags are not case sensitive. They can be either in upper case or lower case.
1.2
Check Your Progress.
Answer in 1-2 sentences.
a)
b)
c)
d)
What is the structure of an HTML document?
.............................................................................................................
.............................................................................................................
What are start tags and end tags?
.............................................................................................................
.............................................................................................................
What are empty and non-empty tags?
.............................................................................................................
.............................................................................................................
What is meant by tag attributes?
.............................................................................................................
.............................................................................................................
1.3 The First Web Page
We are now ready to create our first web page. We shall create our first HTML
document by following these steps :
1)
Start your text editor and type the following code :
<HTML>
<HEAD>
<TITLE>Beginning HTML</TITLE>
</HEAD>
<BODY>
Welcome to My First Web Page
</BODY>
</HTML>
2)
Save the document with the extension .HTML
3)
Now open the browser (Internet Explorer or Netscape Navigator)
4)
In the browser open the HTML document with the help of the File Menu.
Advanced Web Designing / 4
The browser will display the contents of your HTML document.
With this example let us understand the basic structure of an HTML
document.
1.
The HTML document starts with the <HTML> tag. This defines an HTML document.
2.
The Head section starts with the <HEAD> tag.
3.
The <TITLE> tag is placed in the HEAD section. The Navigator displays this title
in the title bar at the top of the browser’s window.
4.
The title of the document is to be typed immediately after the <TITLE> tag and
is to be closed with the </TITLE> tag.
5.
The Head Section is closed with the </HEAD> tag.
6.
After closing the Head section, start the Body section with the <BODY> tag.
7.
In this Body tag, type the required text and then close the body section with the
</BODY> tag. The information in this body tag will be interpreted by the browser
and displayed in the browser window. In our case, “Welcome to My First Web
Page” will be displayed by the browser in the window.
8.
To indicate the end of the HTML document, type the </HTML> tag.
HTML tags are nested in a specific way. It is important to note the way in which
these tags are nested. The entire document has to be nested within the <HTML>and
</HTML> tags. The <HEAD> and </HEAD> tags are contained in these tags, and
these in turn nest the <TITLE> and </TITLE> tags. After closing the Head section the
<BODY> section is opened. The information to be displayed is contained this section
and the </BODY> tag closes the body section. The <BODY> and </BODY> tags are
also to be nested in the <HTML> and </HTML> tags.
As has already been stated HTML tags are not case sensitive. However, in this
self learning material, we shall write all the HTML tags in the upper case in order to
distinguish them from the actual text.
1.3
Fill
a)
b)
c)
d)
Check Your Progress.
in the blanks.
The HTML document starts with the ......................... tag.
The title is displayed in the ......................... bar of the browser window.
The <BODY> section is nested in the ......................... tag set.
The ......................... displays the contents of the HTML document.
1.4 Summary
HTML or Hypertext Markup Language is used to create web pages. A markup
language classifies the different parts of a document according to their functions. HTML
uses a set of tags which tell the browser what to display and how to display. An HTML
document is commonly called as a web page.
A web page is made up of the content and the instructions : (these are the HTML
tags which instruct the browser the way in which to display the content.)
The official technical rules of HTML are known as the HTML specification. These
include the definitions and usage of the complete tag set, the tag attribute set and
character reference entities.
An HTML document is made up of two sections :
(i) The Head Section : The head section contains information related to the web
page eg. the title of the document. Any data which is provided in the Head section will
not appear in the viewing area of the web browser.
(ii) The Body Section : All information contained in the body section is displayed
Beginning HTML / 5
in the browser. The way in which this information is to be displayed is instructed to the
browser with the help of HMTL tags.
HTML tag is a unit of markup. It is also called an element. These tags define
the structure and the behaviour of the different parts of the HTML document. HTML tags
have a specific syntax. Tags start with a less than (<) sign, followed by the keyword
(tag element) and end with the greater than (>) sign.
Start Tags and End Tags : Start tags are used to begin an effect. A start tag
begins with (<) sign followed by the tag element and ends with the (>) sign. The end
tags are used to end the effect. An end tag also begins with (<) sign, it has an
additional forward slash (/) immediately after the less than (<) sign. This is followed by
the keyword and the tag is closed with the greater than (>) sign.
Empty and Non-Empty Tags : Non empty tags are those tags which have both
the opening and closing tags with the text in between. Empty tags on the other hand
are stand alone single elements. They are not in the form of a tag set.
Tag Attributes : Tag attributes (parameters) are elements which modify the effect
or behaviour of a tag. A tag attribute is placed within the start tag immediately after the
tag element with a single space in between the tag and the attribute. The attribute
values of the tag can be specified either as a relative value or absolute values.
It is important to note that the tags are not displayed on the web page. Instead
their effect is applied to the text and the text with the applied effects is displayed.
1.5 Check your Progress - Answers
1.1
a)
b)
c)
d)
e)
a)
b)
c)
d)
Web page
scripting
content, instructions
World Wide Web Consortium (W3C)
platform
1.2
A tag is a unit of markup also called an element. Tags in HTML define
the structure and behaviour of the different parts of the document.
Start tags begin an effect and end tags end the effect. In between the
start tags and end tags, the text to which the effect of the tag is to
be applied is entered.
Empty tags are stand alone single elements. Non empty tags are
those tags which have both the opening and the closing tag.
Tag attributes are elements which modify the effect or behavior of a
tag.
1.3
a)
b)
c)
d)
HTML
title
<HTML> </HTML>
browser
1.6 Questions for Self - Study
1.
Write a short note on what is HTML.
2.
What is a HTML document made of ?
Advanced Web Designing / 6
3.
What are HTML tags? What do you mean by Start Tags and End Tags? Differentiate
between Empty and Non Empty tag sets.
4.
What are the steps involved in creating an HTML document and viewing the web
page in the browser ?
5.
Discuss the basic structure of an HTML document and nesting of HTML tags.
1.7 Suggested Readings
1.
Internet and world wide web: how to program / P. J. Deitel, H. M.
Deitel
2.
Advanced internet programming : technologies and applications /
Sergei Dunaev
3.
WWW.W3Schools.com
4.
www.html.net
uuu
Beginning HTML / 7
NOTES
Advanced Web Designing / 8
CHAPTER 2
Block
Level and Text Level Elements
1234567890123456789012345678901212345
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.0
Objectives
1234567890123456789012345678901212345
2.1
Introduction
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.2
Block Level Elements
1234567890123456789012345678901212345
2.2.1 The Heading Tag
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.2.2 The Paragraph <P> Tag
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.2.3 The Center Tag
1234567890123456789012345678901212345
2.2.4 Block Quote <Block quote> Tag
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.2.5 Horizontal Rule <HR> Tag
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.2.6 The Preformatted <PRE> Tag
1234567890123456789012345678901212345
2.2.7 Lists
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.3
Text
level Elements
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.3.1 The <Font> Tag
1234567890123456789012345678901212345
2.3.2 The <Basefont> Tag
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.3.3 The <BIG> & <Small Tag>
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.3.4 The Bold <B>, Italic <I> & Underline
1234567890123456789012345678901212345
<U> Tags
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.3.5 The Strike Tag
1234567890123456789012345678901212345
2.3.6 The Teletype Tag <TT>
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.3.7 The Superscript <SUP> & <Subscript>
1234567890123456789012345678901212345
1234567890123456789012345678901212345
Tag
1234567890123456789012345678901212345
2.3.8 The <BR> Tag
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.3.9 The Quote <Q> Tag
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.4
Head Selection Elements
1234567890123456789012345678901212345
2.5
Using Comments
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.6
Summary
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.7
Check Your Progress - Answers
1234567890123456789012345678901212345
2.8
Questions for Self - Study
1234567890123456789012345678901212345
1234567890123456789012345678901212345
2.9
Suggested Readings
1234567890123456789012345678901212345
2.0 Objectives
–
–
–
–
After studying this Chapter you will be able to explain The difference between Text Level and Block Level Elements
Some commonly used Text Level and Block Level Elements
Head slection elements
Comments
2.1 Introduction
As we have already seen in the previous chapter, an HTML document is made
up of two sections the Head Section and the Body Section. In this chapter, let us learn
the elements which can be used in the Body Section of an HTML document. The
elements which are used in the Head section are described very briefly at the end of
this chapter.
There are two types of Body section tags : Block Level Elements and Text
Level Elements. Block Level Elements are used to define sections of text like paragraphs
whereas Text Level Elements are applied to smaller bits of text (which may be just a
few words or a line). Here we shall see the commonly used Block Level and Text Level
elements and their attributes. It may not have been possible to include all the HTML
elements, nevertheless most useful tags have been discussed.
2.2 Block Level Elements
These elements are used for blocks of text and paragraphs. Block level elements
Block Level and Text Level Elements / 9
are also used to create lists.
2.2.1 The Heading Tag :
HTML defines six levels of Heading from <H1> to <H6>. The level <H1> is the
largest level and the level <H6> is the smallest level. Heading level tags represent a
relative text sizing. They do not define absolute font sizes. Headings are normally used
to organise the document in sections. Heading level text is always formatted in bold.
Note that these are non-empty tag sets and require the end tags.
l The attributes of the Heading Tag :
The Heading tags can take the ALIGN attribute. The ALIGN attribute will control
the horizontal alignment of the heading. The default alignment of the heading is left.
This attribute can be assigned values as follows :
ALIGN=”LEFT”
ALIGN=”CENTER”
ALIGN=”RIGHT”
ALIGN=”JUSTIFY”
Let us see an example of defining the Heading Levels in an HTML document.
Create the following HTML document with your text editor:
<HTML>
<HEAD>
<TITLE>Practice with the Heading Levels</TITLE>
</HEAD>
<BOOY>
<H3 ALIGN=”CENTER”>The Six Heading Levels</H3>
<H1>This is Heading Level 1</H1>
<H2>This is Heading Level 2</H2>
<H3>This is Heading Level 3</H3>
<H4>This is Heading Level 4</H4>
<H5>This is Heading Level 5</H5>
<H6>This is Heading Level 6</H6>
</BODY>
</HTML>
Save this document with a name and extension .HTML. In order to view the effect
of the Heading tag, you should view this document in your browser.
When you open this page in the browser, you will see the six different levels of
heading Also notice the use of the ALIGN attribute in the code <H3 ALIGN CENTER”>The
Six Heading Levels</H3>. This will display the words ‘The Six Heading Levels” at the
center with the heading level H3.
2.2.2 The Paragraph <P> tag :
This tag is used for paragraphs. The <P> tag marks the beginning of a paragraph.
You can” divide your text into different paragraphs with the <P> tag. Normally, HTML
ignores white spaces i.e. even if you type a carriage return in your document, the
browser ignores it while displaying the text. It appears on the same line. The <P> tag
forces the text following the <P> tag is to the next line. By default, the text is left
justified.
Let us see the use of the Paragraph tag with the following example :
<HTML>
<HEAD>
<TITLE>The Use of the Paragraph Tag</TITLE>
</HEAD>
<BODY>
<P> Sarojini Naidu was born in 1879. She died in 1949. Thus, she lived during
the days of India’s struggle for freedom from the British rule.
<P>ln the early days of her life, she wrote beautiful poems in English. She also
recited them in her sweet voice.,Her voice was so sweet that people called her ‘The
Nightingale of India.
Advanced Web Designing / 10
<P>One day, she recited her poems to Gopal Krishna Gokhale in Pune. Gokhale
was charmed. But he advised her to serve India with her gifts of speech and song. She
then took a vow to serve India while she lived.
<P>lndia became free on August 15, 1947. Later, Sarojini Naidu became the
Governor of Uttar Pradesh. She was the first woman to hold such a high position.
</BODY>
</HTML>
At every instance of the Paragraph <P> tag, the text following the tag will be
forced to the new line. The Paragraph tag is a empty tag and does not require </P>
to mark the end of the paragraph.
2.2.3 The Center <CENTER> Tag :
The center tag center aligns large blocks of text. It can be used with other block
level elements.
2.2.4 BlockQuote <BLOCKQUOTE> tag :
The <BLOCKQUOTE> tag is used for indenting text. It is normally used for
quotes and citations. This tag indents both the left and right margins. <BLOCKQUOTE>
is a non empty tag set. The text enclosed within the <BLOCKQUOTE> tag is displayed
Bold.
<HTML>
<HEAD>
<TITLE>To use the BlockQuote</TITLE>
</HEAD> <BODY>
<H2 ALIGN=CENTER> Let us see the Use of the BLOCKQUOTE
Tag</H2>
<BR> Without the use of the BLOCKQUOTE <BR>
<H3>Swaraj is my Birthright and I shall have it</H3>
<BR> When the BLOCKQUOTE is used, the quote will be indented and
will appear as : <BR>
<H3><BLOCKQUOTE>Swaraj is my Birthright and I shall have it </
BLOCKQUOTE></H3>
</BODY>
</HTML>
In this example, we have made use of the <BR> tag. The <BR> (break) tag is
a text level element which is used to cause a line break. We shall discuss the <BR>
tag in detail when we see the text level elements.
2.2.5 Horizontal Rule <HR> tag :
The horizontal rule tags places a shaded horizontal line in the web page. A
horizontal line is also called as a rule. The <HR> is an empty tag. The horizontal rule
has four tag attributes :
WIDTH: Width attribute can be specified either as a numeric value or a percentage.
It determines the length of the rule. A numeric value is measured in number
of pixels. A percentage will specify the width in terms of percentage of page
width.
SIZE : Size will determine the thickness of the rule as measured in pixels. If no size
is specified the rule is displayed with a size equal to 2.
ALIGN : This will position the line either flush left, flush right or centered. The values
that this attribute takes are : LEFT, RIGHT, CENTER.
NOSHADE : This attribute creates a solid color fill line rather than the default
shaded line.
Block Level and Text Level Elements / 11
You can use multiple attributes with the <HR> tag at the same time.
We shall see the use of the <HR> tag when we discuss lists.
2.2.1 TO 2.2.5 Check Your Progress.
1.
a.
b.
c.
d.
e.
2.
a)
b)
c)
d)
e)
Match the following.
Column A
Column B
Horizontal Rule Tag
(i) Indents the text from both sides
Blockquote Tag
(ii) Center align blocks of text
Center Tag
(iii) Empty tag
Heading Tag
(iv) Takes six different levels
Paragraph tag
(v) To draw rules
Fill in the blanks.
ALIGN attribute of the Heading Tag controls the ......................... alignment
of text.
The ......................... attribute of the <HR> tag determines the thickness of
the rule.
By default the text in the <P> tag is ......................... justified.
The smallest Heading level is ....................and the largest is ..........................
The WIDTH attribute of the <HR> tag determines the ................. of the rule.
2.2.6 The Preformatted <PRE> Tag :
This tag will allow you to include preformatted text (text which has already been
formatted) in your document. It will instruct the browser to display the text exactly as
it has been typed in the document including the white spaces. The text is not wrapped
automatically by the browser. This tag can be used to present tabular data easily and
quickly. The text included in the <PRE> tag is monospaced. (typically in the Courier
Font). <PRE> tag is a non empty tag set. This tag takes one attribute :
WIDTH=”NUMBER”
The number will indicate how wide the text is in terms of columns. However, this
attribute may not be supported by some browsers.
The use of the Preformatted tag will be clear from the following example.
<HTML>
<HEAD>
<TITLE>Preformatted Text</TITLE>
</HEAD>
<BODY>
<H4>Without Preformatted Tag :</H4>
Some day I think I’ll travel<BR>
And visit every land,<BR>
And learn to speak the language<BR>
That each child can understand<BR>
<H4>With the Preformatted Tag :</H4>
<PRE>
Some day I think I’ll travel
And visit every land,
And learn to speak the language
That each child can understand</PRE>
</BODY>
</HTML>
Notice in this example, that although the text has been indented in the HTML
code, in both places i.e without using <PRE> tag and with using <PRE> tag the text
will appear as has been typed and monospaced only when the <PRE> tag is used.
In case, where the <PRE> tag is not used, the text formatting is not effected by the
Advanced Web Designing / 12
browser and the white spaces and line breaks are ignored.
2.2.7 Lists :
Another type of Block Level Elements are lists. Lists are used to organise text
and structure information. There are three types of lists : Unordered Lists, Ordered Lists
and Definition Lists.
l Unordered Lists : These are also known as Bullet lists. Each item in the unordered
list is preceded by a bullet. The tag of the Unordered List is <UL>. Each indivisual
item in the unordered list is preceded by the List Item <LI> tag. The <UL> is a
non empty tag set whereas the <LI> is an empty tag. Both <UL> and <LI> have
the same set of attributes, where the attribute value indicates the type of the bullet.
eg. TYPE=”CIRCLE”
TYPE=”DISC”
TYPE=”SQUARE”
It is also possible to nest one list inside the other and thus create sub
lists.
l Ordered Lists : Ordered List uses the <OL> tag. Ordered lists are also referred to
as numbered lists. Ordered list is similar to the unordered list except that is uses
numbers in the place of bullets. Ordered lists should also contain the List Item <LI>
element which precedes each indivisual element in the list. The attributes which can
be used with the <OL> tag are :
TYPE=”1"
(Arabic Numbers)
TYPE=”a”
(Lowercase Alphanumeric)
TYPE=”A”
(Uppercase Alphanumeric)
TYPE=”i”
(Lowercase Roman Numbers)
TYPE=”I”
(Uppercase Roman Numbers)
START=”X”
(The numbering sequence of the list items begins with X)
The default numbering system is Arabic numbers.
With the following example the use of ordered and unordered lists can
be seen.
<HTML>
<HEAD>
<TITLE>Using Lists</TITLE>
</HEAD>
<BODY>
<H4 ALIGN=LEFT>Unordered List of Flowers</H4>
<UL>
<LI>Rose
<LI>Jasmine
<LI>Dahlia
<LI>Carnation
<LI>Gladioli
</UL>
<H4>Ordered List of Colors</H4>
<OL>
<LI>Red
<LI>Green
<LI>Purple
<LI>Orange
<LI>Blue
</OL>
</BODY>
</HTML>
Here, you will see that the unordered list items are bulleted and the ordered list
items are numbered. Since the TYPE attribute is not used, the default attribute value
circle for bulleted list and Arabic numbers for numbered lists is displayed with the list
item. There is no need to use the <BR> tag to force the List Item to the new line. The
<LI> tag will by default take the next list item to the new line.
Block Level and Text Level Elements / 13
We shall see another example of lists to see the effect of the TYPE attribute,
we shall also create rules in the page using <HR> Horizontal Rule tag.
<HTML>
<HEAD>
<TITLE>Using Lists</TITLE>
</HEAD>
<BODY>
<HR WIDTH=180 SIZE=6 ALIGN=LEFT>
<H4 ALIGN=LEFT>Unordered List of Flowers</H4> <UL TYPE=square>
<LI>Rose
<LI>Jasmine
<LI>Carnation
</UL>
<HR WIDTH=180 SIZE=2 ALIGN=LEFT>
<H4>Ordered List of Colors</H4>
<OL TYPE=a>
<LI>Red
<LI>Green
<LI>Purple
</OL>
</BODY>
</HTML>
As can be seen in this example, a Horizontal rule of width 180 and size 6, is
displayed in the browser above the unordered list. In the unordered list, the list items
will be preceded by a square bullet. A horizontal rule of size 2 appears after the
unordered list. Then the ordered list, where the list items are preceded by the lowercase
alphabets is displayed in the browser window.
l The Definition Lists :
Definition List element is used to create definition lists. The definition list tag is
<DL>. The <DT> tag is used for the term that is to be defined. The <DD> tag is used
for the actual definition of the term.
eg. <DL>
<DT> Definition Term 1
Advanced Web Designing / 14
<DD> Actual Definition of Definition Term 1
<DT> Definition Term 2
<DD> Actual Definition of Term 2
</DL>
Some other Block Level Tags include the <DIV>, <SECTION>, <FORM>,
<TABLE> etc. Out of these, we shall discuss the <FORM> and <TABLE> elements
later. The remaining are left to the student for self study.
2.2.6 & 2.2.7 Check Your Progress.
1.
a)
b)
c)
d)
2.
a)
b)
c)
Fill in the blanks.
The ......................... tag instructs the browser to display the text exactly
as it has been typed in the document including the white spaces.
Unordered List items are preceded by a .........................
Ordered List items are preceded by a ..........................
The attribute that the list items take is .........................
Answer in 1-2 sentences.
What are the different types of lists?
.............................................................................................................
.............................................................................................................
What is the difference between ordered lists and unordered lists?
.............................................................................................................
.............................................................................................................
Which are the tags which are associated with Definition lists?
.............................................................................................................
.............................................................................................................
2.3 Text Level Elements
After studying the block level elements, let us now see what are text level
elements. Text level elements are normally used for words and sentences. They markup
small bits of text and help to change their appearance.Text level elements do not start
new paragraphs. Text level elements may be nested within one another, however
they cannot contain block level elements.
We shall now see some commonly used text level elements :
2.3.1 The Font <FONT> tag :
The <FONT> element allows you to change the size, colour or typeface of the
text in a web page. This is a non empty tag set and has three associated tag
attributes. At least one attribute has to be used with the <FONT> tag.
The attributes of the <FONT> element are as follows :
COLOR : This will allow you to specify the color of the text. Color can be
specified either with a name or a RGB color code. The RGB color code is a six digit
color code, which is a hexadecimal number preceded by the # sign.
eg. <FONT COLOR=green> or <FONT COLOR=#808000>
Note that if the Font color is specified as a RGB value, then the RGB color code
is to be preceded by the # sign. Here are a few RGB color codes and their names:
COLOR
RGB Code
COLOR
RGB CODE
black
#000000
green
#008000
red
#FF0000
purple
#800080
white
#FFFFFF
yellow
#FFFF00
fuchsia
#FF00FF
teal
#008080
Block Level and Text Level Elements / 15
SIZE : In HTML, the size of the words is not specified using point as in word
processors. You have only seven sizes for the font size, with size 1 being the smallest
and size 7 being the biggest. Size can be specified as absolute values or relative
values. The <FONT> element is a non empty tag set.
eg. <FONT SIZE=5> Here the Font size is specified as an absolute value.
<FONT SIZE=+1> In this case the text will be displayed one size bigger than
the normal text.
FACE : This is used to specify the font face eg. ARIAL, VERDANA etc. This
attribute can also allow you to specify a list of fonts separated by commas in the order
of your preference. Thus, if the font face that you have specified first, is not available,
then the second font face would be selected.
It is possible to specify more than one attribute in the <FONT> tag. However,
the <FONT> tag should have atleast one attribute.
We shall see the effect of the <FONT> tag and its attributes with the following
example :
<HTML>
<HEAD>
<TITLE>Practising Fonts</TITLE>
</HEAD>
<BODY>
Using the FONT Tag <BR>
<FONT SIZE=4 COLOR=GREEN>Absolute Font Size is 4, Color is
GREEN</FONT> <BR>
<FONT SIZE=+2 COLOR=RED>Relative Font Size of +2, Color is RED</
FONT> <BR>
<FONT SIZE=-3 COLOR=TEAL>Relative Font Size of -3, Color is TEAL</
FONT><BR>
<FONT SIZE=1 COLOR=BLUE>Absolute Font Size 1, Color is BLUE</
FONT><BR>
<FONT SIZE=4 COLOR=BROWN FACE=VERDANA>Change the Font Face
to VERDANA</FONT><BR>
<FONT FACE=CITYBLUEPRINT SIZE=5>Font Face is City Blue Print</
FONT><BR>
</BODY>
</HTML>
2.3.2 The <BASEFONT> Tag :
This tag establishes the default font size for the entire web page. Once this tag
has been placed in your <BODY> tag, all the other text and <FONT> tags are used
relative to this tag. This tag has no effect on the size of the text in the Headings Tag,
also it may not affect the size of the text inside a table. The <BASEFONT> element
is an empty tag. The default font size for normal body text is 3 if the <BASEFONT>
tag is not used.
2.3.3 The <BIG> and The <SMALL> tag :
The <BIG> tag makes the text appear in a larger font. i.e. it has the same effect
as <FONT SIZE=+1>. The <BIG> element is a non empty tag set.
The <SMALL> tag makes the text appear in a smaller font. It ignores the tag
if the text is already in the smallest size. The tag has the same effect as <FONT
SIZE=-1>. The <SMALL> element is a non empty tag set.
2.3.4 The Bold <B>, Italic <l > and Underline <U > Tags :
These are the most common tags used to change the appearance of the text.
These tags are non empty tags. The Bold tag will make the text appear bold, the Italic
gives a slant effect to the text and the Underline tag underlines the text. The Emphasis
<EM> tag is also used to effect italic formatting. Similarly, the <STRONG> tag can be
used to make the text appear bold.
Advanced Web Designing / 16
2.3.5 The Strike <STRIKE> Tag :
The strike tag indicates that the enclosed text should have a line drawn through
the middle of the text. The Strike tag is a non empty tag set.
2.3.6 The Teletype <TT> Tag :
This makes the enclosed text appear in the teletype font i.e. the text will be
monospaced and look like a typewriter font. Commonly, the browsers use the Courier
New font to display Teletype text. The .<TT> is a non empty tag set.
2.3.7 The Superscript <SUP> and Subscript <SUB> Tags :
Both these tags are non empty tag sets. These tags are used in documents that
contain formulas, footnotes, equations etc.
2.3.8 The Break Tag <BR> :
The Break Tag <BR> inserts a line break immediately following the <BR> tag
and takes the text to the next line. The <BR> tag is an empty tag. This tag is useful
for short items like addresses.
2.3.9 The Quote Tag <Q> :
The quote tag is used for inline quotes. The Quote tag is similar to the Block
level BLOCKQUOTE element, only it does not start a new paragraph since it is a text
level element. The Quote element is a non-empty tag set.
Let us use some of these tags to create the following HTML document and you
will be able to see their effect when you view this code in your browser.
<HTML>
<HEAD>
<TITLE>Text formatting tags</TITLE>
</HEAD>
<BODY>
<H3>Some commonly used text formatting Tags</H3><BR>
<B>Bold Text</BxBR>
<STRONG>Bold text with the Strong Tag</STRONG><BR>
<l>ltalic Text with the I tag</l><BR>
<EM>ltalic Text with the Emphasis EM tag</EM><BR>
<U>The Underline Tag</U><BR>
Registered<SUP>TM</SUP><BR>
The use of the Subscript tag in equations and formulas :
Na<SUB>2</SUB>CO<SUB>3</SUB><BR>
<TT>This is Teletype text</TT><BR>
<STRIKE>The strike tag used to strike text</STRIKE>
</BODY>
</HTML>
Block Level and Text Level Elements / 17
There are some additional text level elements like the Acronym, Citation, Code,
Keyboard etc. These elements are classified as Phrase elements. However, they are
out of scope of this study material.
2.3
1.
a)
b)
c)
d)
2.
a)
b)
3.
a)
b)
c)
d)
Check Your Progress.
Write 1-2 lines on the following tags.
The STRIKE tag :..................................................................................
.............................................................................................................
The TELETYPE tag : ...........................................................................
............................................................................................................
The ITALIC tag :....................................................................................
.............................................................................................................
The SMALL tag : .........................................................................................
.............................................................................................................
Answer in 1-2 sentences.
What is the Font tag? List the attributes of the Font tag.
.............................................................................................................
.............................................................................................................
What is the BASEFONT tag?
.............................................................................................................
.............................................................................................................
Fill in the blanks.
The ......................... tag can also be used like the BOLD tag.
The ......................... tag can also be used like the ITALIC tag.
The .................and ...................tags are used in formulas, footnotes etc.
The BIG has the same effect as FONT SIZE= .........................
2.4 Head Section Elements
Most of the elements of the Head Section are for advanced features of HTML.
They Head section is also much more complicated than the Body section. We shall
attempt to give an overview of the Head section elements in this chapter.
The Head Section of the HTML document contains the information about the
document like the Title of the document, and may include other information like the
document description, copyright information, etc.
The <TITLE> tag :
The <TITLE> element contains the title of the document. It is a non empty tag
set. The text in the <TITLE> tag is displayed as a single line in the title bar of the
browser. No other elements can be nested in the TITLE tag.
The <META> tag :
This tag is used to display the information about the document. META
tag is used to indicate the author of the document.
eg. <META NAME=”abc” CONTENT=”Authorname”>
The <LINK> tag :
This tag indicates the relationship between your document and other
URLs. LINK tags are highly dependant on the browsers and the search
engines.
The <BASE> tag :
The <BASE> tag indicates the complete URL of the document.
The <STYLE> tag :
These are useful when you want to use Style sheets in your document.
Advanced Web Designing / 18
The <SCRIPT> tag :
This tag is used to hold the commands that are written in a scripting
language like JavaScript and VBScript.
These are some of the tags which are used in the Head Section of the HTML
document. The purpose here is only to make you aware of the tags and an indepth
study of these tags is not in the scope of study of this material.
2.5 Using Comments
The Comment<!--> Tag :
The Comment Tag is a logical tag. It is a part of the HTML document which is
not displayed by the browser. The Comment tag is mainly used to add comments to
your HTML document. Comments help you to remember what you have done in your
code, previously, when you view your code after a long time. It is also helpful for others
who might view your code. The Comment Tag is an empty tag set.
The Comment tag starts with <!--. After these symbols, the comment is typed
and the tag is closed with --.
eg. <!--A sample comment -->
The comment doesn’t have to be a single line. It can be multiple lines also.
2.6 Summary
This chapter has covered the elements which can be used in the Body Section
of an HTML document. The elements which are used in the Head section are described
very briefly at the end.
There are two types of Body section tags : Block Level Elements and Text
Level Elements. Block Level Elements are used to define sections of text like paragraphs
and also to create lists whereas Text Level Elements are applied to smaller bits of text.
Lists is one more type of Block Level Elements. Lists are used to organise text
and structure information. There are three types of lists : Unordered Lists, Ordered Lists
and Definition Lists. Unordered Lists <UL>, are also known as Bullet lists. Each item
in the unordered list is preceded by a bullet. Each indivisual item in the unordered list
is preceded by the List Item <LI> tag. The <UL> is a non empty tag set whereas the
<LI> is an empty tag. Both <UL> and <LI> have the same set of attributes, where the
attribute value indicates the type of the bullet. Ordered Lists : Ordered Lists or
numbered list uses the <OL> tag. Ordered Lists use numbers in the place of bullets.
Ordered lists also contain the List Item <LI> element which precedes each indivisual
element in the list. The attributes which <OL> tag can take is TYPE which specifies
the type of the numbers used while listing the items.The Definition Lists : Definition
List element is used to create definition lists. The definition list tag is <DL>. The <DT>
tag is used for the term that is to be defined. The <DD> tag is used for the actual
definition of the term.
Text level elements are normally used for words and sentences. They markup
small bits of text and help to change their appearance.
We have seen the syntax and usage of the commonly used text level elements,
viz. The Font <FONT> tag is used to change the size, colour or typeface of the text
in a web page.
The <BIG> tag makes the text appear in a larger font. i.e. it has the same effect
as <FONT SIZE=+1>. The <SMALL> tag makes the text appear in a smaller font. It
ignores the tag if the text is already in the smallest size. The tag has the same effect
as <FONTSIZE=-1>.
The Bold <B> tag makes the text appear bold, the Italic <l> gives a slant effect
to the text and the Underline <U> tag underlines the text. The Emphasis <EM> tag
also effects italic formatting. Similarly, the <STRONG> tag makes the text appear bold.
The Strike <STRIKE> Tag draws a line through the middle of the text. The Strike
tag is a non empty tag set. The Teletype <TT> Tag makes the enclosed text appear
in the teletype font i.e. the text will be monospaced and look like a typewriter font.
Block Level and Text Level Elements / 19
The Superscript <SUP> and Subscript <SUB> Tags : These are used for formulas,
footnotes, equations etc. The Break Tag <BR> inserts a line break The Quote Tag <Q>
is used for inline quotes.
We have taken an overview of some of the Head Section Elements like the
<TITLE>, the <META>, the <LINK>, the <BASE>, the <STYLE>, the <SCRIPT> tags.
The Comment<!—> Tag : The Comment Tag is a logical tag, a part of the
HTML document which is not displayed by the browser.
2.7 Check your Progress - Answers
2.2.1 to 2.2.5
1
a) - (v)
b) - (i)
c) - (ii)
d) - (iv)
e) - (iii)
2.
a) horizontal
b) size
c) left
d) H6, H1
e) length
2.2.6 & 2.2.7
1.
a) Preformatted <PRE>
b) bullet
c) number
d) TYPE
2. a) The different types of lists are ordered lists, unordered lists
an definition lists.
b) The List items of an ordered list are preceded by numbers,
whereas those of unordered lists are preceded by bullets.
c) The tags associated with the Definition lists are : DL: to
create Definition Lists, DT - used for the Definition term and
DD used for the actual definition of the term.
2.3
1.
a) The Strike Tag is a non empty tag set used to indicate that the
enclosed text should have a line drawn through the middle of the
text.
b) The Teletype tag makes the text appear monospaced and like the
typewriter-font in appearance.
c) The Italic tag gives a slanting effect to the text enclosed within the
tag. It is a non empty tag set.
d) The Small tag makes the text appear smaller. It has the same
effect as FONT SIZE = -1.
2.
a) The Font tag is used to change the size, color or typeface of the
text. The Font tag takes three attributes COLOR, SIZE and FACE.
Al least on attribute of the tag has to be used when the FONT
element is used.
b) The Basefont tag establishes the default font size for the entire
web page. It is placed in the BODY tag and is an empty tag.
3.
a) STRONG
b)
c) Subscript, superscript d)
EMPHASIS
+ 1
Advanced Web Designing / 20
2.8 Questions for Self - Study
1.
What is the difference between text level elements and block level elements?
Describe any three text level and any three block level elements.
2.
Describe in detail the different types of lists.
3.
Write Short Notes on : The FONT element, The Comment Tag.
4.
Write Detailed notes on : Text Level Elements, Block Level Elements describing
the commonly used elements in both.
2.9 Suggested Readings
1.
Internet and world wide web: how to program / P. J. Deitel, H. M. Deitel
2.
Advanced internet programming : technologies and applications / Sergei
Dunaev
3.
The Complete Reference - Thomas Powell
4.
WWW.W3Schools.com
5.
www.html.net
uuu
Block Level and Text Level Elements / 21
NOTES
Advanced Web Designing / 22
CHAPTER 3
Adding Images and Colors
1234567890123456789012345678901212
1234567890123456789012345678901212
3.0
Objectives
1234567890123456789012345678901212
1234567890123456789012345678901212
3.1
Introduction
1234567890123456789012345678901212
3.2
Image Formats
1234567890123456789012345678901212
1234567890123456789012345678901212
3.2.1 GIF Images
1234567890123456789012345678901212
1234567890123456789012345678901212
3.2.2 JPEG Image Format
1234567890123456789012345678901212
3.2.3 PNG Image Format
1234567890123456789012345678901212
1234567890123456789012345678901212
3.3
The
Image Element
1234567890123456789012345678901212
1234567890123456789012345678901212
3.4
Background Images & Colors
1234567890123456789012345678901212
3.4.1 Body Attributes
1234567890123456789012345678901212
1234567890123456789012345678901212
3.4.2 The Background Attribute
1234567890123456789012345678901212
1234567890123456789012345678901212
3.4.3 The BG color Attribute
1234567890123456789012345678901212
3.4.4 The Text Attribute
1234567890123456789012345678901212
1234567890123456789012345678901212
3.4.5 The Link, V link, Alink Attribute
1234567890123456789012345678901212
1234567890123456789012345678901212
3.5
Summary
1234567890123456789012345678901212
3.6
Check Your Progress-Answers
1234567890123456789012345678901212
1234567890123456789012345678901212
3.7
Questions
for Self - Study
1234567890123456789012345678901212
1234567890123456789012345678901212
3.8
Suggested Readings
3.0 Objectives
After studying “Adding Images and Colors”, you will be able
–
–
–
–
–
to insert images alongwith your text in your HTML documents.
to understand the different types of commonly used image formats
to add background images.
to change background colors and text colors to make your document attractive.
to create more appealing web pages which will consist of text and graphics.
3.1 Introduction
Adding photographs, pictures and graphics in a web page is one of the most
appealing characteristic of HTML. Graphics allows you to make your web pages more
attractive and appealing. These images, which you insert within your web page are
known as Inline Images because they are inserted within the body of the text. The
<IMG> element is used in order to insert images in your web page. It is also possible
for you to add a background image to your web page. You can change the background
color of your web page and also change the color of your text. In order to do this you
have to make use of the attributes of the <BODY> tag. We shall see how to make use
of graphics and background images and colors to make our web pages more colourful
and attractive.
3.2 Image Formats
Before understanding how to add inline images in our web page it is worthwhile
to first take a look at a few of the different popular image formats found on the Internet.
3.2.1 GIF (Graphics Interchange Format) Images : The GIF image format
(with a file extension .gif) was introduced by CompuServe Inc. These images are the
most commonly found images on the Web. The two common versions of the GIF format
are GIF87A and GIG89A.
The size of the GIF image format is smaller than that of the other image formats.
This is so, because the images in GIF format are in a compressed file format. The web
browser (which supports display of GIF images) has a built in decoder which first
Adding Images and Colors / 23
decompresses the GIF image file and then displays it on the browser. These images
are stored as compressed files on storage devices. They are decompressed for actual
display and editing.
GIF formats are used for all types of images. It is specially useful for line
drawings, icons, computer generated images etc. GIF images can be transparent,
interlaced or animated. The major drawback of GIF format is that it supports a maximum
color depth of only 256 colors.
3.2.2 JPEG (Joint Photographic Experts Group) Image Format: This format
is inherently a compressed file format. JPEG can handle upto 16 million different colors.
This format is a very compact format, and is used for photographs and images without
big patches of solid colors. JPEGs are not very effective for icons or logos with lots
of solid colors. This is because, JPEG images are lossy i.e. they eliminate the data
which the human eye cannot perceive. At normal level of lossiness the viewer is not
able to know that the JPEG image is compressed and not the original non compressed
image. Because the images are lossy, they offer higher compression than the GIF
formats.
Any image, with a large degree of color variance should be stored in the JPEG
format. JPEG images can’t be transparent or animated.
3.2.3 PNG(Portable Network Graphics) Image Format : The specification for
the PNG format was devised by W3C. PNGs are smaller, have more colors and more
capabilities. They are suitable for both graphics and photo realistic images. Therefore
they have a distinct advantage over both the GIF and JPEG formats. The support
transparency.
The major disadvantages of the PNG formats are :
- They cannot be animated
- More importantly they are supported only by the more recent browsers.
3.2
Check Your Progress.
1.
Give the full forms of a) GIF :
b) JPEG:
c) PNG:
2. Match the following .
Column A
(a) PNG
(i)
(b) JPEG
(c) GIF
Column B
The specification of this format was devised
by W3C
(ii) supports a maximum color depth of only 256
colors.
(iii) These images are lossy
3.3 The IMAGE Element
The Image tag <IMG> is used to include inline images in the body of your Web
page. When the user downloads a Web page, the browser is instructed to download
the image separately and then display it in the specific manner. The image element
does not start a paragraph automatically. The <IMG> tag is an empty tag, which
appears in the <BODY> section of your HTML document. The attributes of the <IMG>
element are:
SRC : This is the URL of the image file. The value it takes is the complete or
partial URL of the image to be displayed. This attribute is essential with the <IMG>
element.
Advanced Web Designing / 24
ALT : Short for Alternate. If any browser is not displaying images or the user has
chosen not to display graphics, then the text contained in the ALT attribute is displayed.
The text in the ALT attribute is also displayed in a pop up window which appears when
the user takes the mouse pointer over the image. The attribute value of this attribute
is text. (normally a text which describes the image).
ALIGN : The ALIGN attribute is used to
- align the image either in a line or
- cause text to wrap around floating images.
In order to align the image in a line, the ALIGN attribute takes the values : TOP,
MIDDLE, BOTTOM. The default is ALIGN=”BOTTOM” which implies that the bottom of
the image will be aligned with the bottom line of the text. If you choose ALIGN=”TOP”
the browser will align the top of the image with the top line of the text. These attribute
values cause a number of white spaces to appear if the image is very big.
In order to make the paragraph wrap around the image and to make the image
float to the left or right side the ALIGN attribute takes the values LEFT or RIGHT.
Choosing LEFT or RIGHT will place the image directly against the left or the right
margin. The text after the <IMG> tag will wrap around the image.
The WIDTH and HEIGHT attributes : These attributes are used to indicate the
exact size of the image in pixels. They help to specify the width and height of an
image. Even if the original dimensions of the image are different you can still use the
width and height attributes to scale the image.
BORDER : By default no border appears to an image, except when the image
is a link. You can specify the border for an image as a number. BORDER=”1" will
make a thin border appear around the image. You can specify larger values for thicker
borders. HSPACE and VSPACE attributes : The amount of horizontal and vertical
space between the text and images can be controlled with the HSPACE and VSPACE
attributes. HSPACE will add space both to the left and right of the image, as measured
in pixels. VSPACE will set white space to the top and bottom of the image as
measured in pixels. Let us see how to make use of the image attributes with the
following example.
Type the HTML document and view the page in the web browser.
<HTML>
<HEAD>
<TITLE>Using Images</TITLE>
</HEAD>
<BODY>
<H3 ALIGN=CENTER>Using Images</H3>
<IMG SRC=fl_1.jpg WIDTH=150 HEIGHT=150 BORDER=2 HSPACE=5
ALIGN=MIDDLE>
Align the Image with the text
Adding Images and Colors / 25
</BODY>
</HTML>
As you can see, a border of width 2 appears around the picture, whose URL is
specified in the SRC attribute and the text associated with the picture is aligned
centrally. The width and height attributes of the picture are specified for an exact size.
The HSPACE attribute creates a gap of 5 between the picture and the associated text.
3.3
1.
a)
b)
c)
2.
a)
b)
c)
d)
Check Your Progress.
Fill in the blanks.
The value of the attribute _________ is the URL of the image file in the
image element
The HSPACE attribute controls the amount of ___________space between
the text and images
By default a border appears to an image only when it is a _______
__________.
State if True or False .
It is possible to scale an inline image.
An image element starts a paragraph automatically.
It is not possible to create white spaces around an image.
Text can be wrapped around floating images.
3.4 Background Images and Colors
In the previous section we saw how we can include images in our web page. Now
let us take a look at using background images and colors.
The attributes of the <BODY> tag are used to define the appearance of the
document. They are used to include background images, change background colors,
colors of the text and links of the web page.
3.4.1 The Body Attributes :
There are six <BODY> attributes : BACKGROUND, BGCOLOR, TEXT, LINK,
VLINK and ALINK. Out of these, the first three are related with changing the background
and text colors and adding background images. Therefore, we shall study them here.
The remaining three attributes are related to Hyperlinks and shall be studied subsequently.
3.4.2 The BACKGROUND Attribute :
An image file (gif or jpeg) can be used as a background for your web page. This
makes your web page more attractive.
The syntax for background image is <BODY BACKGROUND = ”filename”> Here
the value of the attribute is the name of the Image file or URL of the image which is
to be displayed as the background of the web page. HTML allows GIF or JPEG images
to be used as background images. The image is replicated in order to fill the screen.
This repetition of the pattern of the image file is called tiling. The image is tiled
automatically by the browser to form the background image.
<HTML>
<HEAD>
<TITLE>Background images</TITLE>
</HEAD>
<BODY BACKGROUND=Sky.jpg>
<H3>Background Images</H3>
</BODY>
</HTML>
In this example the image Sky.jpg is tiled automatically to form the background
image. Do not forget to include your background image file in the same directory as
Advanced Web Designing / 26
your HTML documents or else you may lose the background image.
3.4.3 The BGCOLOR (Background Color) Attribute :
Like a background image, it is also possible to specify a background color. The
background color is specified using the RGB color code. The syntax is :
<BODY BGCOLOR=#RGB code>
or
<BODY BGCOLOR=colorname>
You can use either the color code or the color name to specify the background
color. If the color is specified as a code, then the code is to be preceded with the “#”
sign.
If you do not specify any background color, then the browser uses the color
which was specified when the browser was set up. It is a good practice to use a
contrast of colors for the background and the text. Do not make the background color
and the text color the same. It will be difficult to read the content.
The BACKGROUND attribute overrides the BGCOLOR attribute. This means that
if you have specified both a background image and a background color, then the
background color will be ignored and the background image will be displayed.
3.4.4 The TEXT Attribute (Changing the Color of the Text) :
Like changing the background color, it is also possible to change the color of
the text in your HTML document. The text color is also to be specified in the <BODY>
tag. The same RGB color codes which are used for the background are applicable to
text also. The text color is specified with the TEXT attribute in the <BODY> tag. The
value of the attribute can be the color name or the color code.
<BODY TEXT=#RGB code>
or
<BODY TEXT=colomame>
The above example shows the use of background colors and text colors with the
<BODY> tag. Type the HTML code of the above example with the help of your editor
and then view the page in the browser, to see the effect of a dark background with a
contrast light color foreground text.
<HTML>
<HEAD>
<TITLE>Background Color</TITLE>
</HEAD>
<BODY BGCOLOR=GREEN TEXT=PINK>
<H3 ALIGN=CENTER>Use a light color against a dark background for
better contrast</H3>
</BODY>
</HTML>
3.4.5 The LINK, VLINK and ALINK Attributes :
These attributes of the <BODY> tags are applied for changing the color of
hyperlinks. We shall study these attributes of the <BODY> tag in the Hyperlinks
section.
3.4
Check Your Progress.
Answer in 1-2 sentences .
a) What are the uses of the attributes of the <BODY> tag?
.............................................................................................................
.............................................................................................................
Adding Images and Colors / 27
b)
c)
Which are the attributes of the <BODY> tag which are associated with
Hyperlinks?
.............................................................................................................
.............................................................................................................
Which are the ways in which you can specify the color of the text in your
web page?
.............................................................................................................
.............................................................................................................
3.5 Summary
Adding photographs, pictures and graphics in a web page is one of the most
appealing characteristic of HTML. Graphics allows you to make your web pages more
attractive and appealing. These images, inserted within your web page are known as
Inline Images. The <IMG> element is used in order to insert images in your web page.
The popular image formats found on the Internet include
- GIF (Graphics Interchange Format) Images : It is specially useful for line
drawings, icons, computer generated images etc. GIF images can be transparent,
interlaced or animated. GIF format supports a maximum color depth of only 256 colors.
- JPEG (Joint Photographic Experts Group) Image Format : This format is
inherently a compressed file format. JPEG can handle upto 16 million different colors.
- PNG(Portable Network Graphics) Image Format : The specification for the
PNG format was devised by W3C. PNGs are smaller, have more colors and more
capabilities.
The attributes of the <BODY> tag are used to define the appearance of the
document. They are used to include background images, change background and
foreground colors of the text and links of the web page.
The BACKGROUND Attribute : An image file (.gif or .jpeg) can be used as a
background for your web page. The value of the attribute is the name of the Image file
or URL of the image which is to be displayed as the background of the web page. The
BGCOLOR Attribute : The background color is specified using either the RGB color
code or the color name. The TEXT Attribute :The text color is also to be specified
in the <BODY> tag. The same RGB color codes which are used for the background
are applicable to text also. <BODY TEXT=#RGB code> or <BODY TEXT=colorname>
The LINK, VLINK and ALINK Attributes : These attributes of the <BODY> tags
are applied for changing the color of hyperlinks.
3.6 Check your Progress - Answers
3.2
1. a)
b)
c)
2. (a)
(c)
(iii)
1.
2.
c)
c)
link
False
Graphics Interchange Format
Joint Photographic Experts Group
Portable Network Graphics
(i)
(b)
(ii)
3.3
a) IMG
b)
horizontal
a) True
b)
False
d) True
3.4
1. a) The attributes of the BODY tag define the appearance of a
document, are used for background images, change background
colors and colors of text and links.
Advanced Web Designing / 28
b.) The attributes of the <BODY> tag associated with hyperlinks are
LINK, VLINK and ALINK.
c) The color of the text on the web page can be specified either with
a 6 digit RGB color code or by giving a color name.
3.8 Questions for Self - Study
1.
Write short notes on : JPEG, PNG, GIF, The IMAGE element.
2.
Discuss the attributes of the BODY tag associated with background images and
colors.
3.
Describe the ALIGN attribute of the IMAGE element.
3.9 Suggested Readings
1.
Advanced internet programming : technologies and applications / Sergei Dunaev
2.
The Complete Reference - Thomas Powell
3.
world wide web design with html - c xavier
4.
WWW.W3Schools.com
5.
www.html.net
uuu
Adding Images and Colors / 29
NOTES
Advanced Web Designing / 30
CHAPTER 4
Hyperlinks
12345678901234567890123456789012123
12345678901234567890123456789012123
12345678901234567890123456789012123
4.0 Objectives
12345678901234567890123456789012123
12345678901234567890123456789012123
4.1 Introduction
12345678901234567890123456789012123
4.2 External Links
12345678901234567890123456789012123
12345678901234567890123456789012123
4.2.1 Linking to another Web Page
12345678901234567890123456789012123
12345678901234567890123456789012123
4.2.2 Links to Download Files
12345678901234567890123456789012123
12345678901234567890123456789012123
4.2.2 Links to Address Outgoing Emails
12345678901234567890123456789012123
12345678901234567890123456789012123
4.3 Internal Links
12345678901234567890123456789012123
12345678901234567890123456789012123
4.4 Link, Vlink & Alink Attributes
12345678901234567890123456789012123
4.5 Summary
12345678901234567890123456789012123
12345678901234567890123456789012123
4.6 Check Your Progress - Answers
12345678901234567890123456789012123
12345678901234567890123456789012123
4.7 Questions for Self - Study
12345678901234567890123456789012123
4.8 Suggested Readings
12345678901234567890123456789012123
12345678901234567890123456789012123
4.0 Objectives
After studying the hyperlinks students will discuss the following points-
what are hyperlinks.
study the external links and internal links.
to discuss the attributes of the BODY tag associated with hyperlinks.
to make effective use of hyperlinks in your web page.
4.1 Introduction
One of the most interesting features of HTML is Hyperlinks. Hyperlinks make it
possible for you to link your web page with other pages. You can not only link to files
that are a part of your site, but it is possible for you to also link to files which are
external to your site. A hyperlink is an anchor in a HTML document which points to
another hypertext document, or multimedia data object. Each hyperlink can point to
only one hypertext document or data object.
There are two types of Hyperlinks : external links and internal links. Links which
point to files which are not a part of your site are external links and links to files that
are a part of your own site are known as internal links. Both external and internal links
are known as hyperlinks.
Any user can click on a link to obtain one of the following things :
- download a different web page
- advance from one location to another in the same web page
- automatically launch a user’s email application
- download a multimedia data object or binary file.By default, a text hyperlink in
a web page is usually underlined and the text color is blue to indicate it as a link. If
an image is used as a link, the browser normally places a blue border around an image.
If a link is visited, the color of the link changes from blue to purple and the border of
an image changes from blue to purple.
l The ANCHOR <A> tag :
The anchor tag defines the beginning and end of a hyperlink. The Anchor element
uses the <A> and </A> tags. The two main attributes of the Anchor Tag Which we will
see in this section are the HREF and TITLE attributes.
q The HREF (Hypertext reference) Attribute :
The main attribute that the anchor tag takes is the HREF i.e. hypertext reference
attribute which specifies the hyperlink reference. We shall discuss the Anchor tag
throughout this chapter in detail as we see External and Internal links.
Hyperlinks / 31
q The TITLE attribute :
This attribute of the Anchor tag is used to explain the information about the link
in more detail. The value of the TITLE attribute is generally displayed in a tool tip or
balloon help. It sometimes also appears on the status bar. For example if you add the
TITLE attribute.to the anchor element as :
<A HREF=http:/www.abc.com TITLE=AII about ABC.com>ABC Web Site</A>
then, the text “All about ABC.com” will appear as a tool tip when the mouse pointer
points to the link.
4.1
1.
a)
b)
c)
2.
Check Your Progress.
Define :
Hyperlink - ...............................................................................................
............................................................................................................
External Links -..........................................................................................
..............................................................................................................
Internal- Links -...........................................................................................
.............................................................................................................
What is the Anchor tag?
.............................................................................................................
.............................................................................................................
4.2 External Links
4.2.1 Linking to another webpage :
It is possible to link to another webpage by specifying the exact URL of that
page as the value of the HREF attribute. You can present a link to the user as a
standard text or an inline image. With these hyperlinks it is possible for you to connect
the user to resources outside your website. You can link to any type of file on the Web,
including images, sounds and movies.
l Using text as a Link :
The syntax for this hyperlink is :
<A HREF=http://www.abc.com>ABC Web Site</A>
Here the URL of the ABC Website is the value of the HREF attribute of the
anchor. The text “ABC WebSite” (which is enclosed within the anchor tags) provides
the visible link to the user and is known as the anchor text. The user clicks on this
link to gain access to the website abc.com.
l Using an Image as a Link :
It is also possible to use an image as the anchor for links. The syntax is : <A
HREF=abc.com><lMG SRC=”pic1 .jpg”></A>
Here the picture file pic1.jpg serves as the anchor to link to the website abc.com.
The user will click on the picture to get access to abc.com.
Both text and image together can also be used in a hyperlink, eg.
<A HREF=abc.com>Go to ABC<IMG SRC=pic1 .jpg></A>
With the following example, the use of text and images as links to, another web
page will be clear.
<HTML>
<HEAD>
<TITLE>Creating Hyperlinks</TITLE>
</HEAD>
<BODY TEXT=GREEN>
<H2 ALIGN=CENTER>Linking to Another Web Page</H2>
You can use text or inline images to link to another web page<BR><BR>
Advanced Web Designing / 32
<FONT COLOR=RED>Use of Text for Links</FONT><BR>
Connect to NewSite
<A HREF=HTTP://WWW.NewSite.COM>NewSite</A><BR><BR>
<FONT COLOR=PINK>Use of Image as Link</FONT><BR>
Connect to Newsite
<A HREF=HTTP://WWW.NewSite.COM><lMG SRC=FL_1.JPG
WIDTH=30 HEIGHT=30 ALIGN=CENTER></A><BR><BR>
<FONT COLOR=MAROON>Use of Text and Image as Link
</FONT><BR>
Connect to Newsite
<A HREF=HTTP://WWW.NewSite.COM>NewSite<IMG SRC=FL_1.JPG
WIDTH=30 HEIGHT=30 ALIGN=CENTER></A>
</BODY>
</HTML>
Here the text NewSite provides a visible link to the user. i.e. it is the anchor text
When the user clicks on this text, or on the image provided as a link the browser will
download the page whose URL is specified in the anchor tag.
4.2.2 Links to Download Files :
It is possible to download binary files from web servers or FTP servers. The
syntax is similar to downloading a web page. You have to additionally only specify the
location and name of the file which is to be downloaded along with the URL.
l To Download from a Web server :
Click <A HREF=http://www.abc.com/files/filename>here</A>
l To Download from an FTP server :
Click <A HREF=ftp://ftp.abc.com/files/filename>here</A>
4.2.3. Links to address outgoing e-mails :
It is possible to create anchors that automatically address outgoing e-mails. This
type of anchor, also known as MAILTO anchor will perform the following actions :
- It will automatically launch the user’s e-mail application
- It will automatically open a new outgoing message
- It will also address this outgoing message to the specific e-mail
address.
This anchor will allow the user to send an e-mail to the specific e-mail address.
These anchors are very useful to obtain feedbacks from the user, as also suggestions,
complaints etc.about your products, web sites etc.
The syntax for this anchor is :
<A HREF=mailto:e-mail_id>Feedback</A>
The HREF attribute value has the prefix mailto attached to it. The HREF
value is not a URL, but an e-mail address.
Let us see how to use the Mailto anchor with this example. The following is the
HTML document code used to create the above mailto link :
<HTML>
<HEAD>
<TITLE>
Using Hyperlinks
</TITLE>
</HEAD>
<BODY>
<FONT COLOR=TEAL SIZE=4>Use of Hyperlinks to address an Outgoing
emaik/FONT><BR>
Send Your<A HREF=MAILTO:[email protected]>Feedback </BODY>
Hyperlinks / 33
</HTML>
In the example, when the user clicks on Feedback (which is the visible link) the
mailto anchor will automatically launch the user’s e-mail application and open a new
outgoing message. It will also address this outgoing message to the e-mail address
specified in the HREF attribute (in this case [email protected]).
4.2
Check Your Progress.
Write True or False.
a) Images can be used as links.
b) It is possible to create anchors that automatically address outgoing e-mails.
c) With external links also it is not possible to link to resources outside your
website.
d) To address outgoing emails, the email address need not be specified as the
HREF attribute value.
4.3 Internal Links
l To link to another section in the same Web Page :
These anchors, which link to another section of the same web page are also
called as internal links. These internal links require two anchor tags : one the referring
anchor and the other the target or referred anchor. In this case, the target of the
referring anchor does not actually perform any hypertext navigation. It only takes the
user to a specific location in the same web page. Internal anchors are generally used
in very large web pages or web pages which have sections. They are also used to
create an index at the top of a large web page. Internal links are also known as NAME
anchors.
The two tags of the NAME anchor are :
(i) Referring tag : The referring tag which contains the reference to a text label
is the attribute value of HREF in the Anchor tag. When it is written it has to be
preceded by the “#” sign. eg. <A HREF=#page1>
(ii) Target or Destination tag : The destination location is marked by the
NAME attribute and the identical text label as in the referring tag. eg. <A NAME=page1>
We shall see the use of the Name anchor with the following example which will
show the list of the pictures of flowers available in this web page. When you select the
link to a particular flower, the picture of that flower will be immediately displayed. You
are not required to scroll through the entire page to view a specific flower.
<HTML>
<HEAD>
<TITLE>Creating Internal Links</TITLE> </HEAD>
<BODY>
<FONT SIZE=4>Flower Collection</FONT><BR>
Introduction :
<P>Here we attempt to take a look at creating internal links.
The table of contents displays the list of the pictures of flowers available in this
page. When the user clicks on a particular link the picture of the flower shall be
displayed.
<H4 ALIGN=LEFT> Table of Contents</H4>
<A HREF=#CH1>1. Picture of a Rose</A><BR>
<A HREF=#CH2>2. Picture of a Lilium</A><BR>
<A HREF=#CH3>3. Picture of a Gerbera</A><BR>
<A HREF=#CH4>4. Picture of an Orchid</A><BR>
<A NAME=CH1><FONT COLOR=PURPLE>Picture of a Rose is here<BR>
<IMG SRC=rose4.jpg HEIGHT=200 WIDTH=150></A><BR>
<A NAME=CH2><FONT COLOR=PURPLE>Picture of a Lilium<BR>
<IMG SRC=lili4.jpg></A><BR>
Advanced Web Designing / 34
<A NAME=CH3><FONT COLOR=PURPLE>Picture of a Gerbera<BR>
<IMG SRC=ger1.jpg></A><BR>
<A NAME=CH4><FONT COLOR=PURPLE>Picture of an Orchid<BR>
<IMG SRC=orch1.jpg></A><BR>
</FONT>
</HTML>
With this example, it is seen that you can link to other parts of the same
document with the use of the NAME anchor. When you click on the link provided, the
picture and text associated with the link, which is elsewhere on your webpage is
displayed.
When you open this page in the browser you will be able to see the opening
paragraph and a list of all the pictures of flowers available on your page. You click on
the required link, and the corresponding image will be immediately displayed by the
browser. We shall first see how the main page appears and the second window shall
show the picture of the flower whose link is clicked, (in this case that of a gerbera).
When you are creating such internal links in your HTML document, it is important
for you to test all the links that you have created. The HTML code becomes more
complicated as the number of links increases, therefore a complete testing of all the
links provided has to be done, prior to making those links available on web.
It shows the list of available pictures as above. When you click on 3. Picture
of a Gerbera is displayed.
At the same time, it is also required that you provide a facility to return to top
i.e to the start of the web page, from the place where you are. This is because, as
you might have seen in the above example, if you wish to go to the beginning of your
page, then you have no option but to use the scroll bar.
This can be overcome by using another link to return to the top of the page. This
link is to be provided in every subsection of your document, from where you wish to
send the surfer back to the top of the page.
Modify the above example as shown below :
<HTML>
<HEAD>
<TITLE>Creating Internal Links</TITLE>
</HEAD>
<BODY>
<A NAME=TOP></A>
Hyperlinks / 35
<FONT SIZE=4>Flower Collection</FONT><BR>
Introduction :
<P>Here we attempt to take a look at creating internal links.
The table of contents displays the list of the pictures of flowers available
in this page.
When the user clicks on a particular link the picture of the flower shall be
displayed.
<H4 ALIGN=LEFT> Table of Contents</H4>
<A HREF=#CH1>1. Picture of a Rose</A><BR>
<A HREF=#CH2>2. Picture of a Lilium</A><BR>
<A HREF=#CH3>3. Picture of a Gerbera</A><BR>
<AHREF=#CH4>4. Picture of an Orchid</A><BR>
<A NAME=CH1><FONT COLOR=PURPLE>Picture of a Rose<BR>
<IMG SRC=rose4.jpg HEIGHT=200 WIDTH=150></A><BR>
<A HREF=#TOP>Go To Top</A><BR>
<A NAME=CH2><FONT COLOR=PURPLE>Picture of a Lilium<BR>
<IMG SRC=lili4.jpg WIDTH=200 HEIGHT=200></A><BR>
<A HREF=#TOP>Go To Top</A><BR>
<A NAME=GH3><FONT COLOR=PURPLE>Picture of a Gerbera<BR>
<IMG SRC-=ger1.jpg></A><BR>
<A HREF=#TOP>Go To Top</A><BR>
<A NAME=CH4><FONT COLOR=PURPLE>Picture of an Orchid<BR>
<IMG SRC=orch1 .jpg WIDTH=200 HEIGHT=200></A><BR>
<A HREF=#TOP>Go To Top</A><BR>
</FONT>
</HTML>
You will notice in the above example, that we have used the same NAME anchor
in each of the sections in our document, to return to the top of the page. This NAME
attribute is defined at the beginning in the Anchor tag and is assigned a value TOP. The
same attribute value is given to all the NAME elements in the anchor tag in flower
section. When the user clicks on Go To Top, he is returned to the top of the page.
4.3 Check Your Progress.
Answer in 1-2 sentences.
a) What is a referring tag in a hyperlink?
.............................................................................................................
.............................................................................................................
b) What is a target tag in a hyperlink?
.............................................................................................................
.............................................................................................................
c) Where are internal links useful?
.............................................................................................................
.............................................................................................................
4.4 LINK, VLINK and ALINK Attributes
We had seen in the previous chapter, some of the attributes of the <BODY>
element and deferred our discussion of the LINK, VLINK and ALINK attributes till we
discussed hyperlinks. Now let us see these attributes.
LINK : This attribute specifies the color of the hyperlink. As we know, in most
Advanced Web Designing / 36
browsers the default color of a link is blue (when is has not been visited). You can
change the color of the link by using the LINK attribute in the BODY tag.
eg. <BODY LINK=BROWN> will set the color of unvisited links to brown. The
color can also be specified as a 6 digit RGB color code.
VLINK : This attribute is used to specify the color of links which have been
previously visited by the viewer. By default, most browsers use the purple color for
visited links. You can set the color of visited links as :
<BODY VLINK=GREEN>
This will set the color of a visited link to green. The color can also be specified
with the 6-digit RGB color code. For e.g <BODY VLINK=#FFFF00>.
ALINK : When the mouse is held on a link, the color which is briefly used is
the color of the active link, It is normally red with most browsers. It can be set to any
desired color with the ALINK attribute.
eg. <BODY ALINK=MAROON>
This sets the color of the active link to maroon.
Normally, a person surfing the net is used to the link colors blue, purple and red
for LINK, VLINK and ALINK. You have to be therefore careful when changing the colors
of links in your web pages.
4.4
Check Your Progress.
Describe the following attributes of the <BODY> element in 1-2 sentences.
a) LINK :.........................................................................................................
.............................................................................................................
b) ALINK :....................................................................................................
..............................................................................................................
c) VLINK :........................................................................................................
..............................................................................................................
4.5 Summary
Hyperlinks make it possible for you to link to files that are a part of your site,
as well as files which are external to your site. A hyperlink is an anchor in a HTML
document which points to another hypertext document, or multimedia data object.
Links which point to files which are not a part of your site are external links and links
to files that are a part of your own site are known as internal links. Both external and
internal links are known as hyperlinks.
The ANCHOR <A> tag defines the beginning and end of a hyperlink. The two
main attributes of the Anchor Tag are the HREF and TITLE attributes. The HREF
(Hypertext reference) Attribute specifies the hyperlink reference. The TITLE attribute
is used to explain the information about the link in more detail.
It is also possible to use an image as the anchor for links. The name of the
picture file is the value of the HREF attribute. Both text and image together can also
be used in a hyperlink.
It is also possible to create anchors that automatically address outgoing e-mails.
This type of anchor, also known as MAILTO anchor will perform the following actions
:
– It will automatically launch the user’s e-mail application
– It will automatically open a new outgoing message
– It will also address this outgoing message to the specific e-mail address.
This anchor will allow the user to send an e-mail to the specific e-mail address.
In this case, the HREF value is not a URL, but an e-mail address.
Anchors, which link to another section of the same web page are also called as
internal links. These internal links require two anchor tags : one the referring anchor
Hyperlinks / 37
and the other the target or referred anchor. In this case, the target of the referring
anchor does not actually perform any hypertext navigation. It only takes the user to a
specific location in the same web page. Internal anchors are generally used in very
large web pages or web pages which have sections. They are also used to create an
index at the top of a large web page.
4.6 Check your Progress - Answers
4.1
1.
a) A hyperlink is an anchor in a HTML document which points to
another hypertext document or multimedia data object.
b) Links which point to files which are not a part of your web page
are called as external links.
c) Links which point to files that are a part of your own site are
known as internal links.
2.
Anchor tag is the element used to create both internal and external
links. It uses the <A> and </A> tags.
4.2
a)
True
b)
True
c)
False
d)
False
4.3
a)
The referring tag is the attribute value of the hypertext reference
(HREF) in the anchor tag. It contains the reference to the text label.
b)
The target tag appears in the anchor element and is the attribute
value of the NAME tag. It is identical to the label in the corresponding
referring tag.
c)
Internal links are useful in very long web pages or web pages which
have sections. They are also used to create an index in long pages.
4.4
a)
This attribute specifies the color of a hyperlink and its value is the
color name or color code to which the color of the link will be set.
b)
The ALINK attribute can be used to set the color of the active link i.e.
the color which appears briefly when the mouse is held on the link.
c)
The colors of visited links can be set with the VLINK attribute. The
value can be specified either as a color name or a 6 digit RGB color
code.
4.7 Questions for Self - Study
1.
What are hyperlinks? What are internal and external links? What are the uses
of hyperlinks?
2.
Discuss external links in detail.
3.
Discuss internal links in detail.
4.
Write a note on the attributes of the <BODY> tag used with hyperlinks.
5.
Write short note on : Links to address outgoing emails.
Advanced Web Designing / 38
4.8 Suggested Readings
1.
Advanced internet programming : technologies and applications / Sergei Dunaev
2.
The Complete Reference - Thomas Powell
3.
world wide web design with html - c xavier
4.
WWW.W3Schools.com
5.
www.tizag.com
uuu
Hyperlinks / 39
NOTES
Advanced Web Designing / 40
CHAPTER 5
Tables
12345678901234567890123456789012123
12345678901234567890123456789012123
5.0
Objectives
12345678901234567890123456789012123
5.1
Introduction
12345678901234567890123456789012123
12345678901234567890123456789012123
5.2
Tables
12345678901234567890123456789012123
12345678901234567890123456789012123
5.2.1 Table Elements
12345678901234567890123456789012123
12345678901234567890123456789012123
5.2.2 Aligning Contents of Row & Columns
12345678901234567890123456789012123
5.2.3 Changing Colour of Table or Parts of
12345678901234567890123456789012123
12345678901234567890123456789012123
Table
12345678901234567890123456789012123
12345678901234567890123456789012123
5.2.4 Putting Images & other Elements
12345678901234567890123456789012123
Inside Table
12345678901234567890123456789012123
12345678901234567890123456789012123
5.2.5 Merging Cells
12345678901234567890123456789012123
12345678901234567890123456789012123
5.3
Non Cell Table Elements
12345678901234567890123456789012123
5.3.1 Rules
12345678901234567890123456789012123
12345678901234567890123456789012123
5.3.2 Frame Attribute
12345678901234567890123456789012123
12345678901234567890123456789012123
5.4
Nesting Tables
12345678901234567890123456789012123
12345678901234567890123456789012123
5.5
Advantages and Disadvantages of Tables
12345678901234567890123456789012123
5.6
Summary
12345678901234567890123456789012123
12345678901234567890123456789012123
5.7
Check Your Progress - Answers
12345678901234567890123456789012123
12345678901234567890123456789012123
5.8
Questions for Self - Study
12345678901234567890123456789012123
12345678901234567890123456789012123
5.9
Suggested Readings
5.0 Objectives
After Studying this chapter you will be more familiar with use of tables.
– to understand how to organise the data using tables
– to use all the table elements and attributes to enhance the appearance
of tables
– to learn how to merge cells of a table
– to learn table nesting
5.1 Introduction
Tables are a very popular way of presenting data on the web. They are a powerful
and functional feature of HTML. A table can contain not only text data, but also lists,
forms, images, paragraphs, preformatted text etc. It is also possible to nest tables
within one another. In this section, we shall start by creating a simple table, learn the
table attributes, and also learn how to merge cells. We shall also see non cell table
elements and table nesting. Data can be presented as organised in rows and columns.
The horizontal lines of data in a table are rows and the vertical lines are columns.
Each intersection of a row and column is called a cell. Let us now see how to present
tabular data by using tables.
5.2 Tables
To create a table in HTML the Table <TABLE> tag is used. The TABLE tag is a non
empty tag set. There are two associated tags, with the <TABLE> tag viz. <TR> and
<TD>
The <TR> tag :This is the Table Row element and creates a horizontal row of cells.
This can contain the table data and headings.
The <TD> tag :The Table Data element <TD> specifies each indivisual cell in the
table. The third tag The Table Heading <TH> tag creates the Heading cells. It is to
be noted that the </TR>, </TD> and </TH> closing tags are optional and the table
appearance and function is not affected if they are not added.
We shall first see how to apply these basic elements and create a simple table.
Tables / 41
<HTML>
<HEAD>
<TITLE>Creating Tables</TITLE> </HEAD>
<BODY>
<TABLE>
<CAPTION>
Animals and their young ones
</CAPTION>
<TR>
<TH>Sr.No</TH>
<TH>Animal</TH>
<TH>Young One</TH>
</TR>
<TR>
<TD>1 .</TD>
<TD>Cat</TD>
<TD>Kitten</TD>
</TR>
<TR>
<TD>2.</TD>
<TD>Dog</TD>
<TD>Puppy</TD>
</TR>
<TR>
<TD>3.</TD>
<TD>Horse</TD>
<TD>Filly</TD>
</TR>
<TR>
<TD>4.</TD>
<TD>Lion</TD>
<TD>Cub</TD>
</TR>
<TR>
<TD>5.</TD>
<TD>Pig</TD>
<TD>Piglet</TD>
</TR>
Advanced Web Designing / 42
</TABLE>
</BODY>
</HTML>
Let us understand the HTML code as we have developed in the example.The
<CAPTION> and </CAPTION> tags are used in the example to give the caption to
the table. The caption is displayed outside the table border. The <CAPTION> tag takes
the attribute ALIGN, which is used to create the caption at the top or bottom of the
table. eg. <CAPTION ALIGN=TOP>. This attribute can take only two values viz. TOP
or BOTTOM.
The default value is TOP. You can use only text elements in the caption element.
It is important to note that the CAPTION tag must appear before the first row, and
immediately after the <TABLE> tag.
The Heading for the columns in the table are specified using the <TH> tag. Every
indivisual cell data is placed in the corresponding cell with the use of the <TD> tag.
We have created six rows in the table, the topmost row is the heading. Note that the
table data in the heading appears in a bold format. The remaining five rows display the
serial number, the animal and its young one.
Since we have not used any formatting attributes of the TABLE element the table
data has not been formatted in any way. We shall now study the attributes of the
TABLE tag to create more attractive and structured tables.
5.2.1 The <TABLE> element attributes :
The attributes of the <TABLE> tag are : ALIGN, WIDTH, BORDER,
CELL-SPACING, CELLPADDING, and BGCOLOR.
(i) The ALIGN attribute : This attribute is used to specify the horizontal alignment
of the table as a whole and not the alignment of indivisual cells in the table. The values
that this attribute can take are LEFT, CENTER and RIGHT. The default alignment of the
table is LEFT. eg. <TABLE ALIGN=CENTER>
(ii) The WIDTH attribute : This attribute is used to specify the width of the table
relative to the width of the web page. The width can be specified as a percentage or
as a number. Number means number of pixels. If you do not specify any width, then
the table width will be set as required.
(iii) The BORDER attribute : This attribute is used to specify a border to the
table and define the thickness of the border in pixels. The default border value is one
pixel if you do not specify any value and simply use the BORDER attribute as <TABLE
BORDER>. Omitting the BORDER attribute or specifying BORDER=0, will indicate no
border to the table. The BORDER attribute will set the border only to the outside table
border and not the indivisual cells.
(iv) CELLSPACING: This attribute is used to specify the spacing between table
cells. This attribute takes the value as a number, indicated in pixels. eg. <TABLE
CELLSPACING=5> will create a space of 5 pixels between the adjacent cells.
(V) CELLPADDING : The CELLPADDING attribute is useful to create space
between the border of the cell and the cell data. The CELLPADDING attribute also
takes a value as a number in pixels.
5.2.2 Aligning the Contents of Cells and Rows :
It is possible for you the align the contents of the cells horizontally as well as
vertically. For this purpose the ALIGN and VALIGN attributes are used.
The ALIGN attribute can be included in the <TR>, <TD> and <TH> tags. This
attribute will indicate the horizontal alignment of the cell data. The values that this
attribute can take are : LEFT, CENTER and RIGHT These values will specify the
alignment of the data in the cells. By default, the cell data will be left aligned.
The VALIGN attribute is used to specify the vertical alignment of data in a cell.
This attribute can also be used with the <TR>, <TD> and <TH> tags. The VALIGN
Tables / 43
attribute takes four values, viz. TOP, MIDDLE, BOTTOM, BASELINE. The default vertical
alignment of cell data is middle.
5.2.3 Changing the Color of a table or parts of a table :
In order to color the table or parts of a table the BGCOLOR attribute is used.
This attribute can be specified with the <TABLE>, <TR>, <TD> and <TH> tags. The
BGCOLOR attribute takes the value as the color name or color number. Using BGCOLOR
in the table works exactly in the same way as it works in the <BODY> tag. It is not
possible to change the color of the caption separately. However, if you have specified
a color to the entire table in the <TABLE> tag, then the background color applies to
the entire table including the caption.
5.2.4 Putting Images and other elements inside table cells :
It is possible for a cell to contain almost anything that can be put inside the body
section of your document. This means that your table cells can include text, block level
elements including paragraphs, lists and other tables and text level elements including
font, links and images.
Now apply some of these attributes and modify our previous table as follows :
<HTML>
<HEAD>
<TITLE>Creating Tables</TITLE>
</HEAD>
<BODY>
<TABLE ALIGN=CENTER WIDTH=50% BORDER=2
CELLSPACING=5> <CAPTION> Animals and their young ones</
CAPTION>
<TR BGCOLOR=GRAY>
<TH>Sr.No</TH>
<TH>Animal</TH>
<TH>Young One</TH>
</TR>
<TR BGCOLOR=PINK>
<TD>1.</TD>
<TD>Cat</TD>
<TD>Kitten</TD>
</TR>
<TR BGCOLOR=GRAY>
<TD>2.</TD>
<TD>Dog</TD>
<TD>Puppy</TD>
</TR>
<TR BGCOLOR=PINK>
<TD>3.</TD>
<TD>Horse</TD>
<TD>Filly</TD>
</TR>
<TR BGCOLOR=GRAY>
<TD>4.</TD>
<TD>Lion</TD>
<TD>Cub</TD>
</TR>
<TR BGCOLOR=PINK>
<TD>5.</TD>
<TD>Pig</TD>
<TD>Piglet</TD>
</TR>
</TABLE>
Advanced Web Designing / 44
</BODY>
</HTML>
5.2.5 Merging Cells:
In a situation where you wish to accommodate images and other graphics or
large blocks of data you can merge the cells into one another.
Cell Spanning :
Cell spanning is used to merge cells i.e. rows and columns. The most important
use of cellspanning is to create asymmetric tables. The ROWSPAN and COLSPAN
attributes are used in order to merge or span cells. These attributes take a number as
a value. eg. In order to span 2 columns you set the attribute value as <TD COLSPAN=2>.
The merging of cells shall be clear from the following example :
<HTML>
<HEAD>
<TITLE>Creating Tables</TITLE>
</HEAD>
<BODY>
<TABLE ALIGN=CENTER WIDTH=40% BORDER=2
CELLSPACING=2>
<CAPTION>
Animals, Birds and their young ones
</CAPTION>
<TR ALIGN=CENTER>
<TD BGCOLOR=PINK ROWSPAN=2>Animals
<TD>Cat</TD>
<TD>Kitten</TD>
</TR>
<TR ALIGN=CENTER>
<TD>Dog</TD>
<TD>Puppy</TD>
</TR>
<TR ALIGN=CENTER>
<TD BGCOLOR=PINK ROWSPAN=2>Birds
<TD>Goose</TD>
<TD>Gosling</TD>
</TR ALIGN=CENTER>
<TR ALIGN=CENTER>
<TD>Duck</TD>
Tables / 45
<TD>Duckling</TD>
</TR>
</TABLE>
</BODY>
</HTML>
Here we see that we have merged the first two rows in the first column with
ROWSPAN=2. The table data Animals will be spanned across the two rows in the first
column. The next two columns will now containing the cell data cat and kitten and this
will complete the first row. The first column of the second row has already been
spanned with the first column. So the cell data dog and puppy will appear in the second
and third columns of the second row. This will complete the first two rows of the table.
Now the table data Birds shall be spanned across the next two rows in the first column
and the remaining information shall be filled as seen in the example.
5.2
1.
a)
b)
c)
d)
e)
2.
a)
b)
c)
d)
e)
Check Your Progress.
Match the following.
Column A
Column B
Cellpadding
(i) Used for table data
Cellspacing
(ii) Specifies the table row
TD
(iii) creates space between border of cell and cell data.
TH
(iv) create heading cells
TR
(v) specify the spacing between table cells
Fill in the blanks.
The ......................... attribute is used to specify the horizontal alignment
of data in a cell.
Each intersection of a row and column in a table is called a.........................
The background color applies to the entire table including the caption when
the BGCOLOR attribute is applied to the ......................... tag.
The default vertical alignment of cell data in a table is.........................
Cell ......................... is used to merge rows and columns of a table.
5.3 Non Cell Table Elements
Uptil now we saw the table elements and their attributes which applied to the
table cells and table data (i.e. contents). The non cell elements of a table are the
FRAMES and RULES. With these elements you can control the display of the rules
and frames of a table.
5.3.1 The RULES attribute :
This attribute will allow you to selectively add gridlines to the table. This attribute
applies only to the inside of the table, not the outside border. The RULES attribute is
Advanced Web Designing / 46
added to the <TABLE> tag and the values that the RULES attribute takes, and their
effects are :
VALUE
EFFECT
NONE
There will be no rules i.e. cells without borders.
This is the default value.
ROWS
Rules will appear between rows only
COLS
Rules will appear between columns only
ALL
Rules will appear between all rows and all columns.
The above examples show the use of the RULES attribute and its values alongwith
the TABLE element to add gridlines to the table. In the first examples rules appear only
between columns, in the second only between the rows and in the third between rows
and columns both. Practice writing the code for these tables on your own.
5.3.2 The FRAME attribute:
This attribute is useful to add indivisual border elements or sides to a table. This
attribute is used with the <TABLE> tag and the values of this attribute and its effect
are :
VALUE
ABOVE
BELOW
BORDER
BOX
HSIDES
VSIDES
LHS
RHS
VOID
EFFECT
The top side only
The bottom side only
All the four sides,
This will have the same effect as specifying the BORDER
attribute.
All the sides, same as FRAME=BORDER
Only the horizontal i.e. top and bottom sides
Only the vertical i.e. left and right sides
Only the left hand side
Only the right hand side
No sides. This is the default value.
Tables / 47
The effect of the application of the values of the FRAME attribute are
shown. Try to attempt writing the code for the same.
5.3
1.
a)
b)
c)
2.
a)
b)
3.
a)
b)
Check Your Progress.
Answer in 1-2 sentences.
What are non cell table elements? Name them.
..............................................................................................................
..............................................................................................................
List the values that the FRAME attribute of the TABLE element can take.
..............................................................................................................
..............................................................................................................
List the values that the RULES attribute of the TABLE element can take.
..............................................................................................................
..............................................................................................................
Write the effect of the following values of the FRAME attribute of
TABLES.
BELOW -....................................................................................................
VSIDES -.....................................................................................................
Write the effect of the following values of the RULES attribute of
TABLES.
ROWS -.......................................................................................................
ALL-............................................................................................................
5.4 Nesting Tables
It is possible for you to include a table inside another table. This is called table
nesting. A table into which another table is nested is called the master table. The
table which is nested in another table is called the slave table. It is possible to apply
all the text and table formatting to tables nested in other tables.
We shall continue with our previous example to see how tables can be nested.
We shall divide the table data into two separate tables and then nest these tables into
another table. Let us see how this can be done :
<HTML>
<HEAD>
<TITLE>Nesting Tables</TITLE>
</HEAD>
<BODY>
<TABLE ALIGN=CENTER WIDTH=50% BORDER=2>
<CAPTION>
Animals, Birds and their young ones in two different tables
</CAPTION>
<TR><TD>
<TABLE BORDER CELLSPACING=2>
<TR ALIGN=CENTER>
<TD BGCOLOR=PINK ROWSPAN=2> Animals
<TD>Cat</TD>
<TD>Kitten</TD>
</TR>
<TR ALIGN=CENTER>
<TD>Dog</TD>
<TD>Puppy</TD>
</TR>
</TABLE>
</TD>
Advanced Web Designing / 48
<TD>
<TABLE BORDER CELLSPACING=2>
<TR ALIGN=CENTER>
<TD BGCOLOR=PINK ROWSPAN=2>Birds
<TD>Goose</TD>
<TD>Gosling</TD>
</TR>
<TR ALIGN=CENTER>
<TD>Duck</TD>
<TD>Duckling</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
5.5 Advantages and Disadvantages of Tables
The greatest advantage of tables is that it is possible for you to structure your
data property in the page. The data when structured, becomes easy to read. It is also
faster and easier for you to compare and evaluate the data, when presented in a tabular
form. The tables can contain not only text, but lists, forms, images, preformatted text
and paragraphs.
One of the biggest limitations of tables is that the table structure is complex and
it takes a lot of time to create the tables.
5.4 & 5.5 Check Your Progress.
Answer in 1-2 sentences.
a) What is a master table and a slave table?
..............................................................................................................
..............................................................................................................
b) Write any one advantage of Tables.
..............................................................................................................
..............................................................................................................
c) Write any one disadvantage of a table.
..............................................................................................................
..............................................................................................................
5.6 Summary
One very popular way of presenting data on the web are tables. A table can
contain not only text data, but also lists, forms, images, paragraphs, preformatted text
etc. It is also possible to nest tables within one another. The horizontal lines of data
in a table are rows and the vertical lines are columns. Each intersection of a row and
column is called a cell. To create a table in HTML the Table <TABLE> tag is used.
Tables / 49
The TABLE tag is a non empty tag set. There are two associated tags, with the
<TABLE> tag viz. The <TR> tag which is the Table Row element and creates a
horizontal row of cells. This can contain the table data and headings. The <TD> tag
is Table Data element <TD> specifies and indivisual cell in the table.
The third tag The Table Heading <TH> tag creates the Heading cells.
The <CAPTION> and </CAPTION> tags are used to give the caption to the
table which is displayed outside the table border.
The <TABLE> element attributes : The ALIGN attribute which specifies the
horizontal alignment of the table as a whole and not the alignment of indivisual cells
in the table. The values that this attribute can take are LEFT, CENTER and RIGHT. The
default alignment of the table is LEFT. The WIDTH attribute is used the specify the
width of the table relative to the width of the web page. The width can be specified as
a percentage or as a number. The BORDER attribute is used to specify a border to
the table and define the thickness of the border in pixels. The BORDER attribute sets
the border only to the outside table border and not the indivisual cells. CELLSPACING
specifies the spacing between table cells. This attribute takes the value as a number,
indicated in pixels. CELLPADDING is useful to create space between the border of the
cell and the cell data. The CELLPADDING attribute also takes a value as a number in
pixels.
To color the table or parts of a table the BGCOLOR attribute is used. This
attribute can be specified with the <TABLE>, <TR>, <TD> and <TH> tags. The BGCOLOR
attribute takes the value as the color name or color number.
Cell spanning is used to merge cells i.e. rows and columns. The most important
use of cellspanning is to create asymmetric tables. The ROWSPAN and COLSPAN
attributes are used in order to merge or span cells.
The non cell elements of a table are the FRAMES and RULES. With these
elements you can control the display of the rules and frames of a table.
Including a table inside another table is called table nesting. A table into which
another table is nested is called the master table. The table which is nested in another
table is called the slave table.
The greatest advantage of tables is that it is possible for you to structure your
data properly in the page. The data when structured, becomes easy to read. It is also
faster and easier for you to compare and evaluate the data, when presented in a tabular
form. The tables can contain not only text, but lists, forms, images, preformatted text
and paragraphs. One of the biggest limitations of tables is that the table structure is
complex and it takes a lot of time to create the tables.
5.7 Check your Progress - Answers
5.2
1.
a) - (iii)
2.
a) ALIGN b) cell
b) - (v)
c) - (i)
d) - (iv)
c) TABLE
d) MIDDLE
e) - (ii)
e) spanning
5.3
1.
a) Elements which are used to control the display of the rules and
frames of a table are non cell table elements. They are FRAMES
and RULES.
b) The FRAME attribute can take the values ABOVE, BELOW,
BORDER, BOX, HSIDES, VSIDES, LHS, RHS, VOID.
c) The values that the RULES attribute can take are NONE, ROWS,
COLS, ALL.
2.
a) Border will appear at the bottom side only.
b) Border will appear only along the vertical i.e. left and right sides
Advanced Web Designing / 50
3.
a) Rules will appear between rows only.
b) Rules will appear between all rows and all columns.
5.4 & 5.5
1. a) A table which nests another table is called as master table.
A table which is nested in another table is called the slave table.
b) The main advantage of the tables is that data can be structured
properly in the web page making it easier to read.
c) The biggest disadvantage of table is that it is a complex structure
thereby requiring a lot of time to create.
5.8 Questions for Self - Study
1.
Write short notes on :
a) Table attributes,
b) Non cell Table elements,
c) Advantages and Disadvantages of Tables.
2.
What is table nesting? Describe in detail.
3.
Explain how cells can be merged in a table.
4.
Describe the various attribute values and effects of the RULES attribute.
5.
Describe the FRAME attribute values and their effects.
6.
Explain the ALIGN and VALIGN attributes in connection with tables.
5.9 Suggested Readings
1.
The Complete Reference - Thomas Powell
2.
world wide web design with html - c xavier
3.
HTML DHTML JAVASCRIPT PERL CGI -Ivan Bayross
4.
WWW.W3Schools.com
5.
www.tizag.com
uuu
Tables / 51
NOTES
Advanced Web Designing / 52
CHAPTER 6
Frames
123456789012345678901234567890121
123456789012345678901234567890121
123456789012345678901234567890121
6.0
Objectives
123456789012345678901234567890121
123456789012345678901234567890121
6.1
Introduction
123456789012345678901234567890121
6.2
Creating Frames
123456789012345678901234567890121
123456789012345678901234567890121
6.3
The FRAME Tag
123456789012345678901234567890121
123456789012345678901234567890121
6.4
Linking Frames
123456789012345678901234567890121
123456789012345678901234567890121
6.5
Summary
123456789012345678901234567890121
6.6
Check your Progress - Answers
123456789012345678901234567890121
123456789012345678901234567890121
6.7
Questions
for Self Study
123456789012345678901234567890121
123456789012345678901234567890121
6.8
Suggested Readings
6.0 Objectives
After studying frames you will get the details about Frames
-
HTML frames
How to create horizontal, vertical frames
How to learn to create a grid of frames
How to learn the FRAME element and the FRAMESET element and their
attributes
understand how to link frames
to understand usage of frames
6.1 Introduction
Frames enable HTML pages to be divided into a series of rectangular sections.
They allow multiple HTML documents to be presented as independent windows in one
main browser window. Each frame will display a separate HTML document. Frames
can be either horizontal or vertical. Each frame is resizable and by default scrolls
separately. However, all browsers do not support frames. Browsers that can display
frames are called frames enabled browsers, those which cannot are called nonframes enabled browsers.
The most common application of frames is creating navigation bar or nav bar.
In one frame, you can present such information, which you may want always to be
present on your webpage. This frame may contain the table of contents, or logos for
example. When you make a selection from table of contents, the correct HTML document
is displayed in the specific frame. An HTML document containing frames consists of
a number of HTML documents.
6.2 Creating Frames
A regular HTML document has a <HEAD> and <BODY> tag.
A FRAMESET document has a head element and a <FRAMESET> element. The
<FRAMESET> tag structure replaces the <BODY> tag set. It is important to note that
an HTML document which contains the <BODY> tag cannot contain the <FRAMESET>
tag, and an HTML document that contains a <FRAMESET> tag cannot contain a
<BODY> tag.
The <FRAMESET> tag is a non empty tag set with many attributes. The two
main attributes of the <FRAMESET> tag are the ROWS and COLS which define the
layout of the frames. The values of the ROWS attribute are a measure of the height
of the frame rows relative to one another and the available browser screen area. The
value of the COLS attribute is a measure of the width of the frame column relative
to one another and available browser screen area. Both the ROWS and COLS attributes
can be defined as percentages, pixels or relative scale values. The FRAME element
Frames / 53
uses a SRC attribute which points to the document which you wish to display in each
frame. The frameset element can contain a NOFRAMES element, in case you wish
to present alternate text where the browser does not support frames.
l Creating Vertical Frames :
Vertical frames can be created with the use of the COLS attribute within the
<FRAMESET> tag. The width of each column is a value separated by a comma. The
default value for a COLS attribute is 100% which means that if you do not specify the
numbers of columns by giving the column width, then there will be only one column.
Each row will be set to the entire width of the window.
eg. <FRAMESET COLS=30%,60%> - This tag will specify two columns. The
first column will take 30 percent of the total browser’s space and the second column
will take 70% of the total browser’s space.
<FRAMESET COLS=1 *,3*> - With this specification, the first column will take
the relative value of one part of the browser and the second column will take the relative
value of three parts of the browser window. This means that since we have requested
a total of four parts
The first frame will get one part out of four parts of the browser window i.e. 25%
and the second will get three parts out of four i.e. 75% of the total browser window.
l Creating Horizontal Frames :
The ROWS attribute is used to create horizontal frames. It works exactly like
the COLS attribute except that it will create horizontal rather than vertical frames.
Horizontal frames are created from top to bottom. You can specify the height of frames
either using absolute values (percentage or pixels) and relative values.
eg. <FRAMESET ROWS=25%,50%,25%> - This frameset will create three
horizontal frames. The first frame and the third frame will take 25% of the total browser
window and the middle frame would take 50% of the total browser window.
l Creating a grid of frames :
You can create a grid of frames by specifying both the COLS and ROWS
attributes in the <FRAMESET> tag. eg. <FRAMESET COLS=50%,50%
ROWS=25%,25%,50%> -This will create two columns and three rows i.e. a total of six
frames, from left to right and top to bottom. The first column will be 50% of the total
width browser window and the second column will also be 50% of the browser window.
The first two rows will use 25% each of the total browser area and the third row will
be 50 percent of the window’s height.
It is also possible to nest one FRAMESET in another FRAMESET. A series of
nested frames can be used to divide frames into more frames.
The <BORDERCOLOR> Attribute :
This is the attribute of the FRAMESET element which is used to set the color
of the frame’s border. The default color is gray. The value that the attribute can take
is the color name or the color code.
6.2
Check Your Progress.
Fill in the blanks.
a) Vertical frames are created with the .........................attribute of the
FRAMESET tag.
b) Horizontal frames are created with the ......................... attribute of the
FRAMESET tag.
c) The FRAME element uses the.........................attribute which points to the
document to be displayed in each frame.
d) The values of the ROWS attribute are a measure of the .........................of
the frame rows relative to one another and the available browser screen area.
Advanced Web Designing / 54
6.3 The FRAME Tag
The FRAME tag is the tag which is used to refer to the HTML document which
has to appear in the frame. The <FRAME> tag is to be nested in the <FRAMESET>
opening and closing tags. It is an empty tag. There has to be one <FRAME> tag for
each frame that you want to appear in your document. There must be the same number
of <FRAME> tags as the number of rows and columns that you have defined in the
<FRAMESET> tag. The <FRAME> tag has one necessary attribute the SRC. The
value of this attribute is the name of the HTML document which is to appear in that
frame. eg. <FRAMESET ROWS=25%,50%,25%>
<FRAME SRC=doc1.html>
<FRAME SRC=doc2.html>
<FRAME SRC=doc3.html>
</FRAMESET>
This will create three horizontal frames in the browser window. In the first frame,
the contents of the doc1.html document will be displayed, in the second frame the
contents of the doc2.html document will be displayed and in the third frame the
contents of the doc3.html will be displayed.
In order to see the use of the FRAME tag along with the FRAMESET element
we shall study the following example :
Type the following code and save in the file named Frames.
<HTML>
<HEAD>
<TITLE>Creating Frames</TITLE>
<FRAMESET COLS=25%,50%,25%>
<FRAME SRC=ONE.HTML>
<FRAME SRC=TWO.HTML>
<FRAME SRC=THREE.HTML>
</FRAMESET>
</HTML>
This HTML document specifies three vertical frames with the COLS attribute. The
source i.e. the HTML document to appear in the first column is ONE. HTML, the source
for the second column is TWO.HTML and the source for the third column is the
document THREE. HTML. Let us now create these three documents:
To create the document ONE.HTML type the following code and save the file
as ONE.HTML
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
Frames / 55
<FONT SIZE=4 COLOR=GREEN>This is the first vertical frame </FONT>
</BODY>
</HTML>
Create the second file TWO.HTML as follows :
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<FONT SIZE=5 COLOR=RED FACE=CITYBLUEPRINT>This is the second
vertical frame</FONT>
</BODY>
</HTML>
Create the third file THREE.HTML as follows :
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<FONT SIZE=3 COLOR=GREEN FACE=VERDANA>This is the third
vertical frame</FONT>
</BODY>
</HTML>
Now view the file FRAMES.HTML in the browser. You will see the three documents
ONE, TWO and THREE in the three columns in the browser window. The first and the
third documents will be allotted 25%. of the total browser window and the second
column will be allotted 50% of the total browser window.
l The attributes of the <FRAME> tag : A number of attributes can be used
with the <FRAME> element to change the appearance of frames and the way they
work.
FRAMEBORDER Attribute : This is used to define a border around the frame.
Each frame by default has a gray border. The border can be removed by specifying
FRAMEBORDER=0.
BORDERCOLOR : The BORDERCOLOR attribute can be used to set the color
of the frame border. This is useful to color indivisual frame borders.
MARGINHEIGHT and MARGINWIDTH : The MARGINHEIGHT determines the
number of pixels between the contents of the frame and the top and bottom edges of
the frame. The MARGINWIDTH is used to set the space between the frame’s content
and the left and right edges of the frame. The values of these attributes are specified
in pixels.
NORESIZE : This attribute is used to prevent the users from resizing your frame.
Normally, each frame is resizable, so the user can drag the frame border to make the
frame larger or smaller. By adding the NORESIZE attribute in the <FRAME> tag, the
resizing of the frame by the user is prevented.
This attribute is added as : <FRAME SRC=doc1 .html NORESIZE>.
SCROLLING : If the contents of a frame do not fit in the frame’s dimensions,
the frame is displayed with a horizontal or vertical scroll bar or both if required. By
default, these scroll bars appear only when they are necessary i.e. only when the
window is not able to display the entire contents within its specified dimensions. You
can choose to always have scroll bars, or have no scroll bars at all. The values that
this attribute takes are : YES, NO, AUTO.
By including SCROLLING= “YES”, a scroll bar will always be included in the
frame’s window. With the attribute value “NO”, there will be no scrollbars. The attribute
value “AUTO” is the default behaviour i.e. the scroll scroll bars will appear only when
necessary.
Advanced Web Designing / 56
NAME : The NAME attribute sets a name to the frame. This name Can-then be
used in links located in other frames to target the named frame.
6.3
Check Your Progress.
Write True or False.
a) One FRAME tag for each frame that has to appear in your document is
necessary.
b) You can choose to have no scroll bars for frames.
c) The SRC attribute of the FRAME tag is optional.
d) You cannot set names to FRAMES.
e) When you use the FRAME tag the FRAMESET tag is not required.
6.4 Linking Frames
We can have links that target a particular frame. Once we name a frame, we can
create links to target the named frame in other frames. It is possible to create more
sophisticated web pages which can include nav bar, table of contents, on line catalogues
etc. by linking frames. We have already learnt to create Hyperlinks with the Anchor Tag.
To link frames, we shall study some more attributes of the tags we have already learnt.
Two attributes are needed to create a basic link between two frames.
l The first is the NAME attribute, which is the attribute of the <FRAME>
tag. This attribute gives a name to the frame document.
l The other attribute is the TARGET attribute of the <A> anchor tag.
This attribute tells the Anchor tag in which frame to display the document.
With the following example the linking of frames will be studied :
In this example we have created three frames in the web page. The first frame
at the top is the Title frame which will remain on the web page at all times. There are
two vertical frames. The frame on the left contains links which target the frame on the
right. When you click on a link in the left frame, which serves as a navigation bar, the
contents in the right frame will change, and they will display the contents of the file
which is accessed with the selected hyperlink.
The basic structure of the three frames is first created in an HTML document
as :
<HTML>
Frames / 57
<HEAD>
<TITLE>Creating Links in Frames</TITLE>
</HEAD>
<FRAMESET ROWS=1*,3*>
<FRAME SRC=HEADS.HTML MARGINHEIGHT=5 SCROLLING=NO>
<FRAMESET COLS=1*,3*>
<FRAME SRC=INDEX.HTML SCROLLING=NO>
<FRAME SRC=CH1.HTML NAME=FIRST SCROLLING=NO>
</FRAMESET>
</FRAMESET>
</HTML>
The title frame is to be created as another HTML document:
<HTML>
<HEAD>
</HEAD>
<BODY BGCOLOR=TEAL>
<CENTER>
<FONT SIZE=5 COLOR=YELLOW>THE MAIN HEADING
FRAME</FONT>
</CENTER>
</BODY>
</HTML>
The first vertical frame, which displays the links is created as
another document:
<HTML>
<HEAD>
</HEAD>
<BODY BGCOLOR=PINK> <CENTER>
<FONT SIZE=2 FACE=ARIAL COLOR=BLUE>The table of contents</FONT><BR>
<FONT SIZE=3 FACE=ARIAL>The Navigation bar</FONT><BR><BR>
<FONT SIZE=2>Click on the links below <BR>
to display the related information <BR>
in the adjacent frame</FONT><BR><BR>
<A HREF=CH1.HTML TARGET=FIRST>Chapter 1</A><BR>
<A HREF=CH2.HTML TARGET=FIRST>Chapter 2</A><BR>
<A HREF=CH3.HTML TARGET=FIRST>Chapter 3</A><BR> </BODY>
</HTML>
This frame contains links to other documents. When you click on a particular
link, the contents of the document specified as the value of the HREF attribute will be
displayed in the vertical frame on the right. Note that the TARGET value has the same
NAME which is the name of the frame in which the document is to be displayed. This
frame is named at the time when we created the frames in the first document.
Now what remains is the code for the indivisual HTML documents for which the
links have been created in the Index. The code for these documents is as follows :
Contents for Chapter 1
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<FONT SIZE=4 FACE=ARIAL>Chapter 1 </FONT><BR><BR>
When you click on the link in the Navigation Bar<BR>
Advanced Web Designing / 58
the contents of Chapter 1 will be displayed<BR>
in this frame.<B.R>
</BODY>
</HTML>
Contents for Chapter 2
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<FONT SIZE=4 FACE=ARIAL>Chapter 2</FONT><BR><BR>
This is chapter 2<BR>
You click on the link Chapter 2<BR>
in the Navigation Bar to view<BR> . the contents of this chapter<BR>
in this frame.<BR>
</BODY>
</HTML>
Contents for Chapter 3
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<FONT SIZE=4 FACE=ARIAL>Chapter 3</FONT><BR><BR>
When you click on the link in the Navigation Bar<BR>
the contents of Chapter 3 will be displayed<BR>
in this frame.<BR>
</BODY>
</HTML>
l The <BASE> Tag : When there are a number of links to be targeted it
becomes inconvenient to use the TARGET= framename attribute with each and every
link. For this purpose we can use the <BASE> tag. The <BASE> tag allows you to
specify the target of all the Anchor elements with a single TARGET attribute. You are
not required to write the TARGET attribute in each of the Anchor tags. This tag is to
be placed above the <HEAD> tag in the HTML document.
Thus, in the above example you can remove the TARGET tag from each Anchor
tags of Chapter 1, Chapter2 and Chapter 3, and place the BASE tag in the HTML code
as follows :
<HTML>
<BASE TARGET=FIRST>
<HEAD>
</HEAD>
......
The remaining code is to be typed as it is.
q Reserved Values for the TARGET attribute :
The following are values which are reserved for the TARGET attribute and the
produce specific results when the user clicks on the hyperlink in a frame.
_blank
-
This attribute value loads the HTML document (specified by
Frames / 59
the Anchor tag) into a new, unnamed window.
_self
-
This loads the HTML document into the calling frame itself.
This attribute value is the default if no NAME and TARGET
attributes have been used in the FRAMESET.
_parent
-
This loads the HTML document into the calling frame’s parent
frameset window
_top
-
Loads the HTML document into the calling frame’s top level
frame set. i.e. removes frames altogether and replaces the
entire frameset document with the value of the HREF attribute
of the anchor tag.
6.4
Check Your Progress.
Fill in the blanks.
a) Two attributes needed to create a basic link between two frames are the
______________ and the ______________.
b) The ______________ attribute value loads the HTML document into a new,
unnamed window.
c) The ______________ tag allows to specify the target of all the Anchor
elements with a single TARGET attribute.
6.5 Summary
Frames enable HTML pages to be divided into a series of rectangular sections.
They allow multiple HTML documents to be presented as independent windows in one
main browser window. Each frame will display a separate HTML document. Frames can
be either horizontal or vertical. Each frame is resizable and by default scrolls separately.
However, all browsers do not support frames. Browsers that can display frames are
called frames enabled browsers, those which cannot are called non-frames enabled
browsers.
A frameset document has a head element and a <FRAMESET> element. The
<FRAMESET> tag structure replaces the <BODY> tag set. The <FRAMESET> tag is
a non empty tag set with many attributes. The two main attributes of the <FRAMESET>
tag are the ROWS and COLS which define the layout of the frames. The values of the
ROWS attribute are a measure of the height of the frame rows relative to one another
and the available browser screen area. The value, of the COLS attribute is a measure
of the width of the frame column relative to one another and available browser screen
area. Both the ROWS and COLS attributes can be defined as percentages, pixels or
relative scale values.
The <FRAME> tag is to be nested in the <FRAMESET> opening and closing
tags. It is an empty tag. There has to be one <FRAME> tag for each frame that you
want to appear in your document. The <FRAME> tag has one necessary attribute the
SRC. The value of this attribute is the name of the HTML document which is to appear
in that frame.
We can have links that target a particular frame. Once we name a frame, we can
create links to target the named frame in other frames. Two attributes are needed to
create a basic link between two frames. The first is the NAME attribute, which is the
attribute of the <FRAME> tag. This attribute gives a name to the frame document. The
other attribute is the TARGET attribute of the <A> anchor tag. This attribute tells the
Anchor tag in which frame to display the document.
Reserved Values for the TARGET attribute are_blank, _self, _parent,_top.
Advanced Web Designing / 60
6.6 Check your Progress - Answers
6.2
a)
b)
c)
d)
COLS
ROWS
SRG
height
6.3
a)
b)
c)
d)
e)
True
True
False
False
False
6.4
a)
b)
c)
NAME, TARGET
_blank
BASE
6.7 Questions for Self - Study
1.
Write a Short Note on FRAMESET tag.
2.
Describe the attributes of the FRAME tag.
3.
What is linking frames? Describe how to link frames.
4.
Write a short note on the reserved values of the TARGET attribute.
6.8 Suggested Readings
1.
The Complete Reference - Thomas Powell
2.
world wide web design with html - c xavier
3.
HTML DHTML JAVASCRIPT PERL CGI -Ivan Bayross
4.
WWW.W3Schools.com
5.
www.tizag.com
uuu
Frames / 61
NOTES
Advanced Web Designing / 62
CHAPTER 7
Forms
12345678901234567890123456789012123
12345678901234567890123456789012123
12345678901234567890123456789012123
12345678901234567890123456789012123
7.0
Objectives
12345678901234567890123456789012123
12345678901234567890123456789012123
7.1
Introduction
12345678901234567890123456789012123
12345678901234567890123456789012123
7.2
The FORM tag
12345678901234567890123456789012123
7.3
The INPUT tag
12345678901234567890123456789012123
12345678901234567890123456789012123
7.3.1 Text
12345678901234567890123456789012123
12345678901234567890123456789012123
7.3.2 Password
12345678901234567890123456789012123
12345678901234567890123456789012123
7.3.3 Checkboxes
12345678901234567890123456789012123
7.3.4 Radio Buttons
12345678901234567890123456789012123
12345678901234567890123456789012123
7.3.5 Submit Button
12345678901234567890123456789012123
12345678901234567890123456789012123
7.4
The SELECT Tag and the TEXTAREA Tag
12345678901234567890123456789012123
12345678901234567890123456789012123
7.4.1 Select Tag
12345678901234567890123456789012123
7.4.2 TextArea Tag
12345678901234567890123456789012123
12345678901234567890123456789012123
7.5
A Sample Form
12345678901234567890123456789012123
12345678901234567890123456789012123
7.6
Processing Forms
12345678901234567890123456789012123
12345678901234567890123456789012123
7.7
Summary
12345678901234567890123456789012123
7.8
Check Your Progress - Answers
12345678901234567890123456789012123
12345678901234567890123456789012123
7.9
Questions for Self - Study
12345678901234567890123456789012123
12345678901234567890123456789012123
7.10 Suggested Readings
12345678901234567890123456789012123
7.0 Objectives
After studying “FORMS” you will be able to understand following points:
– How to build interactivity in web pages.
– use the structure of the FORM container.
– use the form elements including the INPUT type, and select and text area
tags.
– know how forms are processed.
– create different types of forms.
7.1 Introduction
The need of forms : Forms are used to build interactivity in the web page.
Forms may be used to get a feedback from the surfer, complete a transaction etc. A
form is a collection of data in specified fields. The fields are of various types like radio
buttons, text boxes, pull down menus etc. A field in the form is also known as control.
The role of HTML with forms is specific. HTML tags are used to create and name the
form controls, format their appearance and behaviour and determine their default values
if any. HTML itself cannot process a form. When the user has filled and submitted a
form, it is the server which takes this information and sends it to the specified program.
The server level program, which receives the data submitted from the form and
processes it is called a CGI (Common Gateway Interface). CGI are of two types :
CGI programs and CGI scripts. If you use any programming language like C, C++,
Java then you create a CGI program. If you use a script like Perl, Applescript which
runs on the Web server, then you create a CGI script. Another way, which is an
alternative to CGI is to use a mail program. You can specify the e-mail address where
the data collected via the form is to be sent.
7.2 The FORM tag
Since a form is a collection of fields of information, the syntax for a HTML form
is a collection of properly arranged empty and non-empty tag sets and their required
Forms / 63
attributes. The <FORM> tag is a block level element and it creates a form area. It is
a non empty tag set. This tag contains all the form elements. The form can contain
any HTML element like images, tables, frames etc. It however, cannot contain another
form. But you can have more than one form on a page as long as the form elements
are not nested. The two main attributes that the <FORM> tag takes are:
1) ACTION : This is used to specify the e-mail address to which the information
is to be sent or the URL of the CGI program which will use and process the form
information.
2) METHOD : This specifies that the information filled in the form should be
posted to the URL which is given in the ACTION attribute. There are only two possible
values for the METHOD attribute viz. GET or POST. The default value is GET.
The INPUT element is the most common tag within the <FORM> container. It
specifies the type of the form element being created. INPUT is used to create a variety
of controls or types of form elements (field types) like textfields, checkboxes, password
fields and radio buttons. The three required attributes of the <INPUT> tag are :
TYPE : The type attribute specifies the type of the form element
The values it can take are text, password, checkbox, radio, button.
NAME : It is an unique identifier.
VALUE : Used only with checkboxes and radio buttons. Each radio
button or checkbox must have its own value.
Two types of field types TEXT AREA and LIST BOXES do not make use of the
INPUT tag. Instead they have their own tag sets. The TEXT AREA tag is used to
create multiline text input controls. It differs from a textfiefd. A textfield with the input
element creates only a single line text input control. The SELECT option contains one
or more option elements. The select element is used to create pull down menus.
It is a good idea to first understand all the form control elements and then make
use of them together in an example. Therefore, we shall study the various form control
elements indivisually first and later see an example of a form.
7.2
Fill
a)
b)
c)
d)
e)
Check Your Progress.
in the blanks.
A form is used to build ......................... in a web page.
A form is a ......................... level element.
A field in a form is also known as a ..........................
The two main attributes that a FORM element takes are ACTION and
..........................
The server level program, which receives the data submitted from the form
and processes it is called a .........................
7.3 The INPUT tag
The most commonly used element is the <INPUT> element. The syntax for the
input tag is <INPUT TYPE=text, NAME=first>
The TYPE attribute is used to specify the type of control that you want viz. text,
radio, button, checkbox, password. The NAME attribute is an unique name or identifier.
The Input tag also takes the value attribute if the input type is checkboxes or radio
buttons. The default type of an input element is TEXT. Let us take a look at the various
types for an INPUT tag :
7.3.1 TEXT : These are used to create single line text boxes. These are mostly
used to request information from the user, like names, addresses etc. You can enter
alphanumeric data in the text field. The width of the field in characters is specified using
the SIZE attribute. The number of characters which can be input in the text field are
specified by using the MAXLENGTH attribute. You can also add a default text value
using the VALUE attribute. This value appears as the default value in the text field. The
Advanced Web Designing / 64
user can change it if required.
eg.
<FORM METHOD=GET ACTION=HTTP://ABC.COM>
Enter your First Name :<INPUT TYPE=TEXT NAME=FIRST>
</FORM>
In the web browser the form field will be shown as :
7.3.2 PASSWORD :
The PASSWORD field is similar to the text field, except that whatever the user
types is not displayed on the screen. This type of input is used for passwords, or other
important but private information like credit card numbers. Such information is not
displayed when the user enters it, thus preventing others from seeing it. Any alphanumeric
data can be entered in the PASSWORD field. The size of this data can be specified
by using the SIZE attribute and the maximum length in characters can also be specified
by using the MAXLENGTH attribute.
eg. FORM METHOD=GET ACTION=HTTP://ABC.COM>
Enter your Password :<INPUT TYPE=PASSWORD NAME=CREDIT>
</FORM>
7.3.3 CHECKBOXES :
A checkbox is just an empty box by default. You type your label next to the
checkbox. Checkboxes are used to provide the user with multiple options for a particular
field. The user can select any number of options from the available options. Checkboxes
require the VALUE attribute. All the checkboxes in one group will have the same NAME
value, but each indivisual checkbox will have a different attribute value for the VALUE
attribute. Thus, you create a number of checkboxes with the same NAME attribute but
different VALUE attributes. Each checkbox can be selected or deselected, by clicking
in the checkbox.
eg. If you want the user to select the favourite hobbies from a list of hobbies,
provided with a checkbox :
<FORM METHOD=GET ACTION=HTTP://ABC.COM>
Select Your Hobbies :<BR>
<INPUT TYPE=CHECKBOX NAME=HOBBY VALUE=SWIM>SWIMMING<BR>
<INPUT TYPE=CHECKBOX NAME=HOBBY VALUE=READ>READING<BR>
<INPUT TYPE=CHECKBOX NAME=HOBBY VALUE=TV>WATCHING TV<BR>
<INPUT TYPE=CHECKBOX NAME=HOBBY VALUE=CRIC>PLAYING
CRICKET<BR>
<INPUT TYPE=CHECKBOX NLLAME=HOBBY
VALUE=COOK>COOKING<BR>
</FORM>
Forms / 65
Note that if you do not use the <BR> tag after each checkbox, all the checkboxes
will appear in the same line. The Name value for all checkboxes is the same i.e. Hobby,
however the VALUE attributes takes different values for each checkbox. When the form
is submitted for processing the field name will be submitted only if the control is
checked.
7.3.4 RADIO BUTTONS :
Radio buttons are similar to Checkboxes. The only difference is that you use a
radio button only when you want to allow the user a single choice, from the available
list. All the radio buttons in a single group will have the same NAME value, but each
radio button will be indivisually identified with a different VALUE attribute. You can give
any number of radio buttons in a group, however only one radio button from that group
will be selected. Radio buttons are displayed as circles, checkboxes are displayed as
squares.
For example, if you want the user to make a selection from the different age
groups specified make use of the following code to see the effect of the radio buttons.
Your Age Group : <BR>
<INPUT TYPE=RADIO NAME=AGE VALUE=SIXTEEN>16-20 YEARS<BR>
<INPUT TYPE=RADIO NAME=AGE VALUE=TWENTYONE>21-25 YEARS<BR>
<INPUT TYPE=RADIO NAME=AGE VALUE=TWENTYSIX>26-30 YEARS<BR>
<INPUT TYPE=RADIO NAME=AGE VALUE=THIRTYONE>31-35 YEARS<BR>
<INPUT TYPE=RADIO NAME=AGE VALUE=THIRTYSIX>36-40 YEARS<BR>
The user can only select one age group to which he/she belongs from the above
list. You can also indicate the default choice by making use of the CHECKED attribute.
This attribute should be placed in the input tag of the radio button whose value you want
to be the default value. The user has to click on the radio button of his choice.
7.3.5 The Submit Button :
Every form must have a submit button. The label inside the submit button is
taken from the VALUE attribute. The Submit button is created using the INPUT tag. The
Submit button will execute the action specified by the values of the attributes in the
<FORM> tag.
eg. <FORM ACTION=mailto:[email protected] METHOD=post>
When the user clicks on the Submit button, the contents of the form fields will
be uploaded to the address abc.com. A form can include more than one submit button.
This allows the form to be submitted with different values, depending upon which submit
button is clicked.
<FORM ACTION=HTTP://WWW.ABC.COM>
<INPUT TYPE=SUBMIT VALUE=”I Agree”>
<INPUT TYPE=SUBMIT VALUE=”I Disagree”> </FORM>
These two Submit buttons will be created with the above code. Thus depending
upon which button the user clicks, the further action will be taken. An image can also
Advanced Web Designing / 66
be used for a submit button, by specifying TYPE=”IMAGE” instead of TYPE=”SUBMIT”.
You have to specify the SRC for the image. You should also specify the ALT attribute
for alternate text. eg. <INPUT TYPE=IMAGE SRC=pic1 .gif ALT=SUBMIT>
7.3.6 The RESET Button :
The RESET button clears the contents of the form fields. i.e. it just resets all
of the form’s controls to their initial values. The value of the reset button is never
submitted with the form. The VALUE of the reset button is displayed in the button.
eg. <INPUT TYPE=RESET VALUE=CLEAR>.
Here the word CLEAR will appear in the reset button and the all the form fields
will be cleared when the user clicks on the RESET button.
7.3 Check Your Progress
Write True or False.
a) You can make multiple choices with radio buttons.
b) The RESET button is used to clear the contents of all the form fields.
c) Checkboxes are displayed as squares.
d) Textboxes can create multiple line text.
e) Whatever is typed by the user in the PASSWORD field is not displayed on
the screen.
7.4 The SELECT tag and the TEXTAREA tag
7.3.1 The SELECT Tag :
This tag is used to create a menu control. The Select element should contain
one or more option elements. Each option element will create an item on the menu.
The SELECT tag is a non empty tag set and can be used as follows :
eg.My Favourite Color <BR>
<SELECT NAME=color>
<OPTION> Blue
<OPTION> Green
<OPTION> Yellow
<OPTION> Orange
<OPTION> Red
<OPTION> Purple </SELECT>
With this tag a drop down menu control will be created. If you specify a SIZE
attribute in the SELECT tag then a list box will be displayed instead of a dropdown
menu. If the SIZE specified is less than the number of options provided, then a scroll
bar will automatically be added by the browser. If the value of the SIZE attribute is more
than the number of options provided, blanks lines will be left after the list.
Forms / 67
By default, only one item will be selected. If you want to make multiple selections
then the MULTIPLE attribute of the SELECT tag has to be used.
eg. <SELECT NAME=color MULTIPLE>will allow you to select multiple colors
from the given list.
The OPTION tag can have a VALUE attribute which can be set to some text if
you want to specify the text to be submitted when the corresponding item is selected.
The default menu item can also be specified by using the SELECTED attribute with the
OPTION tag.
7.3.2 The TEXTAREA Tag :
As we have seen an input element creates a single line text box with type = text.
A TEXTAREA tag can create a multiple line text box. The TEXTAREA tag contains a
NAME attribute and the ROWS and COLS attribute. You specify the number of rows
and columns as the values of these attributes. You can also include default text which
you may want to appear in the text area. This is optional. The <TEXTAREA> is a non
empty tag set. The default text in the text area is treated as preformatted and therefore
takes into account blank spaces and carriage returns.
TEXTAREA<BR>
<TEXTAREA ROWS=12 COLS=60 NAME=text>
Your other interests :
Do you need Further Information?
Your form will be processed very soon!
</TEXTAREA>
In this example, you can see that you have created a multiple line form control.
The default lines are also included in the text area. Even if you specify the number of
columns and rows, the user input is not limited. The users can type as much text as
they like. The browsers use scroll bars to help the user move from place to place.
7.4
Check Your Progress.
Answer in 1-2 lines.
a)
What is the SELECT tag?
..............................................................................................................
..............................................................................................................
b)
What is the TEXTAREA tag?
..............................................................................................................
..............................................................................................................
Advanced Web Designing / 68
7.5 A Sample Form
Having studied the FORM tag and the various form control elements, let us now
use these elements to create a sample form which will accept the following information
from the user :
– the first name and the last name (with input type text and the select tag)
– the house number and city (with input type text for house number and the
select tag for the city)
– the password (with input type password)
– a list of hobbies from the given hobbies (with input type checkbox)
– age group (with input type radio button)
– a text area to write his comments, opinions, feedback etc.
– provide the submit and reset buttons to submit and reset the form respectively.
In the form we have made use of the non breaking space character (&nbsp).
You can use &nbsp if you want more spaces in your HTML text. The maindifference between a non breaking space and normal space is that a browser will not
wrap (or break) a line of text a point where there is a non breaking space.
The code for this form will be as follows :
<HTML>
<HEAD>
<TITLE>Forms</TITLE>
</HEAD>
<BODY>
<FORM ACTION=HTTP://ABC.COM>
<FONT COLOR=RED FACE=CITYBLUEPRINT>
First Name:&nbsp;&nbsp;&nbsp;<INPUT TYPE=TEXT MAXLENGTH=10>
House No. :&nbsp; <INPUT TYPE=TEXT MAXLENGTH=10 SIZE=10>
&nbsp;&nbsp;&nbsp;&nbsp;<BR>
Last Name :&nbsp; <INPUT TYPE=TEXT MAXLENGTH=10>
Area :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<INPUT TYPE=TEXT MAXLENGTH=10 SIZE=10>
City :
<SELECT NAME=CITY>
<OPTION SELECTED>Pune
<OPTION>Mumbai
<OPTION>Chennai
<OPTION>Calcutta
<OPTION>Bangalore
</SELECT><BR>
</FONT>
Your Password :&nbsp;
<!NPUT TYPE=PASSWORD NAME=PASS SIZE=5 MAXLENGTH=5> <BR>
<FONT COLOR=BLUE FACE=ARIAL SIZE=2>
Select Your Hobbies :<BR>
<INPUT
TYPE=CHECKBOX
NAME=HOBBY
VALUE=SWIM>
Swimming&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <INPUT
TYPE=CHECKBOX
NAME=HOBBY
VALUE=READ>
Reading&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<INPUT TYPE=CHECKBOX NAME=HOBBY VALUE=TV>Watching TV<BR>
<INPUT TYPE=CHECKBOX NAME=HOBBY VALUE=CRIC>
Playing Cricket&nbsp;
<INPUT TYPE=CHECKBOX NAME=HOBBY VALUE=COOK>Cooking<BR>
</FONT>
<FONT COLOR=GREEN SIZE=3>Your Age Group : <BR>
<INPUT TYPE=radio NAME=age VALUE=sixteen>
16-20 years&nbsp;&nbsp;&nbsp;&nbsp;
<INPUT TYPE=radio NAME=age VALUE=twentyone>
21-25 years&nbsp;&nbsp;&nbsp;
Forms / 69
<INPUT TYPE=radio NAME=age VALUE=twentysix>
26-30 years&nbsp;&nbsp;&nbsp;
<INPUT TYPE=radio NAME=age VALUE=thirtyone>
31-35 years&nbsp;&nbsp;&nbsp;
<INPUT TYPE=radio NAME=age VALUE=thirtysix>
36-40 years<BR>
</FONT>
<TEXTAREA ROWS=6 COLS=40 NAME=text>
For your comments, feedback and suggestions
</TEXTAREA><BR>
<INPUT TYPE=SUBMIT VALUE=”Submit”>
<INPUT TYPE=RESET VALUE=”Clear”>
</FORM>
</BODY>
</HTML>
7.6 Processing Forms
As we have seen in the beginning the ways to process a form are by using CGI
program, by using a mailto link and by using a script.
Using Active Script:
Active scripting languages might not be able to handle everything in the form.
Active script works best only when the form data is going to be manipulated in order
to create a new page. But if the data is to be compiled and stored then active script
cannot handle it. The best use of active script is to validate the data submitted through
the form, prior to submitting it to an email address or CGI program.
Using Mailto Processing :
A valid mailto URL can be used to send the data collected in the form to a mail
address. Only mailing the data does not compile or accumulate data. The email should
be responded to and also processed. The email has to be processed.
Using CGI :
The most popular CGI language is PERL (Practical Extraction and Report
Language) which is a free interpreted scripting language. By using CGI it is possible
to send the form information to another web page or email address. You can update
a guest book, send back customer generated feedback email and submit credit card
numbers to banks.
7.5
&
7.6 Check Your Progress.
Write True or False.
a)
PERL is an example of active script.
b)
By using CGI it is possible to send information to another web page.
c)
Active script cannot handle storage and compilation of data.
d)
&nbsp can create white spaces.
e)
Radio buttons are used in the sample form for selection of hobbies.
f)
The example form contains a textarea.
7.7 Summary
Forms are used to build interactivity in the web page. Forms may be used to
get a feedback from the surfer, complete a transaction etc. A form is a collection of
data in specified fields. A field in the form is also known as control. HTML tags are
used to create and name the form controls, format their appearance and behaviour and
Advanced Web Designing / 70
determine their default values if any. HTML itself cannot process a form. When the user
has filled and submitted a form, it is the server which takes this information and sends
it to the specified program.
The <FORM> tag is a block level element and it creates a form area. It is a non
empty tag set which contains all the form elements. The form can contain any HTML
element like images, tables, frames, but it cannot contain another form. The two main
attributes that the <FORM> tag takes are ACTION which specifies the e-mail address
to which the information is to be sent or the URL of the CGI program which will use
and process the form information, and the METHOD which specifies that the information
filled in the form should be posted to the URL which is given in the ACTION attribute.
There are only two, possible values for the METHOD attribute viz. GET or POST. The
default value is GET.
The INPUT element specifies the type of the form element being created.
INPUT is used to create a variety of controls or types of form elements (field types)
like textfields, checkboxes, password fields and radio buttons. The three required
attributes of the <INPUT> tag are TYPE, NAME and VALUE. Two types of field types
TEXT AREA and LIST BOXES do not make use of the INPUT tag. Instead they have
their own tag sets. The default type of an input element is TEXT.
Using Mailto Processing : A valid mailto URL can be used to send the data
collected in the form to a mail address. Only mailing the data does not compile or
accumulate data. The email should be responded to and also processed.
7.8 Check your Progress – Answers
a)
b)
c)
d)
e)
7.2
interactivity
block
control
METHOD
CGI (Common Gateway Interface)
a)
b)
c)
d)
e)
7.3
False
True
True
False
True
a)
b)
7.4
The SELECT tag which should contain one or more option
elements is used to create a menu control. Each option
element will create an item on the menu.
The TEXTAREA tag creates multiple line textbox where a
textarea is created. The default text is treated as preformatted
and the tag contains the ROWS, COLS and NAME attributes.
7.5 & 7.6
a)
b)
c)
d)
e)
f)
False
True
True
True
False
True
Forms / 71
7.9 Questions for Self - Study
1.
2.
3.
4.
5.
6.
7.
Write
What
What
What
What
Write
What
a short note on HTML forms.
is a FORM tag? What are its main attributes?
are the different types for an INPUT tag? Discuss each type in detail.
are the RESET and SUBMIT buttons?
is the SELECT tag? Discuss its usage with an example.
a short note on TEXTAREA.
is form processing? What are the ways to process a form?
7.10 Suggested Readings
1.
The Complete Reference - Thomas Powell
2.
world wide web design with html - c xavier
3.
HTML DHTML JAVASCRIPT PERL CGI -Ivan Bayross
4.
WWW.W3Schools.com
5.
www.tizag.com
uuu
Advanced Web Designing / 72
NOTES
Forms / 73
NOTES
Advanced Web Designing / 74
Chapter 8
Introduction to JavaScript
123456789012345678901234567890121234
123456789012345678901234567890121234
123456789012345678901234567890121234
8.0
Objectives
123456789012345678901234567890121234
123456789012345678901234567890121234
8.1
Introduction
123456789012345678901234567890121234
123456789012345678901234567890121234
8.2
What is JavaScript?
123456789012345678901234567890121234
123456789012345678901234567890121234
8.3
What can a JavaScript do?
123456789012345678901234567890121234
123456789012345678901234567890121234
8.4
JavaScript and Java
123456789012345678901234567890121234
8.4.1 JavaScript Characteristics
123456789012345678901234567890121234
123456789012345678901234567890121234
8.4.2 JavaScript Comments
123456789012345678901234567890121234
123456789012345678901234567890121234
8.5
The Client Server Architecture
123456789012345678901234567890121234
123456789012345678901234567890121234
8.6
Summary
123456789012345678901234567890121234
123456789012345678901234567890121234
8.7
Check Your Progress-Answers
123456789012345678901234567890121234
123456789012345678901234567890121234
8.8
Questions for Self - Study
123456789012345678901234567890121234
123456789012345678901234567890121234
8.9
Suggested Readings
123456789012345678901234567890121234
8.0 OBJECTIVES
Dear Friends,
After learning this chapter you will be able to
l
Explain difference between JavaScript and Java
l
Describe client server architecture
l
Study ASP,JSP and SSI
8.1 INTRODUCTION
JavaScript is an implementation of the ECMA (European Computer Manufacturers
Association) Script language standard and is typically used to enable programmatic
access to computational objects within a host environment. It can be characterized as a
prototype-based object-oriented scripting language that is dynamic, weakly typed and
has first-class functions.
JavaScript is primarily used in the form of client-side JavaScript, implemented as
part of a web browser in order to provide enhanced user interfaces and dynamic websites.
However, its use in applications outside web pages—for example in PDF-documents,
site-specific browsers and desktop widgets—is also significant.
JavaScript uses syntax influenced by that of C. JavaScript copies many names and
naming conventions from Java, but the two languages are otherwise unrelated and have
very different semantics. The key design principles within JavaScript are taken from the
self and Scheme programming languages.
8.2 WHAT IS JAVASCRIPT?
l
JavaScript was designed to add interactivity to HTML pages
l
JavaScript is a scripting language
l
A scripting language is a lightweight programming language
l
JavaScript is usually embedded directly into HTML pages
l
JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
l
Everyone can use JavaScript without purchasing a license
Introduction to JavaScript / 75
8.3 WHAT CAN A JAVASCRIPT DO?
l
JavaScript gives HTML designers a programming tool - HTML authors are normally
not programmers, but JavaScript is a scripting language with a very simple syntax!
Almost anyone can put small “snippets” of code into their HTML pages
l
JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: document.write(“<h1>” + name + “</h1>”) can write a variable text into an
HTML page
l
JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
l
JavaScript can read and write HTML elements - A JavaScript can read and change
the content of an HTML element
l
JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
l
JavaScript can be used to detect the visitor’s browser - A JavaScript can be used to
detect the visitor’s browser, and - depending on the browser - load another page
specifically designed for that browser
l
JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor’s computer
8.1,8.2,8.3 Check Your Progress
Fill in the blanks
1) JavaScript is an implementation of the ................ Script language
2) JavaScript is primarily used in the form of ................
3) JavaScript is a ................ language
4) JavaScript can be used to create session and ................
8.4 JAVASCRIPT AND JAVA
A common misconception is that JavaScript is similar or closely related to Java. It
is true that both have a C-like syntax, the C language being their most immediate common
ancestor language. They are both object-oriented, typically sandboxed (when used inside
a browser), and are widely used in client-side Web applications. In addition, JavaScript
was designed with Java’s syntax and standard library in mind. In particular, all Java
keywords were reserved in original JavaScript, JavaScript’s standard library follows Java’s
naming conventions, and JavaScript’s Math and Date objects are based on classes from
Java 8.0.
However, the similarities end there. Java has static typing; JavaScript’s typing is
dynamic (meaning a variable can hold an object of any type and cannot be restricted).
Java is loaded from compiled bytecode; JavaScript is loaded as human-readable source
code. Java’s objects are class-based; JavaScript’s are prototype-based. JavaScript also
has many functional features based on the Scheme language.
8.4.1 JavaScript Characteristics
JavaScript resembles Java and supports most of Java’s expression syntax. Some
other characteristics of JavaScript are...
8. JavaScript is interpreted, not compiled. Some programming languages must
be compiled or translated into machine code, before they can be executed.
JavaScript, on the other hand, is an interpreted language: the browser executes
Advanced Web Designing / 76
each line of script as it comes to it. JavaScript code is read line by line and acted
upon by the browser in a top-down manner.
2. JavaScript is case sensitive.
Any reference to a function or object in a JavaScript must match the case used to
define the function or object.
For example, a function named fieldBox1() must be referenced in the program as
fieldBox1() using the uppercase “B” in box.
8.4.2 JavaScript Comments
JavaScript comments can be used to make the code more readable. JavaScript
supports two types of comments:
l
A Single-line comment begins with two slashes (//) and ends at the end of the
Line.
l
A multiline-line comment begins with the /* delimiter and ends with */
delimiter .This type of comments can include any number of lines.
The following example uses single line comments to explain the code:
<script type=”text/JavaScript”>
// Write a heading
document.write(“<h1>This is a heading</h1>”);
// Write two paragraphs:
document.write(“<p>This is a paragraph.</p>”);
document.write(“<p>This is another paragraph.</p>”);
</script>
Multi line comments start with /* and end with */.
The following example uses a multi line comment to explain the code:
<script type=”text/JavaScript”>
/*
The code below will write
one heading and two paragraphs
*/
document.write(“<h1>This is a heading</h1>”);
document.write(“<p>This is a paragraph.</p>”);
document.write(“<p>This is another paragraph.</p>”);
</script>
8.4 Check Your Progress
True Or False
1)
2)
3)
4)
A common misconception is that JavaScript is similar or closely related to Java.
Java is loaded from compiled bytecode .
JavaScript is compiled not interpreted .
A Single-line comment begins with two slashes (//) and ends at
the end of the Line .
Introduction to JavaScript / 77
8.5 THE CLIENT SERVER ARCHITECTURE
The Internet revolves around the client-server architecture. Your computer runs
software called the client and it interacts with another software known as the server
located at a remote computer. The client is usually a browser such as Internet Explorer,
Netscape Navigator or Mozilla. Browsers interact with the server using a set of instructions
called protocols. These protocols help in the accurate transfer of data through requests
from a browser and responses from the server. There are many protocols available on the
Internet. The World Wide Web, which is a part of the Internet, brings all these protocols
under one roof. You can, thus, use HTTP, FTP, Telnet, email etc. from one platform - your
web browser.
Client-server architecture - Static HTML pages
The client (browser) requests for an HTML file stored on the remote machine through
the server software. The server locates this file and passes it to the client. The client then
displays this file on your machine. In this case, the HTML page is static. Static pages do
not change until the developer modifies them.
Client-server architecture - Server side scripting technologies
In this it involves dynamic response generated by the use of server side technologies.
There are many server side technologies today.
Active Server Pages (ASP): A Microsoft technology. ASP pages typically have the
extension .asp.
Advanced Web Designing / 78
Java Server Pages: .jsp pages contain Java code.
Server Side Includes (SSI): Involves the embedding of small code snippets inside the
HTML page. An SSI page typically has .shtml as its file extension.
With these server technologies it has become easier to maintain Web pages especially
helpful for a large web site. The developer needs to embed the server-side language code
inside the HTML page. This code is passed to the appropriate interpreter which processes
these instructions and generates the final HTML displayed by the browser. Note, the
embedded server-script code is not visible to the client (even if you check the source of
the page) as the server sends ONLY the HTML code.
8.5 Check Your Progress
Fill in the blanks
1) The Internet revolves around the ............server architecture
2) The ............is usually a browser such as Internet Explorer, Netscape Navigator or
Mozilla
3) A Microsoft technology. ASP pages typically have the extension ............
4) An SSI page typically has............as its file extension.
8.6 SUMMARY
A common misconception is that JavaScript is similar or closely related to Java. It
is true that both have a C-like syntax, the C language being their most immediate common
ancestor language. They are both object-oriented, typically sandboxed (when used inside
a browser), and are widely used in client-side Web applications. In addition, JavaScript
was designed with Java’s syntax and standard library in mind. In particular, all Java
keywords were reserved in original JavaScript, JavaScript’s standard library follows Java’s
naming conventions, and JavaScript’s Math and Date objects are based on classes from
Java 8.0.
The Internet revolves around the client-server architecture. Your computer runs
software called the client and it interacts with another software known as the server
located at a remote computer. The client is usually a browser such as Internet Explorer,
Netscape Navigator or Mozilla
With these server technologies it has become easier to maintain Web pages
especially helpful for a large web site. The developer needs to embed the server-side
language code inside the HTML page. This code is passed to the appropriate interpreter
which processes these instructions and generates the final HTML displayed by the browser.
Note, the embedded server-script code is not visible to the client (even if you check the
source of the page) as the server sends ONLY the HTML code
Source: www.princeton.edu (Link)
8.7 CHECK YOUR PROGRESS - ANSWERS
8.1, 8.2, 8.3
Fill In the blanks
1) ECMA
2) Client side
3) Scripting
4) Cookies
8.4
True or false
1) True
2) True
Introduction to JavaScript / 79
3) False
4) True
8.5
Fill In the blanks
1) Client
2) Client
3).asp
4).shtml
8.8 QUESTIONS FOR SELF - STUDY
1) What is the difference between Java and JavaScript?
2) What are the characteristics of JavaScript?
3) Differentiate between Client side and server side scripting
4) Write a short note on ASP and SSI.
8.9 SUGGESTED READINGS
1.
Html, Dhtml, Javascript, Perl CGI - By Ivan Bayross
2.
Pure JavaScript - Techmedia publication
3.
www.w3schools.com
4.
www.tizag.com
Advanced Web Designing / 80
³³³
NOTES
Introduction to JavaScript / 81
NOTES
Advanced Web Designing / 82
Chapter 9
Working with Variables and Data Types
12345678901234567890123456789012123456
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.0 Objectives
12345678901234567890123456789012123456
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.1 Data Types Available in JavaScript
12345678901234567890123456789012123456
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.2 Declare and Use Variables in Simple Programs
12345678901234567890123456789012123456
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.3 Use Data Declaration and Assignment Statements
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.4 Summary
12345678901234567890123456789012123456
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.5 Check Your Progress - Answers
12345678901234567890123456789012123456
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.6 Questions For Self - Study
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.7 Suggested Readings
12345678901234567890123456789012123456
12345678901234567890123456789012123456
9.0
OBJECTIVES
Dear Friends,
After learning this chapter you will be able to,
•
Explain Data types in JavaScript.
•
Describe Uses of document
•
Describe, Write read and data declaration.
9.1 INTRODUCTION TO DATA TYPES IN JAVASCRIPT
In this chapter, you will learn about the different data types supported by JavaScript and
how they are applied in programs.
JavaScript supports the following data types
Ø
Number :This consists of numbers both integers and floating-point.
Ø
String:This consists of text specified within single or double quotes.
Ø
Null : This is used to indicate that a variable is un-initialized.
Ø
Boolean :This consists of Boolean values true and false
As you proceed, you will understand the need for different data types and how are
used in programs.
Numeric data is composed of numbers. It may be whole or real and contain the following:
Ø
Numeric characters (0-9)
Ø
Decimal point
JavaScript supports Integer and Floating-Point values. Integers are numbers without any
decimal portion, that is they are whole number and do not contain fractions. Integers can
be positive or negative and the maximum integer size is dependent on the operating
system. Few examples for integers are 123, 5004, -121,etc.
Integers can be represented in following number system
Ø
Ø
Ø
Decimal
- Has 10 digits 0-9.
Hexadecimal - Has 16 values 0-15. 0-9 represents the
values 0-9 and letter A-Z for 10-16.
Octal
- It uses digits 0 to 7. Octal numbers have prefix 0.
Working with Variables and Data Types / 83
Number
Systems
Base
Decimal
10
Octal
Hex
8
16
Expressed as
Example
Sequence of digits without a
leading 0.
35, -63
Sequence of digits with a
leading 0.
0377, 0568
A leading 0x. (or 0X) indicates
hexadecimal.
0xABC
0X1234
Floating - Point numbers
These are used for representing fractions numbers with positives and negatives exponents.
Similar to integer values, Floating- Point values can also be positive or negative.
Consider the following example:
o –1210. 4
o 12e-2
o 5E-3
o 3e4
o –6e-2
o .43
Floating- point numbers can be used to storing information like.
o Average marks of a student
o Salary, commissions of an employee
o Cost of an item
o Square root of an number
o Weight of an object
You need to understand that every conditional statement evaluates to either TRUE or
FALSE
JavaScript supports pure Boolean data type and consists of two values true and false.
JavaScript automatically converts true to 1 and false to 0 whenever they are used in
numerical expressions as shown in the following example.
Ans=true*3+false*6
The above statement evaluates to Ans=1*3+0*6 because the Boolean value true is
automatically converted to 1 and the value false is converted to 0 when used in numerical
expressions. Therefore, the variable Ans contains the value 10.
String – Alphanumeric Data
Alphanumeric data is made up of any of the following characters:
Ø Numbera-0 to 9
Ø Alphabets-A to Z, a to z
Special Characters-#, $, * etc.
Note that mathematical operations cannot be performed on alphanumeric data.
Alphanumeric data in JavaScript is known as “String”, which is one or more characters
enclosed within single or double quotes. If a string begins with single quote it must end
with a double end with double quote.
Consider the following examples:
Example 1
s1 = ‘This is a sample string.’
s2 = “This is also a sample string.”
Where s1 and s2 are variables containing strings.
Advanced Web Designing / 84
The table given below lists the set of escape characters, which can be used within
<PRE> </PRE> tags for formatting text.
Character
Meaning
\’
\”
Single Quote
Double Quote
\\
\r
Backslash
Carriage Return
\f
\n
Form Feed
New Line
\b
\t
Backspace
Tab
9.2 DECLARING AND USING VARIABLES IN SIMPLE PROGRAMS
Declaring and Initializing Variables
In order to use a variable, it has to be declared and then assigned a value. Declaring a
variable informs JavaScript that a variable of the given name to be created and can be
used throughout the program. You can declare a variable using the var command in
JavaScript as shown below.
var sum;
This line declares a variable named sum, which currently has no value. The above
statement is known as a declaration statement. You can declare more than one variable
using a single declaration statement by separating each with a common as shown below.
var sum, avg, max, min;
How do you initiate variables?
2. Assign a value to a variable during declaration.
var name = “George”;
In the above code, the first statement declares a variable named name and assigns
the value “George” to it using the assignment operator (=).
2. Assigning a value to a variable after declaration.
var name;
name = “ George”;
document. Write (name);
In the above code, the first statement declares a variable named name, the second
statement assigns the value “George” to it using the assignment operator (=) and the
third statement displays the contents of the value of the variable name.
In JavaScript, the document.write statement is used for displaying some text on the
screen. The same statement can also be used to display the contents of a variable. For
example, consider the Program as shown below.
Program
<HTML>
<HEAD>
<TITLE> Example </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = “JavaScript”>
var temp1, temp2, temp3;
temp1 = 10;
temp2 = 20;
temp3 = temp1+temp2;
Working with Variables and Data Types / 85
document.write (“ temp3 =” );
document.write(temp3);
</SCRIPT>
</BODY>
</HTML>
Consider the following statements from the above code.
Var temp1, temp2, temp3; This statement declares the variables. The use of word
“var” is optional while declaring variable(s).
document.write (“temp3=”);
This statement displays the string temp3 = on the screen.
document.write(temp3);
This statement display the contents of the variable temp3 that is 30.
The output of the above program is shown in figure.
Result is:
Temp3=30
In the above figure the output temp3 = 30 is generated by two separate
document.write statements. Instead you can use a single document.write statement to
display the string (“temp3=”) and also the contents of the variable temp3 (30) as shown
below.
document.write (“temp3=”+temp3);
In this way, you can combine multiple strings of text into a single plus sign (+). Here (+)
is known as the concatenation operator. Some more examples on string concatenation
are given below:
Example 7
var age=16;
document.write (“Mark is”+ var +”years old “);
When the above code is executed, the following string “Mark is 16 years old” will be
displayed.
Consider the following code, which uses a single variable to store an integer value, a
floating-point value and a string value.
Program
<HTML>
<HEAD>
<TITLE> Example </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE =” JavaScript”>
var test_var =10;
document.write (“value of test_var : “ + test_var);
document.write (“<BR>”);
test_var=”This is a sample string”;
document.write (“value of test_var “ + test_var);
document.write (“<BR>”);
</SCRIPT>
</BODY>
</HTML>
Advanced Web Designing / 86
The output of the program is as shown in the figure.
Result:Value of test_var:10
Value of test_var: This is a sample string
9.3 USE DATA DECLARATION AND ASSIGNMENT STATEMENTS
Assignment Operator
Consider the following program code
Program
<HTML>
<HEAD>
<TITLE> Example </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JAVASCRIPT”>
var a=10;
a=a+1;
document.write (“The value of the variable a is”);
document.write (a);
</SCRIPT>
</BODY>
</HTML>
When the above program is executed, the following output will be obtained:
Result:
The value of variable a is 11
In the above example, you can notice that the value of the variable a is incremented by 1
using the assignment operator. The statement a=a+1 can be re-written in the following
ways.
a+=1
This is a compound assignment operator
a++
This is known as unary increment operator and can be whenever the contents
of a variable has to be increased by a value 1.
++ is known as unary increment operator and - - is known unary decrement
operator.
Consider the following program.
Program
<HTML>
<HEAD>
<TITLE> Example </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JAVASCRIPT”>
var a=10;
a=-a - -;
document.write (“The value of variable a is”);
document.write (a);
</SCRIPT>
</BODY>
</HTML>
When the above example is executed, the following output will be obtained.
Result : The value of variable a is 9.
Working with Variables and Data Types / 87
The only difference between unary and decrement operator is that increment operator will
increase the value by 1, whereas the decrement operator will reduce the value by 1.
Program
<HTML>
<HEAD>
<TITLE> Example </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JAVASCRIPT”>
var a =10
document.write (a++); /*a is displayed 10 then it is incremented 11*/
document.write (“<BR>”);
document.write (++a); /* a is incremented 12 then it is displayed 12*/
document.write (a- -); /*a is displayed 12 then it is decremented 11*/
document.write (“<BR>”);
document.write (- -a); /* a is decremented 10, then it is displayed (10) */
</SCRIPT>
</BODY>
</HTML>
The output of the above code is shown in figure
Result:
10
12
12
10
What is the output of the following code?
var a=10;document.write (—a);document.write (++a);document.write
(a++);document.write(a—);document.write (a++);
Program: The following code shows how strings can be concatenated using the “+”
operator
<HTML>
<HEAD>
<TITLE> Example </TITLE>
</HEAD>
<BODY>
<H1 ALIGN =” CENTER”> Working with Strings </H1>
<HR>
<SCRIPT LANGUAGE=”JAVASCRIPT”>
document.write (“<BR>”)
var str1, str2, str3;
str1= “Hello”;
str2= “World”;
str3= str1+str2;document.write (“str1= “+ str1 + “<BR>”);
document.write (“str2=” + str2 +” <BR>”);
document.write (“str1” + “+” + “str2” + “= “ + str3+” <BR>”);
document.write (str1 + “+ “ + str2 + “=” + ( str1+str2) );
</SCRIPT>
</BODY>
</HTML>
The output of program is as shown in the figure
Result:
Str1=Hello
Str2=World
Str1+str2=HelloWorld
Hello+World=HelloWorld
Advanced Web Designing / 88
Program: The program given below explains how arithmetic and assignment operators
work in JavaScript.
<HTML>
<HEAD>
<TITLE> Arithmetic and Compound Assignment Operators </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = “JavaScript”>
var A=50, B=10;
document.write (“<PRE>”);
document.write (“<BR>”+”<CENTER>”+”<U>”+”Arithmetic and Compound
Assignment Operators”+”</U>”+”</CENTER>”)
document.write (“<BR>”+A+”+”+B+”\t\t=\t”)
document.write (A+B)
document.write (“<BR>”+A+”+=”+B+”\T\T=\T”)
document.write(A+=B)
document.write (“</PRE>”)
</SCRIPT>
</BODY>
</HTML>
Result : Arithmetic and Compound
Assignment Operators
50 + 10 = 60
50 + = 10 = 60
The above program uses two variables A, B and performs addition using simple arithmetic
and compound assignment operator.
9.1,9.2,9.3 Check your Progress
Fill in the blank
1. Numeric data is composed of ....................
2. JavaScript supports ..................... and ................ values.
10. Alphanumeric data in JavaScript is known as .................
4. JavaScript supports pure Boolean data type and consists of two values ......... and
...................
9.4 SUMMARY
Steps involved in solving a problem are studying the problem in detail, gathering the
relevant information, processing the information and arriving at the results. looping is
used to excute one or more steps repeatedly.
Source: www.princeton.edu (Link)
9.5 CHECK YOUR PROGRESS - ANSWERS
1. Numbers 2 .Integer and Floating point 10. String. 4. True and False.
9.6 QUESTIONS FOR SELF - STUDY
1. What are the various data types available in JavaScript ?
2. List out various operators in JavaScript.
9.7 SUGGESTED READINGS
1. Html, Dhtml, Javascript, Perl CGI - By Ivan Bayross
2. Pure JavaScript - Techmedia publication
10. www.w3schools.com
4. www.tizag.com
³³³
Working with Variables and Data Types / 89
NOTES
Advanced Web Designing / 90
Chapter 10
Controlling Programme Flow and do…while
Statement
12345678901234567890123456789012123
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 0 Objectives
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 1 Introduction
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 2 For Loop
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 3 If Condition
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 4 While Loop
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 5 Switch Case
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 6 Summary
12345678901234567890123456789012123
10. 7 Check Your Progress−Answers
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 8 Questions For Self - Study
12345678901234567890123456789012123
12345678901234567890123456789012123
10. 9 Suggested Readings
12345678901234567890123456789012123
12345678901234567890123456789012123
12345678901234567890123456789012123
10.0 OBJECTIVES
Dear Friends,
After learning this chapter you will be able to,
• Explain For Loops in JavaScript.
• Describe Conditional Statements.
• Study of Switch cases in JavaScript.
10.1 INTRODUCTION
Normally, statements in a JavaScript script are executed one after the other, in the
order in which they are written. This is called sequential execution, and is the default
direction of program flow.
An alternative to sequential execution transfers the program flow to another part of
your script. That is, instead of executing the next statement in the sequence, another
statement is executed instead.
10.2 FOR LOOP
Document.write (A+B); document.write(“Here a semicolon must be used,since a
JavaScript statement is being continued on the same line”);
Consider the following example to illustrate the use of the for loop in JavaScript.
Program
<HTML>
<HEAD>
<TITLE> for loop Sample Program </TITLE>
</HEAD>
<H1> <Center> for loop Sample Program </Center></H1>
<HR>
<BODY>
<SCRIPT LANGUAGE =”JavaScript”>
for (i=1; i<=10; i++)
{
document.write (“The value of i is” +i+” <BR>”);
}
</SCRIPT>
</BODY>
</HTML>
The above code displays the value of I from 1 through 3. The sequence of steps can be
depicted as follows:
1) The variable i is initialized to “1” for the first time.
Controlling Programme Flow and do…while Statement / 91
2) The for loop checks if value of the variable i is less than or equal to 10.
3) If step2 evaluates to true, then the statement within the loop gets executed.
4) The value of the variable i is incremented by 1.
5) Step2 to Step4 are repeated, till the condition of the for loop evaluates to true.
6) Once the condition evaluates to false, the execution of the for loop is terminated.
The output of the code is given in figure
Result :
The value
The value
The value
The value
The value
The value
The value
The value
The value
The value
of
of
of
of
of
of
of
of
of
of
I
I
I
I
I
I
I
I
I
I
is
is
is
is
is
is
is
is
is
is
1
2
3
4
5
6
7
8
9
10
10.3 IF CONDITION
Program: The program given below accepts two numbers from the user and prints the
greater number.
<HTML>
<HEAD>
<TITLE> Greater of two numbers </TITLE>
</HEAD>
<BODY>
<H1 ALIGN = “CENTER”> Greater of two numbers <H1>
<SCRIPT LANGUAGE = “ JavaScript”>
var num1=0, num2=0;
num1=prompt(“Number 1”,“Enter the value for num1”);num2=prompt(“Number 2”, “Enter
the value for num2”);
if (num1>num2)
{
document.write (“num1 is greater than num2”);
}
else
{
document.write (“num2 is greater than num1”);
}
</SCRIPT>
</BODY>
</HTML>
Two numbers num1 and num2 are declared and initialized with 0. The prompt function is
used to accept a value from the user. The syntax is:
Myvariable = prompt (“User Input”, “Enter the value”);
Enter the value for num1 10
Enter the value for num2 20
Result:
Num2 is greater than num 1
Program: The following program calculates the percentage of discount based upon the
purchase amount. Percentage is calculated based on the following conditions.
Range (In Dollars)
Discount (In %)
100-300
10
300-700
15
700-100
20
>1000
25
Advanced Web Designing / 92
<HTML>
<HEAD>
<TITLE> Logical and Comparison Operator </TITLE>
</HEAD>
<BODY>
<H1 ALIGN=”CENTER”> Logical and Comparison Operators </H1>
<HR>
<PRE>
<SCRIPT LANGUAGE = “ JavaScript”>
var amt=0, discount=0;
amt= prompt (“ Purchase Amount”, “Enter the purchase amount”);
if (amt<100)
{
document.write (“\n sorry no discount”);
}
if ((amt>=100) && (amt<=300))
{
discount=10;
}
if ((amt>300) && (amt<=700))
{
discount=15;
}
if ((amt>700) && (amt <=1000))
{
discoumt=20;
}
if (amt>1000)
{
discount=25;
}
amt=amt –((amt*discount)/100);
if (discount>0)
{
document.write (“\n Discount %=”+ discount +” %");
}
document.write (“\n The amount to be paid : “+ amt);
</SCRIPT>
</PRE>
</BODY>
</HTML>
In the above code first the amount is accepted from the user using the prompt statement.
The value is then compared with 100 using the if conditional statement. If the value is
less than 100, then the following message will be displayed:
document.write (“\n Sorry no discount”);
document.write (“\n The amount to be paid: “+ amt);
The output of the browser, after entering the value is as shown in the figure.
Result: Enter the purchase amount 150
Discount %=10%
The amount to be paid :135
Program: The following program calculates the sum of the numbers 10 through 20
using for statement.
<HTML>
<HEAD>
<TITLE> The for loop </TITLE>
</HEAD>
Controlling Programme Flow and do…while Statement / 93
<BODY>
<H1 ALIGN = “CENTER”> The for loop </H1>
<HR>
<SCRIPT LANGUAGE =” JavaScript”>
var i, sum=0;
for (i=10; i<=20; i++)
{
sum += i;
}
document.write (“The sum is “ + sum);
</SCRIPT>
</BODY>
</HTML>
In the above code, two variables i and sum are declared. The variable I is used to keep
track of the number of times the for loop is executed and the variable sum is used to
store the sum of all the numbers ranging between 10 and 20 is initialized by 0.
The output in the browser is as shown in the figure.
Result:
The sum is 165
Program: The following program uses the for loop and if statement to print all even and
odd numbers between 1 and 19.
<HTML>
<HEAD>
<TITLE>Even and Odd numbers </TITLE>
</HEAD>
<BODY>
<H1 ALIGN= “CENTER”> Even and Odd numbers <H1>
<HR>
<PRE>
<SCRIPT LANGUAGE=”JavaScript”>
document.write (“Even\t\tOdd”);
document.write (“BR>”);
var i;
for (i=1; i<=12; i++)
{
if ((i%2)==0)
{
document.write (i);
document.write (“<BR>”);
}
else
{
document.write (“\t\t”+ I);
document.write (“<BR>”);
}
}
</SCRIPT>
</PRE>
</BODY>
</HTML>
The for loop is used to generates numbers between 1 and 19. Every number that is
generated is divided by 9. Since the modulus operator is used, the remainder of the
division is obtained. If the remainder the division is 0, then it is printed in the Even column
else it is printed in Odd column.
Advanced Web Designing / 94
The output in the browser is as shown in the figure.
Result: Even and Odd numbers
Even
2
4
6
8
10
12
Odd
1
3
5
7
9
11
Program: The following program accepts n numbers from the user and finds the maximum
of the n numbers.
<HTML>
<HEAD>
<TITLE> Maximum of n number </TITLE>
</HEAD>
<BODY>
<H1 ALIGN =”CENTER”> Maximum of n numbers </H1>
<SCRIPT LANGUAGE=”JavaScript”>
var i= 0, n=0, num=0, max=0;
n=parseInt (prompt(“How many numbers?”,”));
for (i=0; i<n; i++)
{
num=parseInt(prompt(“Number”,”Enter the value for number”));
if (num>max)
{
max=num;
}
}
document.write (“The maximum value is “ +max);
</SCRIPT>
</BODY>
</HTML>
Four variables I, n, num, max are declared and all of them are initialized to 0. First the
total number of elements among which the maximum is to be evaluated is accepted from
the user.
The output in the browser will be as shown in the figure.
Result:
Maximum of n numbers
How many numbers? 3
Enter the value for number 10
Enter the value for number 50
Enter the value for number 30
The maximum value is 50
10.4 WHILE LOOPS
Program:
<HTML>
<HEAD>
<TITLE> while loop sample program </TITLE>
</HEAD>
<BODY>
<H1 ALIGN="CENTER"> While loop sample program </H1>
Controlling Programme Flow and do…while Statement / 95
<SCRIPT LANGUAGE="JavaScript">
var I=1;
while (i<=10)
{
document.write (<<\n>>);
document.write (<<The value of i is>> + i+<< <BR>>>);
i++;
}
</SCRIPT>
</BODY>
</HTML>
The output of program is shown in figure
Result:
While Loop Sample Program
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
The value of i is 6
The value of i is 7
The value of i is 8
The value of i is 9
The value of i is 10
In this program the variable i is initialized to 1. This is because the value of
the variable i is tested in the while loop and if it is not initialized before use
then it would cause a run time error.
10. 5 SWITCH -CASE STATEMENT
The program is given below lists 3 options from which the user has to
choose one. It then displays a suitable message on the screen using the
switch-case statement, depending on the user's choice. If the user enters
any option other than existing ones, it displays the message "You have chosen
a wrong value on the screen.
The program given below shows the usage of the 'switch-case' statement
with a do- while loop.
Program:
<HTML>
<HEAD>
<TITLE>switch-case </TITLE>
</HEAD>
<H1 ALIGN ="CENTER"> Switch-Case within loop </H1>
<SCRIPT LANGUAGE="JavaScript">
var num1=0, ans="n";
do{
Advanced Web Designing / 96
document.write ("<BR>");
document.write ("1. Rectangle" +" <BR>"); document.write ("9. Circle" +"
<BR>"); document.write ("10. Square" +"<BR>"); document.write ("<BR>");
num1= parsInt (prompt ("option 1","choose one of the options"));
switch (num1)
{
case 1:
document.write ("You have chosen Rectangle");
break;
case 2:
document.write ("You have chosen Circle");
break;
case3:
document.write ("You have chosen Square");
break;
default:
document.write ("You have chosen wrong value");
}
ans=prompt ("Answer", "Do You Want To Continue");
}
while (ans=="Y" | | ans=="Y");</SCRIPT></BODY></HTML>
The program is modified, to repeat the same process until the user wishes
to continue. The output in the browser is as shown in the figure.
In the above example, three options Rectangle, Circle, Square are listed
and the user is prompted for a selection. The user enters 1,2,3 to select the
respective options. The switch statement then compares the option entered
by the user to display a message. If the user enters an option that does not
exist an error message is displayed.
The output in the browser is as shown in the figure.
Result:
Switch-Case within Loop
1.Rectangle
2.Circle
3. Square
When user enters 1
You have chosen Rectangle
1.Rectangle
2.Circle
3. Square
When user enters 2
You have chosen Circle
Program: The contents of the string stored in an array can be reversed
using the Reverse function. We shall learn how to incorporate this function
in this section.
<HTML>
Controlling Programme Flow and do…while Statement / 97
<HEAD>
<TITLE> Using Functions </TITLE>
</HEAD>
<H1 ALIGN="CENTER"> Using Functions </H1>
<HR>
<PRE>
<SCRIPT LANGUAGE="JavaScript">
str= new Array ('MadaM');
if (str==str. Reverse( ) )
document.write ("The string is a Palindrome");
else
document.write ("The String is not a Palindrome");
</SCRIPT>
</BODY>
</HTML>
Str is a variable that is declared as an array and is initialize with a value
'MadaM'. To check if the string in the array is a Palindrome, the string is
reversed using the function reverse( ). The original string and the reversed
string are compared and as appropriate message is displayed in the browser.
The output in the browser is as shown in the figure.
Result:
Using Functions
The String is a Palindrome
Program: The following example uses a function to add two numbers passed
as parameters to it displays the result.
<HTML>
<HEAD>
<TITLE> Sum Function </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function Sum (num1, num2)
{
var ans= num1+ num2; document.write ("The sum is " + ans");
}
</SCRIPT>
</HEAD>
<BODY>
<H1 ALIGN=" CENTER"> Function to add two numbers </H1>
<SCRIPT LANGUAGE="JavaScript"> Sum (1,2)
</SCRIPT>
</BODY>
</HTML>
The function Sum is defined in the head section and two numbers num1,
num2 to calculate the sum. This function is invoked from the body section
by passing values 1 and 2. If you need to calculate the sum of three numbers,
then you need to write a function, which accepts three arguments. This
becomes tedious because you have to write separate functions to calculate
the sum of two, three, four numbers and so on.
The output of the program will be "The sum is 3".
Advanced Web Designing / 98
Result:
Function to add two numbers
The sum is 3
Program: Consider the following example, which uses a single function to
calculate the sum of two or more numbers.
<HTML>
<HEAD>
<TITLE> Sum Function </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function Sum ( )
{
var len= Sum.arguments.length;
var ans=0;
for (I=0; I<len; I++)
{
ans += Sum.arguments (i);
}
document.write ("The sum is" + ans);
document.write ("<BR>");
}
</SCRIPT>
</HEAD>
<BODY>
<H1 ALIGN="CENTER"> Function to add two or more numbers</H1>
<SCRIPT LANGUAGE="JavaScript"> Sum (10, 20);
Sum (10, 20, 30);
Sum (10, 20, 30, 40);
</SCRIPT>
</BODY>
</HTML>
THE FUNCTION Sum can be used to calculate the sum of two or more
numbers. In the body section, you must have noticed that the function Sum
is called three times with two, three and four arguments respectively. In the
function definition the variable len is assigned the length of the
Sum.arguments array and the variables ans is used to add the elements of
Sum.arguments array.
The values of the arguments array and the length attribute for different function
calls is given below,
1) Function call- Sum (10, 20) Sum.arguments.length=2
Sum.arguments [0]= 10
Sum.arguments [1]= 20
2) Function Call- Sum (10, 20, 30) Sum.arguments.length=3
Sum.arguments [0]= 10
Sum.arguments [1]= 20
Sum.arguments [2]= 30
3) Function Call- Sum (10, 20, 30, 40) Sum.arguments.length=4
Sum.arguments [0]= 10
Sum.arguments [1]= 20
Controlling Programme Flow and do…while Statement / 99
Sum.arguments [2]= 30
Sum.arguments [3]= 40
The output of the above program is given below in figure.
Result:
Function to add two or more numbers
The sum is 30
The sum is 60
The sum is 100
Program:
<HTML>
<HEAD>
<TITLE> The Function object </TITLE>
<SCRIPT LANGUAGE="JavaScript">
func= new function ("x", "y", "oper", "var ans=0; return ans");
switch (oper)
{
case '+':
ans=x+y;
break;
case '-':
ans=x-y; break;
case '*':
ans=x*y; break;
case '/':
ans=x/y;
break;
default:
return 0;
}
</SCRIPT>
<BODY>
<SCRIPT LANGUAGE= "JavaScript">
s1= func (10, 2, "+"); s2= func (10, 2, "-"); s3= func (10, 2, "*"); s4= func (10,
2, "/"); s5= func (10, 2, "&");
document.write ("<PRE>"); document.write ("10+2 \t= \t"); document.write
(s1+ "\n"); document.write ("10-2 \t= \t"); document.write (s2- "\n");
document.write ("10*2 \t= \t"); document.write (s3* "\n");
document.write ("10/2 \t= \t");
document.write (s4/ "\n");
document.write ("10&2 \t= \t");
document.write (s5& "\n");
document.write ("<PRE>");
</SCRIPT>
</BODY>
</HTML>
Run this program and check the output as an exercise.
Function to add two or more numbers
The sum is 30
The sum is 60
The sum is 100
Advanced Web Designing / 100
10.1,10.2,10.3,10.4 Check your Progress
Fill in the blank
1. The .......... statement is used to terminate the loop in the middle of the execution.
2. The continue statement is used to ............. the execution of loop.
3. The ............ case statement is normally used to make a selection from multiple
choices.
4. The ............. loops is variables loop that is executed as long as a condition is true.
10. 6
SUMMARY
The while statement is another looping structure in JavaScript language and is used to
execute a set of statements while a certain condition is true .The break statement is
used to exit from a loop and transfers the control to the statement after the loop .When
a break statement is encountered in a loop , the loop is terminated and the control of the
program is transferred to the statement. The continue statement is same as that of the
break statement but it does not terminate the loop .
10.7 CHECK YOUR PROGRESS-ANSWERS
10. 1,10. 2,10. 3,10. 4
Fill in the blanks
1. Break .
2. Resume.
3. Switch.
4. While.
10.8 QUESTIONS FOR SELF - STUDY
1. Write short notes on
a) Loops in JavaScript.
b) Switch case statements.
2. Write a function to add 2 numbers.
3. Write a program to calculate reverse a string.
10.9 SUGGESTED READINGS
1.
Html, Dhtml, Javascript, Perl CGI - By Ivan Bayross
2.
Pure JavaScript - Techmedia publication
3.
www.w3schools.com
4.
www.tizag.com
³³³
Controlling Programme Flow and do…while Statement / 101
NOTES
Advanced Web Designing / 102
Chapter 11
The JavaScript Object Model
1234567890123456789012345678901212345
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.0 Objectives
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.1 Introduction
1234567890123456789012345678901212345
11.2 The Java Script Commonly Used Objects
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.3 Window object
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.4 The WITH Statement
1234567890123456789012345678901212345
11.5 DOM Document Object
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.6 The Image Object
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.7 The history Object
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.8 The location Object
1234567890123456789012345678901212345
11.9 The Navigator Object
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.10 Summary
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.11 Check Your Progress-Answers
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.12 Questions for Self Study
1234567890123456789012345678901212345
11.13 Suggested Readings
1234567890123456789012345678901212345
1234567890123456789012345678901212345
11.0 OBJECTIVES
Dear friends,
After learning this chapter you can
l
Explain the concept JavaScript object model
l
Understand Language Objects provided by the language
l
Navigator Objects provided by the client browser
11.1 INTRODUCTION
Many JavaScript objects are contained within each other. JavaScript objects have a
container to contained object relationship rather than a class and subclass relationship.
Properties are not inherited from one type of object to another. There are two main types
of JavaScript objects.
l
Language Objects - Objects provided by the language and are not dependent
on other objects.
l
Navigator - Objects provided by the client browser. These objects are all sub
objects to the navigator object.
Fig.11.1 JavaScript’s DOM
The JavaScript Object Model / 103
11.2 The Java Script Commonly Used Objects:
Object
Properties
Methods
Event Handlers
Window
defaultStatus,frames,opener,
parent,scroll,self,status,top,
window
alert,blur,close,confirmfocus,
open,promptclearTimeoutset
Timeout
onLoad,onUnload
onBlur,onFocus
Location
Hash,host,hostname,href,
pathname,protocol,search,
reload(),replace()
none
History
Length,forward,go
back
none
Navigator appCodeNameappName,
appVersionmimeTypes,
pluginsuserAgent
javaEnabled
none
document alinkColor,anchors,applets,
area,bgColorcookie,fgColor,
forms,images,lastModified,
linkColor,links,location,
referrer, title,vlinkColor
Clear,close,open,write,writeln
none
image
Border,complete,height,
hspace,lowsrc,name,src,
vspace,width
none
none
form
Action,elements,encoding,
FileUpload,method,name,
target
submit
reset
onSubmit
onReset
11.1 - 11.2 Check Your Progress
True or false
1) JavaScript objects have a container to contained object relationship
rather than a class and subclass relationship
2) Navigator - Objects provided by the client browser
11.3 WINDOW OBJECT
The window object represents an open window in a browser.
If a document contain frames (<frame> or <iframe> tags), the browser creates one
window object for the HTML document, and one additional window object for each
frame.
11.3.1 Window Object Properties
Property
closed
defaultStatus
document
frames
history
innerHeight
innerWidth
length
location
name
navigator
opener
outerHeight
outerWidth
pageXOffset
pageYOffset
Description
Returns a Boolean value indicating whether a window has been closed or not
Sets or returns the default text in the statusbar of a window
Returns the Document object for the window
Returns an array of all the frames (including iframes) in the current window
Returns the History object for the window
Sets or returns the the inner height of a window’s content area
Sets or returns the the inner width of a window’s content area
Returns the number of frames (including iframes) in a window
Returns the Location object for the window
Sets or returns the name of a window
Returns the Navigator object for the window
Returns a reference to the window that created the window
Sets or returns the outer height of a window, including toolbars/scrollbars
Sets or returns the outer width of a window, including toolbars/scrollbars
Returns the pixels the current document has been scrolled (horizontally)
from the upper left corner of the window
Returns the pixels the current document has been scrolled (vertically) from
the upper left corner of the window
Advanced Web Designing / 104
parent
screen
screenLeft
screenTop
screenX
screenY
self
status
top
Returns the parent window of the current window
Returns the Screen object for the window
Returns the x coordinate of the window relative to the screen
Returns the y coordinate of the window relative to the screen
Returns the x coordinate of the window relative to the screen
Returns the y coordinate of the window relative to the screen
Returns the current window
Sets the text in the statusbar of a window
Returns the topmost browser window
11.3.2 Window Object Methods
Method
alert()
blur()
clearInterval()
clearTimeout()
close()
confirm()
createPopup()
focus()
moveBy()
moveTo()
open()
print()
prompt()
resizeBy()
resizeTo()
scrollBy()
scrollTo()
setInterval()
setTimeout()
Description
Displays an alert box with a message and an OK button
Removes focus from the current window
Clears a timer set with setInterval()
Clears a timer set with setTimeout()
Closes the current window
Displays a dialog box with a message and an OK and a Cancel button
Creates a pop-up window
Sets focus to the current window
Moves a window relative to its current position
Moves a window to the specified position
Opens a new browser window
Prints the content of the current window
Displays a dialog box that prompts the visitor for input
Resizes the window by the specified pixels
Resizes the window to the specified width and height
Scrolls the content by the specified number of pixels
Scrolls the content to the specified coordinates
Calls a function or evaluates an expression at specified intervals (in milliseconds)
Calls a function or evaluates an expression after a specified number of milliseconds
11.3 Check your progress
Fill in the blanks
1) ............ method, Removes focus from the current window.
2)............ method, Opens a new browser window.
3) ............method, Scrolls the content to the specified coordinates .
4)............property, Returns the Location object for the window
11.4 THE WITH STATEMENT
The with keyword specifies an object, and it is followed by a set of statements
enclosed in braces. For each statement in the set, any properties you mention without
specifying an object are assumed to be for that object
The “with” keyword is used to specify an object to which all of the unreferenced
properties and methods in a following block of code are to be applied.
example:
Instead of coding
var x = document.body.scrollLeft;
document.write(‘text1’);
document.write(‘text2’);
The JavaScript Object Model / 105
document.write(‘text3’);
you could use
with document {
var x = body.scrollLeft;
write(‘text1’);
write(‘text2’);
write(‘text3’);
}
11.5 DOM DOCUMENT OBJECT
JavaScript enabled browsers are capable of recognizing individual objects in an
HTML page, after the page has been rendered in the browser, because the JavaScript
browser recognizes and uses the Document Object Model (i.e. DOM)
Using the DOM, JavaScript enabled browser identify the collection of webpage
objects(web page elements) that have to be dealt with while rendering an HTML based,
web page in the browser window.
The HTML object( the collection of webpage elements) which belong to the DOM,
have a descending relationship with each other
The topmost object in DOM is the Navigator itself. The next level in DOM is the
browser’s window. The next level in DOM is Document displayed in the window.
DOM hierarchy continues downward to encompass individual elements on FORM,
such as text boxes, Labels, Radio Buttons, Check Boxes, Push Buttons and so on.
JavaScript object hierarchy is mapped to the DOM, which in turn is mapped to the
web page elements in the browser window. Hence a webpage is rendered in a JavaScript
enebled browser window, JavaScript apable of uniquely identifying each element in the
web page, because major elements of the web page around the DOM
Each HTML document loaded into a browser window becomes a Document object.
The Document object provides access to all HTML elements in a page, from within
a script.
The Document object is also part of the Window object, and can be accessed
through the window.document property.
The DOM contains objects that you can use to access features in a browser and
elements in a Web page.
The DOM has a hierarchical structure that is similar to a family tree and is made up
of “parent” and “child” objects.
Understanding the hierarchical structure of the DOM helps you know how to access
the appropriate child objects and makes writing scripts easier.
In script, you need to separate objects in the hierarchical structure with a period (.)
11.5.1 Document Object Collections
Collection
Description
anchors[]
Returns an array of all the anchors in the document
forms[]
Returns an array of all the forms in the document
images[]
Returns an array of all the images in the document
links[]
Returns an array of all the links in the document
Advanced Web Designing / 106
11.5.2 Document Object Properties
Property
Description
cookie
Returns all name/value pairs of cookies in the document
domain
Returns the domain name of the server that loaded the
document
lastModified Returns the date and time the document was last
modified
readyState
Returns the (loading) status of the document
referrer
Returns the URL of the document that loaded the
current document
title
Sets or returns the title of the document
URL
Returns the full URL of the document
11.5.3 Document Object Methods
Method
Description
close()
Closes the output stream previously
opened with document.open()
getElementById()
Accesses the first element with the
specified id
getElementsByName()
Accesses all elements with a specified
name
getElementsByTagName()
Accesses all elements with a specified
tagname
open()
Opens an output stream to collect the
output from document.write() or
document.writeln()
write()
Writes HTML expressions or
JavaScript code to a document
writeln()
Same as write(), but adds a newline
character after each statement
JavaScript can access the method of all objects belonging to the DOM and JSSS
DOM. Hence using JavaScript, truly interactive web pages can be created
11.4 and 11.5 Check you progress
True or false
1) JavaScript object hierarchy is mapped to the DOM
2) JavaScript cannot access the method of all objects belonging to the DOM and
JSSS DOM
3) The topmost object in DOM is the Navigator itself
4) The DOM contains objects that you can use to access features in a browser and
elements in a Web page
11.6 THE IMAGE OBJECT
The JavaScript Image Object is a property of the document object.The Image object
represents an embedded image. For each <img> tag in an HTML document, an Image
object is created.
The JavaScript Object Model / 107
11.6.1 Image Object Properties
Property
Description
align
Sets or returns the value of the align attribute of an image
alt
Sets or returns the value of the alt attribute of an image
border
Sets or returns the value of the border attribute of an image
complete
Returns whether or not the browser is finished loading an image
height
Sets or returns the value of the height attribute of an image
hspace
Sets or returns the value of the hspace attribute of an image
longDesc
Sets or returns the value of the longdesc attribute of an image
lowsrc
Sets or returns a URL to a low-resolution version of an image
name
Sets or returns the name of an image
src
Sets or returns the value of the src attribute of an image
useMap
Sets or returns the value of the usemap attribute of an image
vspace
Sets or returns the value of the vspace attribute of an image
width
Sets or returns the value of the width attribute of an image
11.6.2 Image Object Events
Event
The event occurs when...
onabort
Loading of an image is interrupted
onerror
An error occurs when loading an image
onload
An image is finished loading
11.7 The history Object
The history object contains the URLs visited by the user (within a browser window).
JavaScript History Object provides the function to get the browser history information
for the current browser window opened by the visitor. JavaScript history object returns the
previously visited web pages by the visitor for the current window of web browser initiated
with single browser session. History object of JavaScript consists of 1 property and 3
methods that return the value corresponding to the single browser window currently used
by the client. JavaScript runtime engine creates the history object that stores the list of
URLs in the form of array visited by the user in single browser window.History Object
11.7.1 The history Object Properties
Property
length
Description
Returns the number of URLs in the history list
11.7.2 History Object Methods
Method
Description
back()
forward()
go()
Loads the previous URL in the history list
Loads the next URL in the history list
Loads a specific URL from the history list
Advanced Web Designing / 108
11.6 - 11.7 Fill in the blanks
1) The JavaScript ...........Object is a property of the document object.(ans: Image)
2)............Sets or returns the value of the align attribute of an image (ans: align
property )
3) JavaScript ...........Object provides the function to get the browser history
information (ans: History)
4) JavaScript runtime engine creates the history object that stores the list of URLs in
the form of ..............
(ans: array )
11.8 THE LOCATION OBJECT
The location object is the property of the windows object. It contains information
about the current URL being displayed by the window. IT has the set of property to hold
the different components of the URL, but no method
The location object contains information about the current URL.
The location object is part of the window object and is accessed through the
window.location property.
11.8.1 Location Object Properties
Property
Hash
Host
hostname
Href
pathname
Port
protocol
search
Description
Returns the anchor portion of a URL
Returns the hostname and port of a URL
Returns the hostname of a URL
Returns the entire URL
Returns the path name of a URL
Returns the port number the server uses for a URL
Returns the protocol of a URL
Returns the query portion of a URL
11.8.2 Location Object Methods
Method
assign()
reload()
replace()
Description
Loads a new document
Reloads the current document
Replaces the current document with a new one
11.9 THE NAVIGATOR OBJECT
The navigator object is a special object that stores information about the version of
the browser. This is Netscape specific tag, and it may or may not be implemented in
other browser.
Navigator object doesn’t technically qualify as a built-in object, because it represents
a physical entity
Navigator object that contains information about the web browser as a whole, such
as the version and a list of the data formats it can display. All the properties are read-only
and can not be dynamically changed. The Navigator object is named after Netscape
Navigator, but it is also supported by Internet Explorer. The Navigator object represents
the particular browser and allows script functions to access information about the browser
being used to access the document.
The JavaScript Object Model / 109
11.9.1 Navigator Object Properties
Property
Description
appCodeName
Returns the code name of the browser
appName
Returns the name of the browser
appVersion
Returns the version information of the browser
cookieEnabled
Determines whether cookies are enabled in the browser
platform
Returns for which platform the browser is compiled
userAgent
Returns the user-agent header sent by the browser
to the server
11.9.2 Navigator Object Methods
Method
Description
javaEnabled()
Specifies whether or not the browser has Java enabled
taintEnabled()
Specifies whether or not the browser has data
tainting enabled
11.8 - 11.9 Check your Progress
True or false
1) The navigator object is a special object that stores information about the version
of the browser
2) Navigator object that contains information about the web browser as a whole
3) The Navigator object represents the particular browser and allows script functions
11.10 SUMMARY
There are two main types of JavaScript objects.
o
Language Objects - Objects provided by the language and are not dependent on
other objects.
o
Navigator - Objects provided by the client browser. These objects are all sub objects
to the navigator object
The topmost object in DOM is the Navigator itself. The next level in DOM is the
browser's window. The next level in DOM is Document displayed in the window.
DOM hierarchy continues downward to encompass individual elements on FORM,
such as text boxes, Labels, Radio Buttons, Check Boxes, Push Buttons and so on.
Navigator object that contains information about the web browser as a whole, such
as the version and a list of the data formats it can displayed. The window object represents
an open window in a browser. The JavaScript Image Object is a property of the document
object. The Image object represents an embedded image. The history object contains
the URLs visited by the user (within a browser window).JavaScript History Object provides
the function to get the browser history information for the current browser window opened
by the visitor. The location object is the property of the windows object. It contains
information about the current URL being displayed by the window.
Source: www.w3schools.com (Link)
Advanced Web Designing / 110
11.11 CHECK YOUR PROGRESS- ANSWERS
11.1 and 11.2
1) True
2) True
11.3
1) blur()
2) open()
3) scollTo()
4) Location
11.4 and 11.5
True or false
1) True
2) False
3) True
4) True
11.6 and 11.7
Fill in the blanks
1) image
2) align property
3) history
4) array
11.8 and 11.9
True or false
1) True
2) True
3) True
11.12 QUESTION FOR SELF - STUDY
1) What are JavaScript commonly used objects?
2) Differentiate between History and Location Object
3) Write a short note on DOM object.
4) Where is the Navigator Object Model Used?
11.13 SUGGESTED READINGS
1.
Html, Dhtml, Javascript, Perl CGI - By Ivan Bayross
2.
Pure JavaScript - Techmedia publication
3.
www.w3schools.com
4.
www.tizag.com
³³³
The JavaScript Object Model / 111
NOTES
Advanced Web Designing / 112
Chapter 12
JavaScript Objects
1234567890123456789012345678901
1234567890123456789012345678901
1234567890123456789012345678901
12.0
Objectives
1234567890123456789012345678901
1234567890123456789012345678901
12.1
Introduction
1234567890123456789012345678901
1234567890123456789012345678901
12.2
JavaScript Objects
1234567890123456789012345678901
1234567890123456789012345678901
12.2.1 String Object
1234567890123456789012345678901
12.2.2 Date Object
1234567890123456789012345678901
1234567890123456789012345678901
12.2.3 Math Object
1234567890123456789012345678901
1234567890123456789012345678901
12.2.4 Array Object
1234567890123456789012345678901
1234567890123456789012345678901
12.2.5 Form Object
1234567890123456789012345678901
12.2.6 Select Object
1234567890123456789012345678901
1234567890123456789012345678901
12.2.7 Textarea Object
1234567890123456789012345678901
1234567890123456789012345678901
12.2.8 Checkbox Object
1234567890123456789012345678901
12.2.9 Radio Button Object
1234567890123456789012345678901
1234567890123456789012345678901
12.2.10 Text Object
1234567890123456789012345678901
1234567890123456789012345678901
12.2.11 Select Object
1234567890123456789012345678901
1234567890123456789012345678901
12.3
JavaScript Form Validation
1234567890123456789012345678901
1234567890123456789012345678901
12.4
Summary
1234567890123456789012345678901
1234567890123456789012345678901
12.5
Check Your Progress-Answers
1234567890123456789012345678901
1234567890123456789012345678901
12.6
Questions for Self - Study
1234567890123456789012345678901
1234567890123456789012345678901
12.7
Suggested Readings
1234567890123456789012345678901
12.0 OBJECTIVES
Dear friends,
After learning this chapter you can
l
l
Describe JavaScript as OOP language
Explain various objects in JavaScript
12.1 INTRODUCTION
JavaScript is an Object Oriented Programming (OOP) language.
An OOP language allows you to define your own objects and make your own
variable types.
Object Oriented Programming
JavaScript is an Object Oriented Programming (OOP) language. An OOP
language allows you to define your own objects and make your own variable types.
Note that an object is just a special kind of data. An object has properties and
methods.
Properties
Properties are the values associated with an object.
12.2 JAVASCRIPT OBJECTS
The various Javascript objects are observed as follows:
String Object
Date Object
Math Object
Array Object
Form Object
Select Object
Textarea Object
JavaScript Objects / 113
Checkbox Object
Radio Button Object
Text Object
Select Object
12.2.1 String Object
Any string variable in JavaScript is actually a string object. They have a single
property i.e. length. And methods of string object enable you to convert strings, work with
pieces of string, search for values. The String object is used to manipulate a stored piece
of text.
The following example uses the length property of the String object to find the length
of a string:
var txt=”Hello world!”;
document.write(txt.length);
The code above will result in the following output: 12.
·
Methods:- Methods are the actions that can be performed on objects.
1. toUpperCase():- It converts all characters in the string to uppercase.
<script type=”text/JavaScript”>
var str=”Hello world!”;
document.write(str.toUpperCase());
</script>
the output of the code above will be:HELLO WORLD!
2. toLowerCase():-It converts all characters in the string to lowercase.
3. subString():- It returns a string consist of a portion of the original string
between two indexed values, which you specify.
E,g str = “ABCDEFGH”;
Document.write(str.subString(0,4));
Output :- “ABCD”
4.
5.
6.
7.
8.
9.
10.
11.
12.
charAt():- it takes a single index & returns a single character.
split():- It splits a string into an array of strings based on a separator.
indexOf():- It searches for a string within another string.
String.big() :- it displays big text
String.bold() :- displays bold text
String.italics():- displays string in italics.
String.small():- display string in small letters.
String.sub():- displays subscript text.
String.sup():- displays superscript text
12.2.2 Date Object
The Date object is used to work with dates and times. You can create date object
any time you need to store a date & use date objects method. Date objects have no
properties. You can create it using new keyword.
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
Advanced Web Designing / 114
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most
methods allow you to get and set the year, month, day, hour, minute, second, and
milliseconds of the object, using either local time or UTC (universal, or GMT) time.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date(“October 13, 1975 11:13:00”)
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
Note: If adding five days to a date shifts the month or year, the changes are handled
automatically by the Date object itself!
Compare Two Dates
The Date object is also used to compare two dates.
The following example compares today’s date with the 14th January 2010:
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert(“Today is before 14th January 2010”);
}
else
{
alert(“Today is after 14th January 2010”);
}
l
Methods
1. setDate() :- It sets the day of the month
2. setMonth() :- It sets the month. JavaScript numbers the month
from 0-11.starting with Jan as zero..
3. setYear() :- It sets the year.
4. setTime() :- sets the time by specifying no.of milliseconds since jan 1st 1970.
5. setHours(),setMinutes() & setSeconds() :- It sets the time.
6. getDay() :- Gets the day.
JavaScript Objects / 115
7. getMonth() :- gets the month.
8. getYear() :- gets the year.
9. getTime():- gets the time in milliseconds since 1 Jan 1970
10. getHours(),getMinutes(),getSeconds() :- It gets the time..
12.2.3 Math Object:-
In JavaScript you can’t create Math object. It automatically exists in JavaScript
program & includes all JavaScript math capabilities.
The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical constants and methods.
Syntax for using properties/methods of Math:
var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by
using Math as an object without creating it.
Mathematical Methods
1. round():- This method rounds the number to the nearest integer.
document.write(Math.round(4.7));
The code above will result in the following output: 5
2. random():- This method of the Math object to return a random number between 0 and
1:
document.write(Math.random());
The code above can result in the following output:
0.14329274580813944
3. floor() :- Rounds a number down to the next integer
4. ceil() :- rounds a number up to the next integer.
12.2.4 Array Object
The Array object is used to store multiple values in a single variable.
Array Object Properties
constructor
Returns the function that created the Array object’s prototype
length
Sets or returns the number of elements in an array
prototype
Allows you to add properties and methods to an object
Advanced Web Designing / 116
Array Object Methods
Method
Description
concat()
Joins two or more arrays, and returns a copy of the joined arrays
join()
Joins all elements of an array into a string
pop()
Removes the last element of an array, and returns that element
push()
Adds new elements to the end of an array, and returns the
new length
reverse()
Reverses the order of the elements in an array
shift()
Removes the first element of an array, and returns that element
slice()
Selects a part of an array, and returns the new array
sort()
Sorts the elements of an array
splice()
Adds/Removes elements from an array
toString()
Converts an array to a string, and returns the result
unshift()
Adds new elements to the beginning of an array, and returns
the new length
valueOf()
Returns the primitive value of an array
12.2.5 Form Object
The Form object represents an HTML form.
For each <form> tag in an HTML document, a Form object is created.
Forms are used to collect user input, and contain input elements like text fields,
checkboxes, radio-buttons, submit buttons and more. A form can also contain select
menus, textarea, fieldset, legend, and label elements.
Forms are used to pass data to a server.
Form Object Collections
Collection
Description
elements[]
Returns an array of all elements in a form
Form Object Properties
Property
Description
acceptCharset
Sets or returns the value of the accept-charset attribute
in a form
action
Sets or returns the value of the action attribute in a form
enctype
Sets or returns the value of the enctype attribute in a form
length
Returns the number of elements in a form
method
Sets or returns the value of the method attribute in a form
name
Sets or returns the value of the name attribute in a form
target
Sets or returns the value of the target attribute in a form
Form Object Methods
Method
Description
reset()
Resets a form
submit()
Submits a form
Form Object Events
Event
The event occurs when...
onreset
The reset button is clicked
onsubmit
The submit button is clicked
JavaScript Objects / 117
12.2.6 Button Object
The Button object represents a push button.
For each <button> tag in an HTML document, a Button object is created.
Inside an HTML button element you can put content, like text or images. This is the
difference between this element and buttons created with the input element.
Button Object Properties
Property
form
name
type
value
Description
Returns a reference to the form that contains a button
Sets or returns the value of the name attribute of a button
Sets or returns the type of a button
Sets or returns the value of the value attribute of a button
12.2.7 Textarea Object
The Textarea object represents a text-area in an HTML form.
For each <textarea> tag in an HTML form, a Textarea object is created.
You can access a Textarea object by indexing the elements array (by number or name)
of the form or by using getElementById().
Textarea Object Properties
Property
Description
cols
Sets or returns the width of a textarea
defaultValue Sets or returns the default text in a textarea
disabled
Sets or returns whether or not a textarea should be disabled
form
Returns a reference to the form that contains the textarea
name
Sets or returns the name of a textarea
readOnly
Sets or returns whether or not a textarea should be read-only
rows
Sets or returns the height of a textarea
type
Returns the type of the form element
value
Sets or returns the text in a textarea
Textarea Object Methods
Method
Description
select()
Selects the text in a textarea
12.2.8 Checkbox Object
The Checkbox object represents a checkbox in an HTML form.
For each instance of an <input type=”checkbox”> tag in an HTML form, a Checkbox
object is created.
Checkboxes let a user select one or more options of a limited number of choices.
You can access a Checkbox object by searching through the elements[] array of a form,
or by using document.getElementById().
Advanced Web Designing / 118
Checkbox Object Properties
Property
Description
checked
Sets or returns the checked state of a checkbox
defaultChecked Returns the default value of the checked attribute
form
Returns a reference to the form that contains the checkbox
name
Sets or returns the value of the name attribute of a checkbox
type
Returns which type of form element the checkbox is
value
Sets or returns the value of the value attribute of a
checkbox
12.2.9 Radio Button Object
The Radio object represents a radio button in an HTML form.
Radio buttons allow the user to select only ONE of a predefined set of options.
You define groups with the name property (radio buttons with the same name belong to
the same group).
For each <input type=”radio”> tag in an HTML form, a Radio object is created.
You can access a radio object by searching through the elements[] array of the
form, or by using document.getElementById().
Radio Button Object Properties
Property
Description
checked
Sets or returns the checked state of a radio button
defaultChecked
Returns the default value of the checked attribute
form
Returns a reference to the form that contains the radio
button
name
Sets or returns the value of the name attribute of a
radio button
type
Returns which type of form element the radio button is
value
Sets or returns the value of the value attribute of the
radio button
12.2.10 Text Object
The Text object represents a single-line text input field in an HTML form.
For each <input type=”text”> tag in an HTML form, a Text object is created.
You can access a text input field by searching through the elements[] array of the form,
or by using document.getElementById().
Text Object Properties
Property
defaultValue
form
Description
Sets or returns the default value of a text field
Returns a reference to the form that contains
the text field
W3C
Yes
Yes
JavaScript Objects / 119
maxLength
name
readOnly
size
type
value
Sets or returns the maximum number of
characters allowed in a text field
Sets or returns the value of the name
attribute of a text field
Sets or returns whether a text field is
read-only, or not
Sets or returns the width of a text field
(in number of characters)
Returns which type of form element a
text field is
Sets or returns the value of the value
attribute of the text field
Yes
Yes
Yes
Yes
Yes
Yes
Text Object Methods
Method
Description
W3C
select()
Selects the content of a text field
Yes
12.2.11 Select Object
The Select object represents a dropdown list in an HTML form.
For each <select> tag in an HTML form, a Select object is created.
You can access a Select object by searching through the elements[] array of the form, or
by using document.getElementById().
Select Object Collections
Collection
Description
options[]
Returns an array of all the options in a dropdown list
Select Object Properties
Property
Description
disabled
Sets or returns whether or not a dropdown list should be disabled
form
Returns a reference to the form that contains the dropdown list
length
Returns the number of options in a dropdown list
multiple
Sets or returns whether or not multiple items can be selected
name
Sets or returns the name of a dropdown list
selectedIndex
Sets or returns the index of the selected option in a dropdown list
size
Sets or returns the number of visible rows in a dropdown list
type
Returns the type of form element a dropdown list is
Select Object Methods
Method
add()
remove()
Description
Adds an option to a dropdown
Removes an option from a dropdown list
Advanced Web Designing / 120
12.1 and 12.2 Check your Progress
Fill in the blanks
1) The Button object represents a .............button
2) The .............. represents a single-line text input field in an HTML form
3) The ..............object represents a dropdown list in an HTML form.
4) .............are used to pass data to a server.
12.3 JAVASCRIPT FORM VALIDATION
JavaScript can be used to validate data in HTML forms before sending off the content to
a server.
Form data that typically are checked by a JavaScript could be:
l
has the user left required fields empty?
l
has the user entered a valid e-mail address?
l
has the user entered a valid date?
l
has the user entered text in a numeric field?
Required Fields
The function below checks if a field has been left empty. If the field is blank, an alert
box alerts a message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms[“myForm”][“fname”].value
if (x==null || x==””)
{
alert(“First name must be filled out”);
return false;
}
}
The function above could be called when a form is submitted:
Example
<form name=”myForm” action=”demo_form.asp” onsubmit=”return validateForm()”
method=”post”>First name: <input type=”text” name=”fname”><input type=”submit”
value=”Submit”></form>
E-mail Validation
The function below checks if the content has the general syntax of an email.
This means that the input data must contain an @ sign and at least one dot (.).
Also, the @ must not be the first character of the email address, and the last dot must be
present after the @ sign, and minimum 2 characters before the end:
function validateForm()
{
var x=document.forms[“myForm”][“email”].value
var atpos=x.indexOf(“@”);
var dotpos=x.lastIndexOf(“.”);
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert(“Not a valid e-mail address”); return false;
}
}
JavaScript Objects / 121
The function above could be called when a form is submitted:
Example
<form name=”myForm” action=”demo_form.asp” onsubmit=”return
validateForm();” method=”post”>
Email: <input type=”text” name=”email”>
<input type=”submit” value=”Submit”>
</form>
12.3 Check Your Progress
True or false
1) JavaScript can be used to validate data in HTML forms before sending off the content
to a server
2) Form data that typically are checked by a JavaScript could be, has the user entered
a valid date
12.4 SUMMARY
Object Oriented Programming
JavaScript is an Object Oriented Programming (OOP) language. An OOP language
allows you to define your own objects and make your own variable types.
Note that an object is just a special kind of data. An object has properties and
methods.
Any string variable in JavaScript is actually a string object. They have a single
property i.e. length. And methods of string object enable you to convert strings, work with
pieces of string, search for values. The String object is used to manipulate a stored piece
of text
The Date object is used to work with dates and times. You can create date object
any time you need to store a date & use date objects method. Math Object automatically
exists in JavaScript program & includes all JavaScript math capabilities. The Array object
is used to store multiple values in a single variable. The Form object represents an HTML
form.
12.5 CHECK YOUR PROGRESS - ANSWERS
12.1 and 12.2
Fill in the blanks
1) push
2) text object
3) select
4) forms
12.3
True or false
1) True
2) True
Advanced Web Designing / 122
12.6 QUESTIONS FOR SELF - STUDY
1) Write a short note on WITH statement.
2) Explain any three JavaScript object models.
3) What is validation? Write a code for phone number validation for textbox.
4) What is use of SELECT object in JavaScript?
12.7 SUGGESTED READINGS
1. Html, Dhtml, Javascript, Perl CGI - By Ivan Bayross
2. Pure JavaScript - Techmedia publication
3. www.w3schools.com
4. www.tizag.com
³³³
JavaScript Objects / 123
NOTES
Advanced Web Designing / 124
Chapter 13
Active Server Pages
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.0 Objectives
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.1 Introduction to Jscript
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.2 Language Directive.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.3 If condition and loops.
12345678901234567890123456789012123456789
13.4 Active Server Pages.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.4.1 What can you do with Active Server Pages
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.4.2 Web Server.
12345678901234567890123456789012123456789
13.4.3 Integrating Script into Active Server Pages.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.4.4 Testing Your Configuration.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.5 Sessions
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.5.1 Contents of Session.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.5.2 Identifying a Session
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.6 Cookies
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.13.1 Creating and Reading Cookies with Active
12345678901234567890123456789012123456789
Server Pages.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.13.2 Retaining State With Hidden Form Fields
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.7 What is an Application.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.14.1 Modifying the Global.asa file.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.14.2 Reading and Appending Data from Text File.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.14.3 Retrieving the Attributes of a File.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.8 Difference between JavaScript and VB Script
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.9 Summary
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.10 Check Your Progress - Answers
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
13.11 Questions For Self - Study
12345678901234567890123456789012123456789
13.12
Suggested Readings
12345678901234567890123456789012123456789
13.0 OBJECTIVES
Dear friends,
After learning this chapter you can
•
Explain Use of JavaScript in ASP pages
•
Understand Language directives and Use of loops.
•
Describe Use of Sessions and Cookies
•
Explain Concept of Global.asa
13.1 INTRODUCTION
IIS stands for Internet Information Server. Internet Information Server is the underpinning
that provides Information-publishing capabilities on Internet. Microsoft provides other vehicles
for personal content publishing such as Personal Web Server but Internet Information
Server is Microsoft’s engine for departmental & enterprise-level publishing. IIS is the
engine that runs large Web sites such as Microsoft .com, msm.com & investersedge.com.
Table for versions of IIS & year of availability is given below: -
Active Server Pages / 125
Version Year
IIS 1.0 1995
IIS 3.0 summer of 1996
IIS 4.0 June 1997
Using the Service Manager
Microsoft introduced a new management tool with IIS 4.0 known as the Microsoft
Management Console (MMC). MMC is more of framework that hosts snap- ins, such as
IIS. As Microsoft moves forward to NT 5, more snap-ins will be designed for MMC. MMC
is used to manage IIS, not to install it. MMC uses a familiar Explorer like interface,
complete with an expandable tree view control.
It isn’t integrated with Explorer in the same way as Control Panel & Internet Explorer
4.0.
13.2 LANGUAGE DIRECTIVE
After including the Language directive in your Active Server Page, you can create
JScript scripts by using the two special characters < % & %>. For e.g.the following
JScript scripts executes automatically in an Active Sever Page:
<% @ LANGUAGE = Jscript %>
<HTML>
<HEAD>
<TITLE> Simple Jscript </TILTE>
</HEAD>
<BODY>
<% for (myvar = 0; myvar < 500 ; myvar + +)%>
<B> Hello World!!! <B></BODY>
</HTML>
This script prints the sentence Hello World! 500 times in a row.<% & %> indicates
the places where the Jscript script begins & ends.
Working With Dates & Times
The DATE object has a number of useful methods for manipulating & retrieving dates
& times. For e.g.
<%
mydate = new Date ()
%>
<BR>The current date & time is:
<%=my date %>
< BR> The current month is:
<%= my date. get Month ( ) %>
<BR> The current day of the month is:
<%=my date .get Date( )%>
<BR>The current day of the week is:
<%=my date. get Day( )%>
<BR> The current year is:
<%= mydate. get Year ( )%>
<BR> The current hour is:
<%= my date .get Hour ( )%>
<BR> The current minute is:
<%= my date .get Minutes ( )%>
<BR> The current second is:
<%= my date .get Second ( )%>
Advanced Web Designing / 126
You must create a DATE object before you can retrieve any date or time information.
In this script, the date object mydate is created with the first statement in the script.
Many of values retuned by Date methods are zero-based.
Adding HTML to String
If you use the View Source command on your Web browser, you’ll discover that
exactly the same string is outputted in each case. The bold ( ) method isn’t the only
String Method that adds HTML tags to a string. Consider all the methods used in the
following script.
<BR> <%= “I am big!”. big ( )%>
<BR> <%= “I am bold!”. bold ( )%>
<BR> <%= “Blink, blink “. blink ( )%>
<BR> <%= “I am formatted with fixed width font”. fixed ( )%>
<BR> <%= “I am in italics”. italics ( )%>
<BR> <%= “I am small”. small ( )%>
<BR> <%= “I have line through me”. strike ( )%>
<BR> <%= “I am in subscript”. sub ( )%>
<BR> <%= “I am in superscript”. sup ( )%>
<BR> <%= “I am in color red”. font color (“red” )%>
<BR> <%= “I am big!”. font size (4)%>
You can also use String method to create hypertext links & named anchors.
You can run this program as an exercise and check the output.
13.3 IF CONDITION AND LOOPS
Using conditional statements [ if……then…..else]
If you need to execute a single statement or block of the statement depending on
whether some conditions is true or false, then you need to use a conditional. A
conditional accepts any expression as its condition that returns a Boolean value. For
e.g.
<%
greeting = “Happy Weeday!”
mydate = new date ( ) ;
if (mydate.getDay ( )= =0) greeting = “Happy Sunday!”;
if (mydate.getDay ( )= =6) greeting = “Happy Saturday!”;
%>
<%greeting%>
if the day of the week is Saturday or Sunday, this script returns the appropriate
greeting, otherwise, the script outputs the greeting Happy Weekday!
Word then is not used in a Jscript conditional. If the condition is true, the statement
or block of statement following the parentheses is executed. For e.g.
<%
greeting = “Happy Other Day !”
mydate = new date ( ) ;
if (mydate.getDay ( )= =0)
{
greeting = “Happy Sunday!”;
greeting = greeting .bold( );
greeting = greeting .italics ( )
}
%>
<%greeting%>
in this e.g., the three statements contained within the curly braces ( { } ) are not
executed on any day except Sunday. The braces indicates the stat & end of the
consequence of the conditional.
Repeating Statements with Loops [for…. next]
If you need to repeat a single statement or block of statement a particular number of
times, you can use a For. ……Next loop. The following for….next prints Hello World!
Exactly 10 times.
Active Server Pages / 127
<%
for (myvar = 0 ; myvar < 10 ;myvar + +)
%>
Hello World!
For statement has three parts.
a) Initializes the variable
b) Tests whether some condition is true [ this loop is keep executing while the
value of myvar is less than 10]
c) Increments the myvar variable.
A statement that’s closely related to the for…next statement is the for…in statement.
You can use the for… in statement to step through each of the elements of an array
or objects. For e.g.
<%
myarray =new Array (“John” , “Paul”, “George”, “Ringo”);
for (myvar in myarray )
{
%>
<% =myarray [myvar]%>
<%
}
%>
this script output the values of all the members of the array named myarray. For each
element in myarray, the statement executes the block of the code
13.4 ACTIVE SERVER PAGES
An Active Server Page is standard HTML file that has been extended with additional
features. Like a standard HTML file, an Active Server Page can contain HTML tags
that will be interpreted & displayed by a Web browse. Anything you could normally
place in an HTML file – JAVA applets, blinking text, client-side scripts, client-side
ActiveX controls- you can place in an Active Server Page
Active Server Page has four features that make it unique:
a) An Active Server Page can contain server-side scripts.
b) An Active Server Page provides a number of build-in objects.
c) An Active Server Page can be extended with additional components.
d) An Active Server Page can interact with a database such as Microsoft’s SQL
Server.
13.4.1 What Can You Do with Active Server Pages?
1
2
3
4
5
6
7
The following list shows some simple examples of what you can do:
Include rotating banner advertisement on the Web pages of your WebSite.
Retrieve information entered into a HTML form & store that information in a database.
Create personalized Web pages that displayed different content to different user.
Add hit counters to one more pages of your Web site.
Display different Web pages, depending on the capability of a user’s browser.
Link together multiple Web pages in such way that they can be navigated Easily.
Track information about user activity at your Web site & save that information in a
custom log file.
How Do Active Server Pages Work?
Microsoft introduced Active Server Pages transformed IIS from being s mere server of
static content to being a server of dynamic content. The main function of IIS was to server
static HTML pages. When someone requested a Web page from a Web site using IIS,
the server would fetch static HTML file from disk or memory & send it out to the person’s
browser. The primary responsibility of IIS was to act as an efficient interface between
browsers & a bunch of files sitting on the Web server’s hard drive.
Advanced Web Designing / 128
13.4.2
a)
b)
c)
d)
e)
Web Server
The main function of any Web server is to serve HTML files. It is important to
understand how this process of serving an HTML file is carried out. So here are
the steps:
A user enters the Internet address of an HTML file into the address bar of a Web
browser & process Enter to request a Web page.
The browser sends a request for the Web page to a Web server such as IIS.
The Web server receives the request & recognized that the request is for an
HTML file because the requested file has the extension .htm, .html
The Web server retrieves the proper HTML file from disk or memory & sends the
file back to the browser.
The HTML file is interpreted by the person’s Web browser & the results are
displayed in the browser window.
Active Server Page contrasts with the normal process of serving an
HTML page, so we’ll break it into steps:
a) A user enters the Internet address of an Active Server Page file into the address
bar of a Web browser & presses Enter to request an Active Server Page.
b)
The browsers send a request for the Active Server Pages to IIS.
c)
The web server receives the request & recognizes that the request is for an
Active Server Page file because the requested file has the extension .asp.
d)
The Web server retrieves the proper Active Server Page file from disk or memory.
e)
The Web server sends the file to special program named ASP.dll
f)
The Active Server Page file is processed from top to bottom & any encountered
commands are executed. The result of this process is a standard HTML file.
g)
The HTML file is sent back to the browser.
h)
The person’s Web browser interprets the HTML file & the results are displayed
in the browser window.
13.4.3 Integrating Scripts into Active Server Pages
Any scripting language that has a scripting engine compatible with ActiveX scripting
standard can be used in an Active Server Page.
The easiest way to add script to an Active Server Page is by using the scripts
delimiters <% & %>. Any text enclosed within these delimits will be processed as a
script. For e.g.
<HTML>
<HEAD>
<TITLE> ASP Script </TITLE>
</HEAD>
<BODY>
This is a
<% For i =1 To 10%>
very,
<%NEXT%>
very long sentence.
</BODY>
</HTML>
Active Server Pages / 129
Mix Multiple Scripting Language Within a Single Active Server Page
Consider the following e.g.
<%@LANGUAGE = “VBSCRIPT”%>
<HTML>
<HEAD>
<TITLE> ASP Script </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = “Jscript” RUNAT = “server”>
function sayhello( )
{
response. write (“Hello!”)
}
</SCRIPT>
<%
FOR i = 1 to 10
Sayhello( )
NEXT
%>
</BODY>
</HTML>
Active Server Pages Components
Active Server Pages Components can be used to extend the power of your scripts. The
following list provides a brief overview of some of the components bundled with Active
Server Pages:
The Ad Rotator components:
The Ad Rotator components is used to display banner advertisement on the
Web pages of a Web site.
The Browser Capabilities components:
The Browser Capabilities component can be used to display different HTML
contents, according to the capabilities of different browsers.
The Content Linking components:
Using the Content Linking component, you can link together a number of HTML
pages so that they can be navigated easily.
The Counters components
The Counters component can be used to keep track of the number of visitors to
your Web site.
The Content Rotator component
The Content Rotator component enables you to rotate through HTML content on
a page.
The Page Counter component
The Page Counter component can be used to track the number of visitors to a
Web page.
The Permission Checker component
The Permission Checker component can be used to display links to Web pages
only if a user has permission to see them
The ActiveX Data Objects
The ActiveX Data Objects enable you to retrieve & store data in a database such
as Microsoft SQL Server.
Configuring & Troubleshooting Active Server Pages.
You need to configure at least one directory in your web site with permission to execute
an Active Server Pages file. Follow these steps:
Advanced Web Designing / 130
Launch the Internet Service Manager from the Microsoft Internet Information Server program
on the start menu.
In the left pane of the Internet Service Manger, navigate to your default Web site.
Choose the directory in your Web site where you want to store your Active Server Pages
files by navigating to it in the Internet Service Manager.
Right-click the name of this directory & choose Properties.
Click the tab labeled Directory or Virtual Directory
In the permission section, choose either Script or Execute.
13.4.4 Testing Your Configuration
To create an Active Server Pages, you can use any text editor. For e.g. you can use
Notepad, which is included as an accessory with Windows NT Server. Start Notepad
& enter the following text:
<HTML>
<HEAD>
<TITLE> ASP Page</TITLE>
</HEAD>
<BODY>
<%
Response. Write (“Hello World”)
%>
</BODY>
</HTML>
Save the Active Server Page file as test. asp.
To execute program type command in the brower window http://localhost/test.asp
HTTP Protocol
HTTP stands for Hypertext Transfer Protocol. The HTTP protocol specifies how
messages can be transported over the Internet. The protocol specifies the ways in
which a browser & a Web server can interact.
The web server receives the request & issues a response. For this reason, the HTTP
protocol is called a request & responds protocol.
A browser request has a certain structure. A request message contains a request
line, header fields, && possibly a message body. The most common type of request
is a simple request for a Web page, as followig e.g.
GET /hello.htm HTTP /1.1
Host: www. aspsite .com
Password Protected
<HTML>
<HEAD>
<TITLE> password protected</TITLE>
</HEAD>
<BODY>
<%
If request. Server Variables (“AUTH_TYPE”) = “Basic” THEN
%>
You are logged in using Authentication.
Your account is <%= Request. Server Variables( “LOGON_USER”)%>
<%ELSE%>
You are logged in using Basic Authentication.
Your account is <%= Request. Server Variables( “LOGON_USER”)%>
<%END IF %>
</BODY>
</HTML>
Active Server Pages / 131
Registration
Suppose you want visitors to your Web site to register before they can be use it.
To gather registration information, you should use an HTML form. For e.g.
<HTML>
<HEAD>
<TITLE> registration </TITLE>
</HEAD>
<BODY>
<H4> Registration</H4>
<FORM METHOD = “POST” ACTION = “/regresults. Asp”>
<P> Please enter your first name:
<BR> <INPUT NAM E= “First Name” TYPE = “TEXT”>
<P> Please enter your last name:
<BR> <INPUT NAM E= “Last Name” TYPE = “TEXT”>
<INPUT TYPE = “SUBMIT “ VALUE= “Continue’>
</FORM>
</BODY>
</HTML>
This form simply asks for the first & last name of the visitor. Once the information is
entered, the Continue button can be click to move to the next page.
Dumping the Contents of the Form Collection
A number of ways exits to retrieve all the contents of the form collection. If you want
to loop through the contents of the collection & display each value, you could use
the following script:
<%
FOR EACH name IN Request. Form
Response. Write (“<BR>”&name& “=”)
Response. Write (Request. Form (name))
NEXT
%>
this script displays each key-&-value pair in the Form collection. IF bill Gates visit
your Web site & use registration form, the output will belook like this:
LAST NAME= Gates
FIRST NAME = Bill
Form Elements with Multiple Values
Certain HTML form elements can have more than one value. For e.g. both check
boxes & list boxes can have multiple values. Consider the following HTML.
<FORM METHOD = “POST” ACTION = “.reg results .asp”>
How did you hear about our web site?
<BR> <INPUT NAME = “How Hear” TYPE = “Checkbox” VALUE = “A News Paper
Article”>
A News Paper Article.
<BR> <INPUT NAME = “How Hear” TYPE = “Checkbox” VALUE = “A Search Engine”>
A Search Engine
<BR> <INPUT NAME = “How Hear” TYPE = “Checkbox” VALUE = “A Friend”>
A Friend
<BR> <INPUT NAME = “How Hear” TYPE = “Checkbox” VALUE = “Stumbled Into
It”>
Stumbled Into It
<P> <INPUT TYPE = “SUBMIT” VALUE = “Continue”>
</FORM >
This form can be used to determine how visitors to your Web site discovered it. But
someone may found out about your Web site in more than one way.
Advanced Web Designing / 132
13.5 SESSIONS
A session is something that starts the moment a user request a page from your Web
site & ends soon after the user levels. Each visitor to your Web site is given individual
session.
Use of Sessions
a) Sessions can be used to store a visitor’s preferences.
b) Sessions can also be used to create virtual shopping carts. Whenever a visitor
selects an item to buy at your Web site, the item can be added to a shopping
cart. All the information about items is stored in the shopping cart can be stored
in a session.
c) Session can be used to keep of the habits of your visitors.
Storing Session Information
Active Server Pages sessions are easy to use. You can control all aspects of sessions
by using the Active Server Pages session’s objects. If you need store data, you
simply store data in a collection of the Session object. For e.g.
<HTML>
<HEAD>
<TITLE> Session e.g.</TITLE>
<BODY>
<%
Session (“Greeting”) = “Welcome!”
Response. Write (Session (“Greeting”))
%>
</BODY>
</HTML>
The first line in a script assigns the text “Welcome!” to a session variable named
Greeting. The next line in the script outputs the Greeting to the screen.
By using VB script, imagine that the same user request for another:
<HTML>
<TITLE> Another Page. </TITLE>
<BODY>
<%Session (“Greeting”) %>
</BODY>
</HTML>
13.5.1 The Contents of a Session
Most session variables are actually stored in a collection of the session object named
contents. For e.g., the following two statements are equivalent:
<% Session (“MyVar”) = “Some data”%>
<% Session.contents (“MyVar”) = “Some data”%>
Using FOR…EACH & FOR…. NEXT
<%
Session (“Favorite Color”) = “Blue”
Session (“Favorite Font”) = “Comic Sans MS”
%>
There are <% = Session. Contents. Count %>
Items in the Session Contents collection.
<HR>
<%
FOR EACH thing IN Session collection
Active Server Pages / 133
Response. Write (“<BR>” &thing &” = “&Session. Contents (thing))
NEXT
Response. Write (“<HR>”)
FOR i =1 To Session. Contents. Count
Response. Write (“<BR>”&Session. Contents (i)).
NEXT
%>
Using both FOR… EACH & FOR …. NEXT loop display all the items.
13.5.2 Identifying a Session
Active Server Page assigns each user session a unique identifier. This session ID is
created when the user session is first created & persists thorough the time user
remains at your Web site. The session Id is property of session object. For e.g.
<HTML>
<HEAD>
<TITLE> Session ID </TITLE>
</HEAD>
<BODY>
Your session ID is: <%= Session. Session ID%>
</BODY>
</HTML>
13.6 COOKIES
Few Internet technologies create greater agitation among web users than cookies.
Cookies have an innocent-sounding name, but many users assume that they have
an evil purpose.
Browser that supports cookies maintains one or more special files. These files are
called cookies files on Windows machine & magic cookies file on the Macintosh, are
used to store data form Web sites. The Web server inserts pieces of information into
cookie file
Certain cookies are temporary; others are persistent for e.g. the cookies are used by
Active Server Pages to track user sessions expire after a visitor leaves the Web site.
Other cookies are remains in the cookies files to be read by the server when a user
returns.
How Cookies Work
Cookies are passed back & forth between a browser & server through HTTP headers.
The server first creates a cookie by using the set-cookie header in a response.
Subsequent request form the browser will return this cookie in the cookie header.
Suppose you want to create a cookie name User Name that contains the name of
the visitor to your web site. To create this cookie, the server would send a header like
this:
Set –Cookie: User Name = BILL +Gates; path = /; domain = aspsite.com;
Expires = Tuesday, 01-Jan-99 00:00:01 GMT
This header instructs the browser to add an entry to its cookie file. The browser adds
the cookie name User Name with the Bill Gates. Notice that the value of the cookie
is URL encoded.
13.6.1 Creating & Reading Cookies With Active Server Pages
To create a cookie with Active Server Page, you use the cookies collection of Response
object. You can create two types of cookies;
Cookies with single value, or cookie dictionary.
Cookies with multiple name & value pairs
If you don’t specify an expiration date for the cookie, the cookie expires when the
user leaves your Web site.
Cookies collection has a number of additional attributes.
Advanced Web Designing / 134
For e.g.
<%
Response. Cookies (“UserName”) = “Steve Jobs”
Response. Cookies (“UserName”). Expires = “Jan 1,1999”
Response. Cookies (“UserName”). Pah = “/example”
Response. Cookies (“UserName”) .Domain = “aspsite.com”
Response. Cookies (“UserName”).Secure = True
%>
13.6.2 Retaining State With Hidden Form Fields
You can hide the information you’re passing by using a hidden form field, as in e.g.
<HTML>
<HEAD>
<TITLE>Form State</TITLE>
</HEAD>
<BODY>
<%
UserName = “Bill Gates”
%>
<FORM METHOD = “Post” Action = “/nextpage.asp”>
<INPUT NAME = “UserName” TYPE = “HIDDEN” VALUE =
“<% UserName%>”>
<INPUT TYPE = “SUBMIT” VALUE=”Next Page”>
</FORM>
</BODY>
</HTML>
You must use the form Collection of the Request object to retrieve the data in the
hidden field. For e.g.
<HTML>
<HEAD>
<TITLE>Form State</TITLE>
</HEAD>
<BODY>
<%
UserName = Request.form(“UserName”)
%>
<FORM METHOD = “Post” Action = “/nextpage.asp”>
<INPUT NAME = “UserName” TYPE = “HIDDEN” VALUE =
“<% UserName%>”>
<INPUT TYPE = “SUBMIT” VALUE=”Next Page”>
</FORM>
</BODY>
</HTML>
13.7 WHAT IS AN APPLICATION?
An application is defined by using the Internet Service Manager to specify a root
directory for the application. An application consists of a particular directory & all of
its subdirectories. If one of these subdirectories is also defined to be an application,
then it constitutes a separate application.
Features of an Active Server Page application
a) Data can be shared among the pages in an application, therefore among more
than one user of a web site.
b) An application has events that can trigger special application scripts.
c) An instance of an object can be sheared among all the pages in an application.
Active Server Pages / 135
d) Separate the application can be configured with Internet Service Manager to
have different properties.
e) You can stop one application without affecting other application.
13.7.1 The Global.asa file
The Global.asa file is an optional file that can contain declarations of objects,
variables, and methods that can be accessed by every page in an ASP application.
All valid browser scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be
used within Global.asa.
The Global.asa file can contain only the following:
l
Application events
l
Session events
l
<object> declarations
l
TypeLibrary declarations
l
the #include directive
Note: The Global.asa file must be stored in the root directory of the ASP application, and
each application can only have one Global.asa file.
Events in Global.asa
In Global.asa you can tell the application and session objects what to do when the
application/session starts and what to do when the application/session ends. The code
for this is placed in event handlers. The Global.asa file can contain four types of events:
Application_OnStart - Occurs when the FIRST user calls the first page in an ASP
application. This event occurs after the Web server is restarted or after the Global.asa file
is edited. The “Session_OnStart” event occurs immediately after this event.
Session_OnStart - This event occurs EVERY time a NEW user requests his or her first
page in the ASP application.
Session_OnEnd - This event occurs EVERY time a user ends a session. A user-session
ends after a page has not been requested by the user for a specified time (by default this
is 20 minutes).
Application_OnEnd - This event occurs after the LAST user has ended the session.
Typically, this event occurs when a Web server stops. This procedure is used to clean up
settings after the Application stops, like delete records or write information to text files.
A Global.asa file could look something like this:
<script language=”vbscript” runat=”server”>
sub Application_OnStart
‘some code
end sub
sub Application_OnEnd
‘some code
end sub
sub Session_OnStart
‘some code
end sub
Advanced Web Designing / 136
sub Session_OnEnd
‘some code
end sub
</script>
Note: Because we cannot use the ASP script delimiters (<% and %>) to insert scripts in
the Global.asa file, we put subroutines inside an HTML <script> element.
Restrictions
Restrictions on what you can include in the Global.asa file:
•
You cannot display text written in the Global.asa file. This file can’t display
information
•
You can only use Server and Application objects in the Application_OnStart and
Application_OnEnd subroutines. In the Session_OnEnd subroutine, you can use
Server, Application, and Session objects. In the Session_OnStart subroutine
you can use any built-in object
How to use the Subroutines
Global.asa is often used to initialize variables.
The example below shows how to detect the exact time a visitor first arrives on a
Web site. The time is stored in a Session variable named “started”, and the value of the
“started” variable can be accessed from any ASP page in the application:
<script language=”vbscript” runat=”server”>
sub Session_OnStart
Session(“started”)=now()
end sub
</script>
Global.asa can also be used to control page access.
The example below shows how to redirect every new visitor to another page, in this
case to a page called “newpage.asp”:
<script language=”vbscript” runat=”server”>
sub Session_OnStart
Response.Redirect(“newpage.asp”)
end sub
</script>
And you can include functions in the Global.asa file.
In the example below the Application_OnStart subroutine occurs when the Web
server starts. Then the Application_OnStart subroutine calls another subroutine named
“getcustomers”. The “getcustomers” subroutine opens a database and retrieves a record
set from the “customers” table. The record set is assigned to an array, where it can be
accessed from any ASP page without querying the database:
<script language=”vbscript” runat=”server”>
sub Application_OnStart
getcustomers
Active Server Pages / 137
end sub
sub getcustomers
set conn=Server.CreateObject(“ADODB.Connection”)
conn.Open “ Provider=”Microsoft.Jet.OLEDB.4.0;Data Source=northwind.mdb”
set rs=conn.execute(“select name from customers”)
Application(“customers”)=rs.GetRows
rs.Close
conn.Close
end sub
</script>
Global.asa Example
In this example we will create a Global.asa file that counts the number of current
visitors.
•
The Application_OnStart sets the Application variable “visitors” to 0 when the
server starts
•
The Session_OnStart subroutine adds one to the variable “visitors” every time
a new visitor arrives
•
The Session_OnEnd subroutine subtracts one from “visitors” each time this
subroutine is triggered
The Global.asa file:
<script language=”vbscript” runat=”server”>
Sub Application_OnStart
Application(“visitors”)=0
End Sub
Sub Session_OnStart
Application.Lock
Application(“visitors”)=Application(“visitors”)+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application(“visitors”)=Application(“visitors”)-1
Application.UnLock
End Sub
</script>
To display the number of current visitors in an ASP file:
<html>
<head>
</head>
<body>
Advanced Web Designing / 138
<p>There are <%response.write(Application(“visitors”))%> online now!</p>
</body>
</html>
13.7 CHECK YOUR PROGRESS
True or false on
1) The Global.asa file is an optional file that can contain declarations of objects
2) The time is stored in a Session variable named “started”, and the value of the “started”
variable can be accessed from any ASP page
3) Global.asa is often used to initialize variables
4) Global.asa can also be used to control page access
Modifying the Global.asa File
The following script I s used to initialize the application variables needed for the chat
pages. The following script initializes this variable to zero.
<SCRIPT NAGUAGE = VBScript RUNAT =Server>
SUB Application _ On Start
Dim Temp Array (5)
Application (“Talk”)= Temp Array
Application(“Tplace”) =0
END SUB
</HTML>
Creating Message Page
<%
If not request. Form (“message”) = “ “ THEN
Application. LOCK
IF Application.(“Tplace”) > 4 THEN
Application (“Tplace”) = 0
END IF
Temp Array = Application.(“Talk”)
Temp Array (Application.(“Tplace”)) = Request. Form (“Message”)
Application.(“Talk”) = Temp Array
Application.(“Tplace”) = Application.(“Tplace”) +1
Application.Unlock
END IF
%>
<HTML>
<HEAD>
<TITLE>Message Page</TITLE>
</HEAD>
<BODY BGCOLOR = “LIGHTBLUE”>
<FORM METHOD= “POST” ACTION = “method.asp”>
<INPUT NAME =”message” TYPE = “TEXT” SIZE = 50>
<INPUT TYPE = “SUBMIT” VALUE = “SEND”>
</FORM>
</BODY>
</HTML>
Creating The Display Page
<%
MyServer = Request. Server variables(“SERVER_NAME”)
MyPath= request. Server variables(“SCRIPT_NAME”)
MySelf = “HTTP:// “&MyServer & Mypath
Active Server Pages / 139
%>
<HTML>
</HEAD>
<TITLE> DISPALT PAGE</TITLE>
<BODY>
<P ALIGN = RIGHT> <%= NOW%> </P>
<%
TempArray= Application (“Talk”)
FOR I=0 to application (“Tplace”)-1
Response. Write (“<P>”& Temparray(i))
NEXT
%>
</BODY>
</HTML>
A sample Application of the Browser Capabilities Components
<%
Set MyBrow = Server. CreateObject (“MSWC.BrowserType”)
IF MyBrow.Frames THEN
%>
<HTML>
<HEAD>
<TITLE> Framed Page </TITLE>
<FRAMESET COLS = “100, * “>
<FRAMESET SRC = “menu.asp”>
<FRAMESET SRC = “body.asp”>
</FRAMESET>
</HTML>
<%ELSE%>
<HTML>
<HEAD>
<TITLE> Frameless Page </TITLE>
</HEAD>
<BODY>
We have detected that your browser is incapable of using frames:
You are using a <%=My Brow. Browser%> browser
(Version <% = MyBrow.version%>).
To download a more recent browser, please visit:
<P> <A HREF = “http: // www.microsoft.com”> Microsoft</A>
<P> OR
<P> <A HREF = “http: // www.netscape.com”> Netscape<A>
</BODY>
</HTML>
<%END IF%>
Writing To A Text File
To create & write to a text file you can use the File System object & Text Stream
Object. The Write Line ( ) method is used to send the single line of text Hello There!
To the file. For e.g.
<%
Set MyFileObject = Server. Create Object (“Scripting. File System object”)
Set MyTextFile = MyFileObject.Create Text File (“c:\mydir\test.txt”)
MyTextFile.Write Line (“Hello There!”)
MyTextFile. Close
%>
Advanced Web Designing / 140
13.7.2 Reading & Appending Data from a Text File
To read form a text, you first need to create an instance of the FileSystemObject
Object. You can use the Open Text File ( ) method to return an instance of the Text
Stream object.
<%
Set MyFileObject = Server. Create Object (“Scripting. File System Object”)
Set MyTextFile = MyFileObject.Open Text File (“c:\mydir\test.txt”)
WHILE NOT My TEXT File.AtEndofStream
Response. Write (MyTextFile.Read Line)
WEND
MyTextFile. Close
%>
This scripts reads everything form the text file named test. txt. It outputs the contents
of this file to the browser, if the file doesn’t exit, the error FILE Not Found is returned.
Sample Application
This section provides a sample application of the methods used for reading & writing
to files.
<%
IF NOT Request. Form (“NextLine”) = “a” THEN
Set MyFileObject = Server. Create Object (“Scripting.FileSystemObject”)
Set MyTextFile = MyFileObject.Open Text File (“c:\mydir\TheStory.txt”, B, TRUE)
MyTextFile.Write Line (Request. Form (“Next Line”)
MyTextFile.Close
END IF
<HTML>
<HEAD>
<TITLE> Only Story</TITLE>
<BODY>
<HR>
<%
Set MyFileObject = Server. Create Object (“Scripting.FileSystemObject”)
SetMyText File = MyFileObject.Open TextFile(“c:\mydir\TheStory.txt”)
WHILE NOT MyText FILE. AtEndofstream
Response .Write (“&nbsp;&nbsp;”&MyTextFile.ReadLine)
WEND
MyTextFile.Close
%>
<HR>
<H3> Enter a new line for the story: </H3>
<FORM METHOD = “POST” ACTION = “story.asp”>
<INPUT NAME = “NextLine” TYPE = “TEXT” SIZE= 70>
<INPUT TYPE = “SUBMIT” VALUE = “Submit Sentence”>
</FORM>
</BODY>
</HTML>
Active Server Page contains two scripts. The first scripts executes when a new
sentence has been submitted. The second script is used to display the contents of
the Story .txt file.
13.7.3 Retrieving the Attributes of Files
The ATTRIBUTE property requires some explanation this property returns a number
corresponds to the sum of the file attributes that have been set.
<HTML>
<HEAD>
Active Server Pages / 141
<TITLE> File Properties </TITLE>
</HEAD>
<BODY>
<%
Create an instance of the FileSystemObject object.
Set MyFileObject = Server.CreateObject (“Scripting. FileSystemObject”)
Create an instance of the File object.
Set a file = MyFIleObject.GetFile(“c:\test.txt”)
%>
<BR>Name: <%= afile.Name%>
<BR>Path: <%= afile.Path %>
<BR>Drive: <%= afile.Drive%>
<BR>Size: <%= afile.Size%>
<BR>Type: <%= afile.Type%>
<BR>Attributes: <%= afile. Attributes %>
<BR>Date Created: <%= afile. Date Created %>
<BR>Date Last Accessed: <%= afile. Date Last Accessed %>
<BR> Date Last Modify: <%= afile. Date Last Modify %>
Working with Drive
There is two objects that you can use to retrieve information about the drives on the
local machine: the FileSystemObject & Drive object. For e.g. the following Active
Server Page displays a list of all the drives on the server & their total size & available
size.
<HTML>
<HEAD>
<TITLE> Drive List </TITLE></HEAD>
<BODY>
<%
Create an instance of the FileSystemObject object
Set MyFileObject = Server. Create Object (“Scripting.FileSystemObject”)
Loop through the drives collection
FOR EACH thing in MyFileObject. Drives
%>
<BR> Drive Letter: <5= thing. Drive Letter%>
<BR>drive Total Size: <% = thing. Total Size %>
<BR> Drive Available Space:<% =thing . Available Space %>
<HR>
<%
NEXT
%>
</BODY>
</HTML>
Working with Folders
<HTML>
<HEAD>
<TITLE> Folder contents </TITLE></HEAD>
<BODY>
Create an instance of the FileSystemObject object
Set MyFileObject = Server. Create Object (“Scripting.FileSystemObject”)
Create a folder object
Set Myfolder = My FileObject. GetFolder (“c:myfolder”)
Loop through the files collection
FOER EACH thing in MyFolder.Files
Advanced Web Designing / 142
Response. Write (“<P>&thing “)
NEXT
%>
</BODY>
</HTML>
In above e.g., A folder object is created by using the GetFolder( ) method of the
FileSystemObject object. Once the Folder object is created, the FOR…. NEXT loop
is used to loop through its Files collection. The page displays all the files in this
collection.
13.2-13.6
Check your Progress
Fill in the blank
1. ............can be used to perform exactly same scripting task as VBScript.
2.After including the language directives in your Active Server Pages, You can create
Jscript by using that two special characters ............. and ...............
3.Microsoft introduced Active Server Pages transformed IIS from being mere server of
.................to being a server of .................
4.Main function of any web browser is to server.................
State True of False
1. The main purpose of the IIS was to server static HTML pages.
2. An active server page can contain server-side scripts.
3. To create Active Server Pages, You need special text editor.
4. Each visitor to your website is given same session.
13.8 DIFFERENCE BETWEEN JAVASCRIPT & VBSCRIPT
JavaScript:
1. JavaScript is case sensitive scripting language.
2. JavaScript is client scripting language; it is interpreted by a user’s browser.
3. JavaScript by is developed by Sun Microsystems.
4. JavaScript has cross-platform support from all popular browsers.
5. JavaScript is used for client side validation
6. JavaScript syntax uses curly braces to denote functions. JavaScript supports only
functions.
14. JavaScript is powerful to create custom object classes.
8. JavaScript is object-based, wraps core functionality in intrinsic objects like Date,
Math, Number, String, and Array
16. JavaScript supports to optional procedure argument.
VBScript:
1. Vbscript is not case sensitive scripting language.
2. VBScript is both client side and server-side scripting language; it is interpreted by
the server.
3. VBScript is developed by Microsoft.
4. VBScript is supported by MS IE only.
5. VBScript is used for server side validation
6. VBScript uses Function…End Function and Sub…End Sub. VBScript supports
functions and subroutines.
14. VBScript is less powerful to create custom object classes.
8. VBScript is less object-based, dumps functionality into global functions.
16. VBScript does not support to optional procedure argument.
Active Server Pages / 143
Check Your Progress - 13.8
Fill in the blanks
1) .............................is case sensitive scripting language.
2) JavaScript is .............................scripting language; it is interpreted by a user’s
browser.
3) .............................is supported by MS IE only.
4) VBScript is used for .............................side validation
13.9 SUMMARY
This chapter gives us the information about ASP. You will be able to write & execute
the ASP program. A session is something that starts the moment a user request a page
from your Web site & ends soon after the user levels. Each visitor to your Web site is
given individual session. Browser that supports cookies maintains one or more special
files. Certain cookies are temporary; others are persistent for e.g. the cookies are used by
Active Server Pages to track user sessions expire after a visitor leaves the Web site. An
application is defined by using the Internet Service Manager to specify a root directory for
the application. An application consists of a particular directory & all of its sub
directories.
The Global.asa file is an optional file that can contain declarations of objects, variables,
and methods that can be accessed by every page in an ASP application.
13.10 CHECK YOUR PROGRESS - ANSWERS
13.2-13.6
Fill in the blanks
1. Jscript.
2.<% and %>
3.Staic Content,dyamic content.
4.HTML file.
State True of False
1. TRUE.
2. TRUE.
3. FALSE
4. FALSE.
13.7
True or false on
1) True
2) True
3) True
4) True
13.8
Fill in the blanks on
1) JavaScript
2) Client
3) VBScript
4) Server
Advanced Web Designing / 144
13.11 QUESTIONS FOR SELF - STUDY
1. State difference between client side programming language and server side programming
language. ?
2. How will you define Array ?
3. Write short note on Active Server Pages ?
4. Explain the term Web Server.?
5. List out various Active Server Pages Components.
13. Write short note on 1.Session 2.Cookies 3.Application
13.12 SUGGESTED READINGS
1. ASP in 24 Hours - SAMS Teach yourself s
2. ASP in 21 days -SAMS Teach yourself E -Commerce Programming
3. www.w3schools.com
4. www.tizag.com
with ASP.
³³³
Active Server Pages / 145
NOTES
Advanced Web Designing / 146
Chapter 14
VB SCRIPT in ASP
123456789012345678901234567890121234
123456789012345678901234567890121234
14.0 Objectives
123456789012345678901234567890121234
123456789012345678901234567890121234
14.1 Introduction
123456789012345678901234567890121234
14.2 Client-Side and Server-Side Programming
123456789012345678901234567890121234
123456789012345678901234567890121234
Language.
123456789012345678901234567890121234
123456789012345678901234567890121234
14.3 Using Visual Basic Script with Active Server
123456789012345678901234567890121234
Pages.
123456789012345678901234567890121234
123456789012345678901234567890121234
14.4 Declaring Variables.
123456789012345678901234567890121234
14.5 If Conditions and Loops
123456789012345678901234567890121234
123456789012345678901234567890121234
14.5.1 Reporting Operations with For Loop.
123456789012345678901234567890121234
14.5.2 FOR EACH….NEXT.
123456789012345678901234567890121234
123456789012345678901234567890121234
14.6
Summary
123456789012345678901234567890121234
14.7 Check Your Progress - Answers
123456789012345678901234567890121234
123456789012345678901234567890121234
14.8 Questions for Self - Study
123456789012345678901234567890121234
123456789012345678901234567890121234
14.9 Suggested Readings
123456789012345678901234567890121234
123456789012345678901234567890121234
14.0
OBJECTIVES
Dear friends,
After learning this software you will know the use of VBScript and will be able to
• Explain concept client-server side programming.
• Describe Creating an ASP Pages.
• Make Use of all the Loops.
14.1
INTRODUCTION TO VB SCRIPT
VB script is closely related to the BASIC programming language. VB script is
simplest version of Microsoft’s Visual Basic for application.
VB script is scripting language. This means that the language is both easier & the harder
to use than a full-fledged version of BASIC. A scripting language is typically easier to use
when creating simple program. The syntax of the language itself is simple. However, this
simplified syntax can actually make larger application more difficult to develop.
You can create VB script directly into HTML files. This allows you to extend
HTML into something more than a page-formatting language. Pages with VB script can
change every time they’re loaded into browser. They can also respond intelligently to
user actions.
VB script is the default language of Active Server Pages. Other scripting languages
with Active Server Pages such as Perl, JS script.
14.2 CLIENT-SIDE & SERVER-SIDE PROGRAMMING LANGUAGE
VB script acts as both a client-side & server-side programming language.
Client-Side Programming Language:
A client-side is programming language is language that can be interpreted & executed by
a browser. When a program is written in any of these language is loaded into a browser,
the browser will automatically execute the program.
Advantage
a)
The advantage of client-side language is that browsers do all work.
b)
This places less of burden on the server.
c)
Client-side is programs much faster than Server side programs.
d)
A response doesn’t have to be fetched over the network. The client-side programs
can respond.
VB SCRIPT in ASP / 147
Server-Side Programming Language:
VB script is also a server-side programming language. A sever-side programming language
is a language that executes on the server that serves a Web site’s files, rather than on
the browsers that receives those files. A server-side programming language performs all
the work on your Web site’s computer.
When you create Active Server Pages, you’ll be using VB script as a server-side
programming language.
Disadvantage:
a) This places more of burden on the user.
Advantage
a)
b)
The advantage of using VB script as a server-side programming language is that the
scripts work regardless of the browser being used.
The scripts are processed before the pages are sent our across the Internet to the
browsers. Web browser receives nothing but more than normal HTML files.
14.3 USING VISUAL BASIC SCRIPTS WITH ACTIVE SERVER PAGES
It helps us to learn how to create Active Server Pages that can execute Visual Basic
Scripts. You must save the files in a directory of your Web sever. For e.g. you can save
the files in the “wwwroot” directory. For the scripts to execute, the page must be located
in a directory that can be accessed by your Web Server.
When you load an Active Server Page, you shouldn’t load the file directly from disk. For
e.g. if you save an Active Server Page as c:\ InetPub\wwwroot\mypage .asp, you shouldn’t
load the file into your browser by typing this path in the address bar. Request the file by
using your Web server instead.
14.4 DECLARING VARIABLES
You don’t need to explicitly declare a variable before you use it in your Visual Basic
scripts. For :
<HTML>
<HEAD>
<TITLE> Simple VB script </TITLE>
</HEAD>
<BODY>
<%myvar = “Hello World !!” %>
<%= myvar%>
</BODY>
</HTML>
In this e.g., the variable myvar is never declared. However, it is assigned the value “Hello
World!!”& The value is outputted to the browser. This works fine & won’t result in an error.
However, if you’re creating long or complicated programs, you may choose to require
variables to be declared. The advantage of doing this is that it makes your scripts easier
to debug. If you mistype the variable name, an error is generated. Following e.g.
shows how you can force variables to be explicitly declared:
<%OPTION EXPLICIT%>
<HTML>
<HEAD>
<TITLE>> Simple VB script </TITLE>
</HEAD>
<BODY>
<%
DIM myvar
myvar = “Hello World”
%>
Advanced Web Designing / 148
<% = myvar %>
</BODY>
</HTML>
In this e.g., the OPTION EXPLICIT statement forces all variables explicitly declared. The
DIM statement declares variable myvar. If you neglect to declare this variable, you receive
the error Variable is undefined: ‘myvar’.
14.5 IF CONDITIONS AND LOOPS
Testing for a Single Condition with IF ……THEN
One of the most useful statement is IF…THEN statement. The following e.g. shows how
to use it:
<%
IF TIME > # 5: 00: 00 PM # THEN
Greeting = “Good Evening!!!”
END IF
%>
This script assigns the value “ Good Evening” to the variable Greeting only if it’s after 5:00
p.m. (the # characters are used to delimit a date or time literal). Notice the expression
END IF. The END IF expression designates the end of the conditional block code. You
can place more than one statement before END IF expression as shown:
<%
IF TIME > # 5: 00: 00 PM # THEN
Greeting = “Good Evening!!!”
Evening _Visitor = Evening _ Visitor + 1
END IF
%>
Both statements in this e.g. executes only if the time is after 5:00 p.m.
Statement that follow the ELSE expression execute only if the conditional is false.
For e.g.
<%
IF TIME > # 5: 00: 00 PM # THEN
Greeting = “Good Evening!!!”
ELSE
Greeting = “Good some other time!!!”
END IF
%>
You can also use the multiple statements after the ELSE statement. You can also
nest conditionals. For e.g.
<%
IF TIME > # 5: 00: 00 PM # THEN
IF TIME < # 10: 00: 00 PM # THEN
Greeting = “Good Evening!!!”
ELSE
Greeting = “Good Late Evening!!!”
END IF
ELSE
Greeting = “Good some other time!!!”
END IF
%>
In this example, the greeting is Good Evening!!! If it’s before 10:00 p.m., but Good
Late Evening!!! If it’s later. If it’s not after 5:00, the greeting Good some other time!!!
Is used instead.
If you need to execute a single statement with a conditional, then you don’t need to
use the END IF expression for e.g.
VB SCRIPT in ASP / 149
<%
IF TIME < # 5:00:00 PM # THEN Greeting = “Good Day!!!”
%>
14.5.1 Repeating Operations with FOR Loop
When You need to repeat a group of ststements set number of times, you
can use a FOR ....NEXT loop. For e.g.
<%
FOR i=1 to 500
%>
Hello Again!!!
<%
NEXT
%>
In this example, the sentence Hello Again!!! Is printed to the browser screen 500
times. Anything contained between the FOR statement & the NEXT statement is
repeated.
You can make a FOR…NEXT loop move backwards by using the keyword STEP.
Consider the following e.g.
<%
FOR i =500 to 1 STEP –1
%>
Hello Again!!!
<%
NEXT
%>
In this e.g. FOR… NEXT loop starts with the number 500 & steps backwards to the
number 1.
You can step through a loop with different-sized steps. In the following e.g., the value
of the i variable is incremented by 10 at each step:
<%
FOR i =1 to 500 STEP 10
%>
<% = i %><BR>
<%
NEXT
%>
You can use the statement EXIT FOR to exit out of a FOR…NEXT loop.
If the value of one elements of the array matches the expression “Running Shoes”,
the FOR…. NEXT loop is immediately exited. The value of i variable equals the index
of the matched elements in the array. For e.g
<%
DIM myarray (10)
myarray (4) = “Running Shoes”
For i =0 to UBOUND ( Myarray)
If Myarray (i) = “Running Shoes” THEN EXIT FOR
NEXT
%>
14.5.2 FOR EACH…NEXT
The FOR EACH…. NEXT statement is closely related to the FOR…NEXT statement.
The FOR EACH….NEXT statement is particularly appropriate for stepping through
the elements of an array or a collection. For e.g.
<%
DIM myarray (10)
myarray (4) = “Running Shoes”
Advanced Web Designing / 150
FOR EACH i in myarray
If i = “Running Shoes” THEN EXIT FOR
NEXT
%>
if you want to display the values of all elements of an array, you could do like this:
<%
FOR EACH i in Myarray
%>
<% = i %>
<%
NEXT
%>
Check your Progress - 14.1-14.5
Fill in the blanks
1. .......................is closely related to BASIC programming Language.
2. VBScript acts as both .......................and .......................Programming Language.
3. Server side language is executed at .......................
4. You can create .......................directly into HTML file.
State True of False
1.VBScript is not server-side programming language.
2.Option Explicit statement forces all variables explicitly declared.
3.The advantage of client-side language is that browser do all work .
4.Server-Side program is much faster than client-side programs.
14.6 SUMMARY
Is a comprehensive survey of VBScript.You can learned use of VBScript variables,
Operators,data function and string function.You learn also the use loops.Also you
know the use of VBScript in ASP pages.
14.7 CHECK YOUR PROGRESS- ANSWERS
14.1,14.2,14.3,14.4,14.5
Fill in the blanks
1.VBScript. 2.Client-side and server-side.
3.Server.
4.VBScript.
State True of False
1.FALSE.
2.TRUE.
3.TRUE.
4.FALSE.
14.8 QUESTIONS FOR SELF - STUDY
1.
2.
3.
4.
Explain client and server. ?
How will you define variable in VB Script ?
Explain with example if condition ?
Write short note on loops in VB Script ?
14.9 SUGGESTED READINGS
1. ASP 3.0 - wrox publication
2. ASP in 21 days -SAMS Teach yourself E -Commerce Programming with ASP.
3. www.w3schools.com
4. www.html.net
VB SCRIPT in ASP / 151
NOTES
Advanced Web Designing / 152
Chapter 15
ASP Intrinsic Objects
123456789012345678901234567890121234567
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.0 Objectives
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.1 Introduction
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.2 Response Object
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.3 Request Object
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.4 ASP Application Object
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.4.1 Store and Retrieve Application Variables
123456789012345678901234567890121234567
15.4.2 Loop through the Contents Collection
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.4.3 Lock and Unlock
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.5 ASP Session Object
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.6 ASP Server Object
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.7 The ASP Error Object
123456789012345678901234567890121234567
15.8 ASP Cookies
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.9 Summary
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.10 Check Your Progress-Answers
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.11 Questions for Self - Study
123456789012345678901234567890121234567
123456789012345678901234567890121234567
15.12 Suggested Readings
123456789012345678901234567890121234567
15.0 OBJECTIVES
Dear Friends,
After learning this chapter you will be able to
l
Explain ASP Request objects and ASP session Objects
l
Describe creation and use of cookies
l
Study how to Loop through the Contents Collection
15.1 INTRODUCTION
ASP provides a rich set of intrinsic objects. You can use intrinsic objects without
instantiating them
Each object has a set of properties and methods. Properties exhibit attributes of
object whereas methods contain functionality offered by object
ASP intrinsic objects include Session, Application, Server, Request, Response,
Error and ObjectContext objects
In addition to ASP intrinsic objects you can use other objects in ASP. However
objects other than intrinsic objects are needed to be instantiated before using
15.2 RESPONSE OBJECT
The ASP Response object is used to send output to the user from the server. Its
collections, properties, and methods are described below:
Collections
Collection
Cookies
Description
Sets a cookie value. If the cookie does
not exist, it will be created, and take the
value that is specified
ASP Intrinsic Objects / 153
Properties
Property
Buffer
CacheControl
Charset
ContentType
Expires
ExpiresAbsolute
IsClientConnected
Pics
Status
Methods
Method
AddHeader
AppendToLog
BinaryWrite
Clear
End
Flush
Redirect
Write
Description
Specifies whether to buffer the page output or not
Sets whether a proxy server can cache the output generated by
ASP or not
Appends the name of a character-set to the content-type header
in the Response object
Sets the HTTP content type for the Response object
Sets how long (in minutes) a page will be cached on a browser
before it expires
Sets a date and time when a page cached on a browser will
expire
Indicates if the client has disconnected from the server
Appends a value to the PICS label response header
Specifies the value of the status line returned by the server
Description
Adds a new HTTP header and a value to the HTTP response
Adds a string to the end of the server log entry
Writes data directly to the output without any character conversion
Clears any buffered HTML output
Stops processing a script, and returns the current result
Sends buffered HTML output immediately
Redirects the user to a different URL
Writes a specified string to the output
Check your Progress - 15.1 - 15.2
TRUE OR FALSE
1) ASP provides a rich set of intrinsic objects. You can use intrinsic objects without
instantiating them (ans:true)
2) The ASP Response object is used to send output to the user from the server (ans:
true)
15.3 REQUEST OBJECT
When a browser asks for a page from a server, it is called a request. The Request
object is used to get information from a visitor. Its collections, properties, and methods
are described below:
Collections
Collection
ClientCertificate
Cookies
Form
QueryString
ServerVariables
Description
Contains all the field values stored in the client certificate
Contains all the cookie values sent in a HTTP request
Contains all the form (input) values from a form that uses the post
method
Contains all the variable values in a HTTP query string
Contains all the server variable values
Advanced Web Designing / 154
Properties
Property
TotalBytes
Methods
Method
BinaryRead
Description
Returns the total number of bytes the client sent in the body of the
request
Description
Retrieves the data sent to the server from the client as part of a
post request and stores it in a safe array
15.4 ASP APPLICATION OBJECT
A group of ASP files that work together to perform some purpose is called an
application. The Application object is used to tie these files together.
An application on the Web may consists of several ASP files that work together to
perform some purpose. The Application object is used to tie these files together. The
Application object is used to store and access variables from any page, just like the
Session object. The difference is that ALL users share ONE Application object (with
Sessions there is ONE Session object for EACH user). The Application object holds
information that will be used by many pages in the application (like database connection
information). The information can be accessed from any page. The information can also
be changed in one place, and the changes will automatically be reflected on all pages.
The Application object’s collections, methods, and events are described below:
Collections
Collection
Description
Contents
Contains all the items appended to the application through
a script command
StaticObjects
Contains all the objects appended to the application with
the HTML <object> tag
Methods
Method
Description
Contents.Remove
Deletes an item from the Contents collection
Contents.RemoveAll()
Deletes all items from the Contents collection
Lock
Prevents other users from modifying the variables in the
Application object
Unlock
Enables other users to modify the variables in the
Application object (after it has been locked using the Lock
method)
Events
Event
Description
Application_OnEnd
Occurs when all user sessions are over, and the application
ends
Application_OnStart
Occurs before the first new session is created (when the
Application object is first referenced)
ASP Intrinsic Objects / 155
15.4.1 Store and Retrieve Application Variables
Application variables can be accessed and changed by any page in an application.
You can create Application variables in “Global.asa” like this:
<script language=”vbscript” runat=”server”>
Sub Application_OnStart
application(“vartime”)=””
application(“users”)=1
End Sub
</script>
In the example above we have created two Application variables: “vartime” and “users”.
You can access the value of an Application variable like this:
<%
Response.Write(Application(“users”))
%>
active connections.
15.4.2 Loop Through the Contents Collection
The Contents collection contains all application variables. You can loop through the
Contents collection, to see what’s stored in it:
<%
dim i
For Each i in Application.Contents
Response.Write(i & “<br />”)
Next
%>
If you do not know the number of items in the Contents collection, you can use the
Count property
<%
dim i
dim j
j=Application.Contents.Count
For i=1 to j
Response.Write(Application.Contents(i) & “<br />”)
Next
%>
15.4.3 Lock and Unlock
You can lock an application with the “Lock” method. When an application is locked,
the users cannot change the Application variables (other than the one currently accessing
it). You can unlock an application with the “Unlock” method. This method removes the
lock from the Application variable:
<%
Application.Lock
‘do some application object operations
Application.Unlock
%>
Advanced Web Designing / 156
Check your Progress - 15.3 - 15.4
True or false
1) The Request object is used to get information from a visitor.
2) You can lock an application with the “Lock” method.
15.5 ASP SESSION OBJECT
A Session object stores information about, or change settings for a user session.
Session Object
When you are working with an application on your computer, you open it, do some
changes and then you close it. This is much like a Session. The computer knows who
you are. It knows when you open the application and when you close it. However, on the
internet there is one problem: the web server does not know who you are and what you
do, because the HTTP address doesn’t maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is
sent to the user’s computer and it contains information that identifies the user. This
interface is called the Session object. The Session object stores information about, or
change settings for a user session. Variables stored in a Session object hold information
about one single user, and are available to all pages in one application. Common information
stored in session variables are name, id, and preferences. The server creates a new
Session object for each new user, and destroys the Session object when the session
expires.
The Session object’s collections, properties, methods, and events are described
below:
Collections
Collection
Description
Contents
Contains all the items appended to the session through a
script command
StaticObjects
Contains all the objects appended to the session with the
HTML <object> tag
Properties
Property
Description
CodePage
Specifies the character set that will be used when displaying
dynamic content
LCID
Sets or returns an integer that specifies a location or region.
Contents like date, time and currency will be displayed
according to that location or region
SessionID
Returns a unique id for each user. The unique id is generated
by the server
Timeout
Sets or returns the timeout period (in minutes) for the Session
object in this application
ASP Intrinsic Objects / 157
Methods
Method
Description
Abandon
Destroys a user session
Contents.Remove
Deletes an item from the Contents collection
Contents.RemoveAll()
Deletes all items from the Contents collection
Events
Event
Description
Session_OnEnd
Occurs when a session ends
Session_OnStart
Occurs when a session starts
When does a Session Start?
A session starts when:
•
A new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure
•
A value is stored in a Session variable
•
A user requests an ASP file, and the Global.asa file uses the <object> tag to
instantiate an object with session scope
When does a Session End?
A session ends if a user has not requested or refreshed a page in the application for a
specified period. By default, this is 20 minutes.
If you want to set a timeout interval that is shorter or longer than the default, use the
Timeout property.
The example below sets a timeout interval of 5 minutes:
<%
Session.Timeout=5
%>
Use the Abandon method to end a session immediately:
<%
Session.Abandon
%>
Note: The main problem with sessions is WHEN they should end. We do not know if the
user’s last request was the final one or not. So we do not know how long we should keep
the session “alive”. Waiting too long for an idle session uses up resources on the server,
but if the session is deleted too soon the user has to start all over again because the
server has deleted all the information. Finding the right timeout interval can be difficult!
Tip: Only store SMALL amounts of data in session variables!
Store and Retrieve Session Variables
The most important thing about the Session object is that you can store variables in
it.
Advanced Web Designing / 158
The example below will set the Session variable username to “Donald Duck” and
the Session variable age to “50”:
<%
Session(“username”)=”Donald Duck”
Session(“age”)=50
%>
When the value is stored in a session variable it can be reached from ANY page in
the ASP application:
Welcome <%Response.Write(Session(“username”))%>
The line above returns: “Welcome Donald Duck”.
You can also store user preferences in the Session object, and then access that
preference to choose what page to return to the user.
The example below specifies a text-only version of the page if the user has a low
screen resolution:
<%If Session(“screenres”)=”low” Then%>
This is the text version of the page
<%Else%>
This is the multimedia version of the page
<%End If%>
15.6 ASP SERVER OBJECT
The Server object is used to access properties and methods on the server.
The ASP Server object is used to access properties and methods on the server.
Its properties and methods are described below:
Properties
Property
Description
ScriptTimeout
Sets or returns the maximum number of seconds a script can run
before it is terminated
Methods
Method
Description
CreateObject
Creates an instance of an object
Execute
Executes an ASP file from inside another ASP file
GetLastError()
Returns an ASPError object that describes the error condition
that occurred
HTMLEncode
Applies HTML encoding to a specified string
MapPath
Maps a specified path to a physical path
Transfer
Sends (transfers) all the information created in one ASP file to a
second ASP file
URLEncode
Applies URL encoding rules to a specified string
ASP Intrinsic Objects / 159
Check your Progress - 15.5 - 15.6
True or false
1) A new user requests an ASP file, and the Global.asa file includes a Session_OnStart
procedure
2) The cookie is sent to the user’s computer and it contains information that identifies
the user
3) The ASPError object displays information about errors in scripts.
15.7 THE ASPERROR OBJECT
The ASPError object displays information about errors in scripts. The ASPError
object was implemented in ASP 3.0 and is available in IIS5 and later. The ASPError
object is used to display detailed information of any error that occurs in scripts in an ASP
page.
Note: The ASPError object is created when Server.GetLastError is called, so the error
information can only be accessed by using the Server.GetLastError method. The
ASPError object’s properties are described below (all properties are read-only):
Properties
Property
Description
ASPCode
Returns an error code generated by IIS
ASPDescription
Returns a detailed description of the error (if the error is ASPrelated)
Category
Returns the source of the error (was the error generated by ASP?
By a scripting language? By an object?)
Column
Returns the column position within the file that generated the error
Description
Returns a short description of the error
File
Returns the name of the ASP file that generated the error
Line
Returns the line number where the error was detected
Number
Returns the standard COM error code for the error
Source
Returns the actual source code of the line where the error ccurred
15.8 ASP COOKIES
A cookie is often used to identify a user.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user’s computer. Each time the same computer requests a page with a
browser, it will send the cookie too. With ASP, you can both create and retrieve cookie
values.
How to Create a Cookie?
The “Response.Cookies” command is used to create cookies.
Note: The Response.Cookies command must appear BEFORE the <html> tag.
Advanced Web Designing / 160
In the example below, we will create a cookie named “firstname” and assign the value
“Suraj” to it:
<%
Response.Cookies(“firstname”)=”Suraj”
%>
It is also possible to assign properties to a cookie, like setting a date when the
cookie should expire:
<%
Response.Cookies(“firstname”)=”Suraj”
Response.Cookies(“firstname”).Expires=#April 10,2009#
%>
How to Retrieve a Cookie Value?
The “Request.Cookies” command is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named “firstname” and
display it on a page:
<%
fname=Request.Cookies(“firstname”)
response.write(“Firstname=” & fname)
%>
Output: Firstname=Alex
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support cookies, you will have to
use other methods to pass information from one page to another in your application.
There are two ways of doing this:
1. Add parameters to a URL
You can add parameters to a URL:
<a href=”welcome.asp?fname=John&lname=Smith”>Go to Welcome Page</a>
And retrieve the values in the “welcome.asp” file like this:
<%
fname=Request.querystring(“fname”)
lname=Request.querystring(“lname”)
response.write(“<p>Hello “ & fname & “ “ & lname & “!</p>”)
response.write(“<p>Welcome to my Web site!</p>”)
%>
<%
fname=Request.querystring(“fname”)
lname=Request.querystring(“lname”)
response.write(“<p>Hello “ & fname & “ “ & lname & “!</p>”)
response.write(“<p>Welcome to my Web site!</p>”)
%>
ASP Intrinsic Objects / 161
2. Use a form
You can use a form. The form passes the user input to “welcome.asp” when the
user clicks on the Submit button:
<form method=”post” action=”welcome.asp”>
First Name: <input type=”text” name=”fname” value=”” />
Last Name: <input type=”text” name=”lname” value=”” />
<input type=”submit” value=”Submit” />
</form>
Retrieve the values in the “welcome.asp” file like this:
<%
fname=Request.form(“fname”)
lname=Request.form(“lname”)
response.write(“<p>Hello “ & fname & “ “ & lname & “!</p>”)
response.write(“<p>Welcome to my Web site!</p>”)
%>
Remove Session Variables
The Contents collection contains all session variables.
It is possible to remove a session variable with the Remove method.
The example below removes the session variable “sale” if the value of the session variable
“age” is lower than 18:
<%
If Session.Contents(“age”)<18 then
Session.Contents.Remove(“sale”)
End If
%>
To remove all variables in a session, use the RemoveAll method:
<%
Session.Contents.RemoveAll()
%>
Loop Through the Contents Collection
The Contents collection contains all session variables. You can loop through the
Contents collection, to see what’s stored in it:
<%
Session(“username”)=”Donald Duck”
Session(“age”)=50
dim i
For Each i in Session.Contents
Response.Write(i & “<br />”)
Next
%>
<%
Advanced Web Designing / 162
Session(“username”)=”Donald Duck”
Session(“age”)=50
dim i
For Each i in Session.Contents
Response.Write(i & “<br />”)
Next
%>
Result:
username
age
If you do not know the number of items in the Contents collection, you can use the
Count property :
<%
dim i
dim j
j=Session.Contents.Count
Response.Write(“Session variables: “ & j)
For i=1 to j
Response.Write(Session.Contents(i) & “<br />”)
Next
%>
Result:
Session variables: 2
Donald Duck
50
Loop Through the StaticObjects Collection
You can loop through the StaticObjects collection, to see the values of all objects
stored in the Session object:
<%
dim i
For Each i in Session.StaticObjects
Response.Write(i & “<br />”)
Next
%>
Check your progress - 15.7 - 15.8
Fill in the blanks on
1) The “Request.Cookies” command is used to retrieve a ..................value
2) The Contents collection contains all ..................variables.
3) A ..................is often used to identify a user.
ASP Intrinsic Objects / 163
15.9 SUMMARY
ASP provides a rich set of intrinsic objects. You can use intrinsic objects without
instantiating them
Each object has a set of properties and methods. Properties exhibit attributes of
object whereas methods contain functionality offered by object
ASP intrinsic objects include Session, Application, Server, Request, Response and
Object Context & error objects.
The ASP Response object is used to send output to the user from the server. The
Request object is used to get information from a visitor.
A group of ASP files that work together to perform some purpose is called an
application. The Application object is used to tie these files together.
The difference is that ALL users share ONE Application object (with Sessions there
is ONE Session object for EACH user). Variables stored in a Session object hold
information about one single user, and are available to all pages in one application.
Common information stored in session variables is name, id, and preferences.
The Server object is used to access properties and methods on the server
15.10 CHECK YOUR PROGRESS- ANSWERS
15.1 - 15.2
1) True
2) True
15.3 - 15.4
1) True
2) True
15.7 - 15.8
1) Cookie
2) Session
3) Cookie
15.11 QUESTIONS FOR SELF - STUDY
1) Short note on Store and Retrieve Application Variables.
2) Explain Session and Cookies.
3) Write a short note on concept: Lock and Unlock.
15.12 SUGGESTED READINGS
1. ASP 3.0 - wrox publication
2. ASP in 21 days -SAMS Teach yourself E -Commerce Programming with ASP.
3. www.w3schools.com
4. www.html.net
³³³
Advanced Web Designing / 164
NOTES
ASP Intrinsic Objects / 165
NOTES
Advanced Web Designing / 166
Chapter 16
ActiveX Data Objects
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.0 Objectives
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.1 Overview of the ActiveX Data Objects.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.2 Using the ActiveX Data Objects to Stored and
12345678901234567890123456789012123456789
Retrieve Data From a Database.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.3 Opening and Closing a Database Connection .
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.4 Executing SQL Statements with and Open Connection.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.5 Using a Record Set to Display Record
12345678901234567890123456789012123456789
16.5.1 Displaying all the Records and Rows in a Table.
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.5.2 Using Command Object
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.6
Summary
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.7 Check Your Progress- Answers
12345678901234567890123456789012123456789
16.8 Questions For Self - Study
12345678901234567890123456789012123456789
12345678901234567890123456789012123456789
16.9 Suggested Readings
12345678901234567890123456789012123456789
16.0 OBJECTIVES
After learning this chapter you should be able to
•
Learn the concept of ActiveX Data Objects.
•
Explain Store and retrieve the data from database.
•
Describe Connectivity of database.
•
Describe Execution of structured Query Language and Concept of recordset.
16.1 INTRODUCTION
Microsoft’s ActiveX Data Objects (ADO) is a set of Component Object Model (COM)
objects for accessing data sources. A part of MDAC, it provides a middleware layer
between programming languages and OLE DB (a means of accessing data stores, whether
they be databases or otherwise, in a uniform manner). ADO allows a developer to write
programs that access data without knowing how the database is implemented. You must
be aware of your database for connection only. No knowledge of SQL is required to
access a database when using ADO, although one can use ADO to execute SQL
commands. The disadvantage of this (i.e. using SQL directly) is that it introduces a
dependency upon the type of database used
16.2 USING THE ACTIVEX DATA OBJECTS TO STORE & RETRIEVE
DATA FROM A DATABASE
<HTML>
<HEAD>
<TITLE> ADO Example </TITLE></HEAD>
<BODY>
<%
Set MyConn = Server.CreateObject (“ADODB.Connection”)
MyConn.Open “FILEDSN = d:\Program Files \Common Files \ODBC
\DataSource\Mydata.dsn”
MyConn.Open.Execute “INSERT MyTable (Mycolumn) VALUES (Hello World!”)
Set RS = MyConn .Execute (“SELECT* FROM MyTable”)
Response . write (RS(“MyColumn”))
MyConn.close
ActiveX Data Objects / 167
%>
</BODY>
</HTML>
In above e.g. you need to create a table named Mytable. You can do this by using
ISQL/w. Launch the program, select your default database, & execute the following
SQL statement:
Create Table MyTable (MyColumn VARCHAR (255))
16.3 OPENING & CLOSING A DATABASE CONNECTION
To open a connection with a database, you can create an instance of the Connection
object. Once an instance of this object is created, you can call the Open method of
the Connection object to actually open the connection. For e.g.
<%
Set MyConn = Server. Create Object (“ADODB.Connection)
MyConn.Open “FILEDSN =d:\Program Files \Common Files\ODBC\Data Source
\MyData.dsn”
MyConn. Execute “INSERT MyTable (Mycolumn) VALUES (“”Hello World”)
MyConn . Close
%>
16.4 EXECUTING SQL STATEMENTS WITH AN OPEN CONNECTION
You can execute method to return results from a SQL query. e.g.
<%
Set MyConn = Server. Create Object (“ADODB.Connection”)
MyConn.Open “FILEDSN =d:\Program Files \Common Files\ODBC\Data Source
\MyData.dsn”
Set RS = MyConn .Execute (“SELECT* FROM MyTable”)
MyConn . Close
%>
In this e.g. the Execute ( ) method is used to return the results from SQL SELECT
query. Parentheses are used with this Execute method.
Creating Transaction
<%
Set MyConn = Server. Create Object (“ADODB.Connection”)
MyConn.Open “FILEDSN =d:\Program Files \Common Files\ODBC\Data Source
\MyData.dsn”
MyConn. BeginTrans
MyConn. Execute “INSERT Credit Card (CCNum) VALUES (‘5555-55-555-55-5555’)”
MyConn.Execute “INSERT Shipping (Address) VALUES (‘Paris, France’)”
MyConn.CommitTrans
MyConn.Close
%>
In this e.g., the BeginTrans & CommitTrans methods are used to mark the beginning
& end of transaction.
16.5 USING A RECORDSET TO DISPLAY RECORDS
A Recorset can be used to represent the records in a database table. Like a table, a
Recordset contains one or more records (rows). Each record contains one or more
filed (columns).
<%
Set MyConn = Server. Create Object (“ADODB.Connection”)
Advanced Web Designing / 168
MyConn.Open “FILEDSN =d:\Program Files \Common Files\ODBC\Data Source
\MyData.dsn”
Set RS = MyConn .Execute (“SELECT* FROM MyTable”)
RS. Close
MyConn . Close
%>
In this e.g., a SQL SELECT statement is used to retrieve the entire records from a
table named MyTable. The EXECUTE ( ) method returns a Recordset.
Each record in the RS Recordset corresponds to a record in the MyTable table. To
display all the records in the Recordset, you can simply loop through the records, as
in following e.g.
<%
Set MyConn = Server. Create Object (“ADODB.Connection”)
MyConn.Open “FILEDSN =d:\Program Files \Common Files\ODBC\Data Source
\MyData.dsn”
WHILE NOT RS.EOF
Response. Write (“<BR>” & RS (“MyCoumn”))
RS.MoveNext
WEND
RS.Close
MyConn.Close
%>
16.5.1 Displaying all the records & rows in a table
<HTML>
<HEAD>
<TITLE> ADO Example </TITLE>
</HEAD>
<BODY>
<%
Set MyConn = Server.CreateObject (“ADODB.Connection”)
MyConn.Open “FILEDSN = d:\Program Files \Common Files \ODBC
\DataSource\Mydata.dsn”
Set RS = MyConn .Execute (“SELECT* FROM MyTable”)
%>
<TABLE ORDER=1>
<TR>
<%FOR i=0 to RS. Fields. Count – 1%>
<TH> <%= RS(i) .Name%> </TH>
<%Next%>
</TR>
<%While Not RS.EOF%>
<TR.
<% FOR i = 0 TO RS.Fields. Count – 1%>
<TD> <% = RS(i)%> </td>
<%NEXT%>
</TR>
<%
RS.MoveNext
WEND
RS.Close
MyConn.Close.
%>
</TABLE>
</BODY>
</HTML>
ActiveX Data Objects / 169
16.5.2 Using Command Object
<! ——#INCLUDE VIRTUAL = “ADOVBS.inc”—>
<%
Set MyConn = Server.CreateObject (“ADODB.Connection”)
Set MyConn = Server.CreateObject (“ADODB.Command”)
MyConn.Open “FILEDSN = d:\Program Files \Common Files \ODBC
\DataSource\Mydata.dsn”
Set MyCommand .ActiveConnection = MyConn
MyCommand.commandText = UPDATE MyTable SET MyColumn = ‘Hello’
MyCommand.commandType = adCMDText
MyCommand.Execute
MyConn. Close
%>
In this e.g., an instance of the command object is created. The Active Connection
property associates the Command with an open connection. The Command Text
property specifies which SQL statement will be executed.
Command object with a preexisting Recordset
<! ——#INCLUDE VIRTUAL = “ADOVBS.inc”—>
<%
Set MyConn = Server.CreateObject (“ADODB.Connection”)
Set MyConn = Server.CreateObject (“ADODB.Command”)
Set RS = Server.CreateObject (“ADODB.Recordset “)
MyConn.Open “FILEDSN = d:\Program Files \Common Files \ODBC
\DataSource\Mydata.dsn”
Set MyCommand. Active Connection = MyConn
MyCommand.Command Text = “SELECT * FROM MyTable”
MyCommand. CommandType = adcCMDText
RS.Open MyCommand,,adOpenStatic,adLockOptimistic
RS.Close
MyConn.close
%>
Check your Progress - 16.1- 16.5
Fill in the blanks
1. Using .......................you can store and retrieve data from a variety of data providers..
2. The Activex Data Objects consists of .......................independent objects.
3. To open a connection with a database ,you can create an .......................the
connection object.
4. A .......................can be used to represent the records in a database table.
State True of False
1. A record set can be used to represent the records in a database table.
2. To open a connection with a database ,you can create an instance of the connection
object ..
3. You cant’t specify recordset’s cursor and locking type.
4. Each visitor to your website is given same session.
Advanced Web Designing / 170
16.6 SUMMARY
The advantage of passing a command object to a preexisting recordset is that
you can specify the recordset’s cursor and locking type. The command object is used to
open a recordset that uses a static cursor and optimistic locking.
It introduced the Activex data objects.You learned how use the ADO connection
object. To execute SQL stored procedures. You Learned how to pass and retrieve input
parameters ,put parameters and return values.
16.7 CHECK YOUR PROGRESS - ANSWERS
16.1-16.5
Fill in the blanks
1.ADO.
2.Seven.
3.instance of.
4.record set.
State True of False
1.TRUE.
2.TRUE.
3.FALSE.
16.8 QUESTIONS FOR SELF - STUDY
1. Write commands to do the following.
a.
b.
Create a table ‘student’ along with field name– rollno, name,marks ?
Display all records ?
16.9 SUGGESTED READINGS
1. ASP 3.0 - wrox publication
2. ASP in 21 days -SAMS Teach yourself E -Commerce Programming with ASP.
3. www.w3schools.com
4. www.html.net
ActiveX Data Objects / 171
NOTES
Advanced Web Designing / 172