Você está na página 1de 638

Web Development

ITM 4132

Internet and W3
By Pramudith Kandambi

© Pramudith_Kandambi Rajarata_University BIT_2009


Evaluation Criteria

„ Continues assessment 20%


‰ Assessment I
‰ Assessment II
‰ Micro Project

„ Semester Examination 80%

© Pramudith_Kandambi Rajarata_University BIT_2009


Web Development
ITM 4132
„ Topics to be covered:

‰Introduction
‰HTML/XHTML
‰Cascading Style Sheets (CSS)
‰JavaScript: Object-Based Scripting for the Web
‰Dynamic HTML
‰Web Servers
‰PHP: Database Programming

„ Self Study Packages:

‰Adobe Photoshop: Creating Web Graphics


‰Macromedia Flash: Building Interactive Animations
‰Macromedia Dreamweaver

„ References:

‰Internet & WWW, 3rd ed, 2005 - Deitel & Deitel


‰PHP and MySQL Web Development - Luke Welling Laura Thomson

© Pramudith_Kandambi Rajarata_University BIT_2009


What is internet

„ The Internet is a network of computer


networks.

„ It makes it possible for any computer


connected to it to send and receive data from
any other computer connected to it.

© Pramudith_Kandambi Rajarata_University BIT_2009


What is Web

„ Using Internet transferring Fils, Data ect.


What is a Network?

„ A group of two or more devices, that are


able to communicate with one another:

‰ The telephone network: interconnection of


telephones and switches
‰ Computer networks: interconnection of
computers
‰ Between two and millions of devices
interconnected

© Pramudith_Kandambi Rajarata_University BIT_2009


How it works
„ Computer Networks
„ The computers in a network are connected via
‰ hardware and software

„ Hardware
Physically connects the computers together
telephone lines, fiber-optic cables, routers and
gateways, and the computers themselves

„ Software
Enables communication and exchange of information,
by following a set of rules, called protocols

© Pramudith_Kandambi Rajarata_University BIT_2009


Internet Protocols

„ A protocol is a standard set of rules that


determines how computers communicate
with each other across networks

„ A protocol describes:
‰ the format that a message must take
‰ the way in which computers must exchange a
message

© Pramudith_Kandambi Rajarata_University BIT_2009


IP

„ TCP/IP- Transmission Control Protocol and Internet


Protocol .
„ SMTP - Simple Mail Transfer Protocol to send and
receive electronic mail
„ FTP - File Transfer Protocol to transfer files between
computers
„ HTTP - Hypertext Transfer Protocol to transmit
information on the World Wide Web
„ NNTP - Network News Transfer Protocol to transmit
discussion forum messages

© Pramudith_Kandambi Rajarata_University BIT_2009


IP Addresses
„ Every machine on the the Internet has a unique number assigned
to it,

192.168.1.10
Class Start address Finish address

A 0.0.0.0 126.255.255.255

B 128.0.0.0 191.255.255.255

C 192.0.0.0 223.255.255.255

D 224.0.0.0 239.255.255.255

E 240.0.0.0 255.255.255.255

© Pramudith_Kandambi Rajarata_University BIT_2009


Domain Name
• Domain Names are the unique name that identifies an entity

whether that be an single individual or a company, on the


Internet.

• Domain Names always have 2 or more parts seperated by the dots.

• The leftmost piece is the most specific part while the right part is the TLD
or Top Level Domain.

Full Address Hostname Domain Name TLD


www.bleepingcomputer.com www bleepingcomputer.com com
bleepingcomputer.com bleepingcomputer.com bleepingcomputer.com com
www.google.net www google.net net
my.www.bleepingcomputer.com my.www bleepingcomputer.com com

© Pramudith_Kandambi Rajarata_University BIT_2009


Internet Architecture

Computer on the
Internet holding
information -
Desktop remote “server”
computer -
“client”

© Pramudith_Kandambi Rajarata_University BIT_2009


Server/Client Interface

SERVERS
Hardware + Software

Software
Protocols
CLIENTS
Hardware + Software

© Pramudith_Kandambi Rajarata_University BIT_2009


Web Browsers

© Pramudith_Kandambi Rajarata_University BIT_2009


Web Servers

© Pramudith_Kandambi Rajarata_University BIT_2009


The Internet Address or URL

This page is being viewed in the


Internet Explorer Browser.
Browsers allow computers to read
Hyper Text Mark-up Language
OR HTML.

The Address or URL is typed in here.

© Pramudith_Kandambi Rajarata_University BIT_2009


Entering a URL address in the address box

After entering a URL address in the address


box click Go or hit the RETURN key. In this
example we have entered http://www.who.int
for the WHO website

© Pramudith_Kandambi Rajarata_University BIT_2009


Hypertext links

Links to other pages are usually


underlined or in another colour of
text.

© Pramudith_Kandambi Rajarata_University BIT_2009


Forward and back navigation buttons

The arrow buttons on the tool bar


allow users to move Back and
Forward to pages within the website.

© Pramudith_Kandambi Rajarata_University BIT_2009


Home page button

The House icon on the tool bar will


take you back to the browser’s
default Home Page.

© Pramudith_Kandambi Rajarata_University BIT_2009


This is the end of Module 1

This is the end of Module 1.1


There is a Work Book to accompany this part of
the module. The workbook will take you through
a live session covering the topics included in
this demonstration with working examples.
Updated 02 2008

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML
Hyper Text Markup Language

By Pramudith Kandambi

© Pramudith_Kandambi Rajarata_University BIT_2009


What is HTML?
„ HTML is a language for describing web pages.

„ HTML stands for Hyper Text Markup Language.

„ HTML is not a programming language, it is a


markup language.

„ A markup language is a set of markup tags.

„ HTML uses markup tags to describe web pages.

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Tags

„ HTML markup tags are usually called HTML tags


„ Keywords surrounded by angle brackets like
<html>
„ HTML tags normally come in pairs like
<b> and </b>

„ Starting tag <b> abcd </b> Closing Tag

© Pramudith_Kandambi Rajarata_University BIT_2009


Format of a HTML Doc

<html>
<head>
</head>

<body>
This is area what we view
</body>
</html>

© Pramudith_Kandambi Rajarata_University BIT_2009


W3C HTML Validation Service

„ Validation service ( validator.w3.org )


‰ Checking a document’s syntax
„ URL that specifies the location of the file
„ Uploading a file to the site
http://validator.w3.org/file-upload.html

© Pramudith_Kandambi Rajarata_University BIT_2009


W3C HTML Validation Service

© Pramudith_Kandambi Rajarata_University BIT_2009


First HTML Doc

<html>
<head>
</head>

<body>
Hello Sri Lanka
</body>
</html>

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Headings

„ HTML headings are defined with the


<h1> to <h6> tags.

„ Example

<h1> This is a heading</h1>


<h2>This is a heading</h2>
<h3>This is a heading</h3>

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Paragraphs

„ HTML paragraphs are defined with the <p>


tag.

„ Example

<p> This is a paragraph</p>


<p>This is another paragraph</p>

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Links

„ HTML links are defined with the <a> tag.

„ Example

<a href="http://www.rjt.ac.lk">This is a
link</a>

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Images

„ HTML images are defined with the <img> tag.

Example

<img src="w3schools.jpg" width="104"


height="142" />

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Element Syntax

„ An HTML element starts with a start tag / opening tag


<h1>
„ An HTML element ends with an end tag / closing tag
<h1> </h1>
„ The element content is everything between the start and the
end tag

„ Some HTML elements have empty content

„ Empty elements are closed in the start tag

„ Most HTML elements can have attributes

© Pramudith_Kandambi Rajarata_University BIT_2009


Empty HTML Elements
„ HTML elements without content are called empty elements.

„ <br> is an empty element without a closing tag (it defines a


line break).

„ In XHTML, XML, and future versions of HTML, all elements


must be closed.

„ Adding a slash to the start tag, like <br />, is the proper way of
closing empty elements, accepted by HTML, XHTML and
XML.

„ Even if <br> works in all browsers, writing <br /> instead is


more future proof.

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Tip: Use Lowercase Tags

„ HTML tags are not case sensitive:


<P> same as <p>.
„ Plenty of web sites use uppercase HTML
tags in their pages.
„ World Wide Web Consortium (W3C)
recommends lowercase in HTML 4, and
demands lowercase tags in future versions
of (X)HTML.

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Attributes
„ Attributes provide additional information about
HTML elements.

„ HTML elements can have attributes

„ Attributes provide additional information about the


element

„ Attributes are always specified in the start tag

„ Attributes come in name/value pairs like:


name="value"

© Pramudith_Kandambi Rajarata_University BIT_2009


Always Quote Attribute Values

„ Attribute values should always be enclosed in


quotes.

„ Double style quotes are the most common, but


single style quotes are also allowed.

„ In some rare situations, like when the attribute value


itself contains quotes, it is necessary to use single
quotes:
name='John "ShotGun" Nelson'

© Pramudith_Kandambi Rajarata_University BIT_2009


Don't Forget the End Tag

„ Most browsers will display HTML correctly


even if you forget the end tag:

Example

<p> This is a paragraph </p>


<p> This is another paragraph </p>

© Pramudith_Kandambi Rajarata_University BIT_2009


HTML Output - Useful Tips

„ You cannot be sure how HTML will be displayed. Large or small


screens, and resized windows will create different results.

„ With HTML, you cannot change the output by adding extra


spaces or extra lines in your HTML code.

„ The browser will remove extra spaces and extra lines when the
page is displayed.

„ Any number of lines count as one space, and any number of


spaces count as one space.

© Pramudith_Kandambi Rajarata_University BIT_2009


Text Formatting Tags

Tag Description
<b> Defines bold text
<big> Defines big text
<em> Defines emphasized text
<i> Defines italic text
<small> Defines small text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<s> Deprecated. Use <del> instead
<strike> Deprecated. Use <del> instead
<u> Deprecated. Use styles instead

© Pramudith_Kandambi Rajarata_University BIT_2009


The HTML Style Attribute
„ To provide a common way to style all HTML elements.

„ Styles was introduced with HTML 4,


„ Styles can be added to HTML elements directly by using the style
attribute
or
„ separate style sheets (CSS files).

„ HTML Style Examples

‰ style="background-color:yellow"
‰ style="font-size:10px"
‰ style="font-family:Times"
‰ style="text-align:center"

© Pramudith_Kandambi Rajarata_University BIT_2009


Hyperlinks, Anchors, and Links

„ In web terms, a hyperlink is a reference (an


address) to a resource on the web.

„ Hyperlinks can point to any resource on the


web: an HTML page, an image, a sound file,
a movie, etc.

„ An anchor is a term used to define a


hyperlink destination inside a document.
An HTML Link

„ Link syntax:
<a href="url">Link text</a>
‰ Note: The element content doesn't have to be text. You can link
from an image or any other HTML element.

„ The href Attribute


„ The href attribute defines the link "address".
„ This <a> element defines a link to RJT site
„ <a href="http://www.rjt.ac.lk/">Visit Rajarata!</a> The
code above will display like this in a browser:
An HTML Link cont..

„ The target Attribute


‰ The target attribute defines where the linked
document will be opened.
‰ The code below will open the document in a new
browser window:

„ Example
<a href="http://www.w3schools.com/"
target="_blank">Visit W3Schools!</a>
An HTML Link cont..

„ The name Attribute


‰ Named anchor are not displayed in any special
way. They are invisible to the reader.
„ Named anchor syntax:
‰ <a name="label">Any content</a>
„ The link syntax to a named anchor:
‰ <a href="#label">Any content</a>
‰ The # in the href attribute defines a link to a
named anchor.
An HTML Link cont..

Example:
„ A named anchor inside an HTML document:

<a name="tips">Useful Tips Section</a>

„ A link to the Useful Tips Section from the


same document:

<a href="#tips">Jump to the Useful Tips Section</a>


<!--> <dd> <legend>
<li> <style>
<!DOCTYPE> <del> <sub>
<a> <dfn> <link>
<map> <sup>
<abbr> <dir> <table>
<acronym> <div> <menu>
<meta> <tbody>
<address> <dl> <td>
<applet> <dt> <noframes>
<noscript> <textarea>
<area> <em> <tfoot>
<b> <fieldset> <object>
<ol> <th>
<base> <font> <thead>
<basefont> <form> <optgroup>
<option> <title>
<bdo> <frame> <tr>
<big> <frameset> <p>
<param> <tt>
<blockquote> <head> <u>
<body> <h1> - <h6> <pre>
<q> <ul>
<br> <hr> <var>
<button> <html> <s>
<caption> <i> <samp>
<center> <iframe> <script>
<cite> <img> <select>
<code> <input> <small>
<col> <ins> <span>
<colgroup> <kbd> <strike>
<dd> <label> <strong>
HTML –Part 2
Pramudith_Kandambi@MIT_IMdepartment
Introduction to HTML: Part 2
Outline

Introduction
Basic HTML Tables
Intermediate HTML Tables and Formatting
Basic HTML Forms
More Complex HTML Forms
Internal Linking
Creating and Using Image Maps
meta Elements
frameset Element
Nested framesets
Web Resources

2
Objectives

` In this lesson, you will learn:


` To be able to create tables with rows and columns of
data.
` To be able to control table formatting.
` To be able to create and use forms.
` To be able to create and use image maps to aid in Web-
page navigation.
` To be able to use the frameset element to display multiple
Web pages in a single browser window.

3
Introduction

` Tables
` Present information
` Forms
` Collect information from visitor
` Internal linking and image maps
` Enhance Web page navigation
` Frames
` Display multiple documents in the browser

4
Basic HTML Tables
` Organize data into rows and columns

` <table> element
` Attribute border
` Specifies the table’s border width in pixels
` Attribute summary
` Describes the table’s contents
` Attribute caption
` Describes the table’s content and helps text-based
browsers interpret table data

5
Basic HTML Tables

` Head section (header cell, defined with a <thead>


element)
` Contains header information such as column names
` <tr> element (defines an individual table row)
` <th> element (defines the columns in the head section)

` Foot section (defined with a <tfoot> element)


` Table body (defined with a <tbody> element)
` Data cells (defined with <td> element)
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- table1.html -->
6 <!-- Creating a basic table -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>A simple XHTML table</title>
11 </head>
12
13 <body>
14
15 <!-- the <table> tag opens a table --> table.html
16 <table border = "1" width = "40%"
17 summary = "This table provides information about (1 of 3)
18 the price of fruit">
19
20 <!-- the <caption> tag summarizes the table's -->
21 <!-- contents (this helps the visually impaired) -->
22 <caption><strong>Price of Fruit</strong></caption>
23 7
24 <! -- th e <t hea d> i s t he f irst se ctio n o f a tabl e - ->
25 <! -- it for mat s th e t able hea der are a - ->
26 <t hea d>
27 <t r> <!-- <tr > i nser ts a ta ble row -->
28 < th>F rui t</t h> <!-- ins ert a h ead ing cell -- >
29 < th>P ric e</t h>
30
31
</ tr >
</ the ad >
table.html
32
33 <! -- th e <t foo t> i s t he l ast sec tion of a t able -- >
(2 of 3)
34 <! -- it for mat s th e t able foo ter -- >
35 <t foo t>
36 <t r>
37 < th>T ota l</t h>
38 < th>$ 3.7 5</t h>
39 </ tr >
40 </ tfo ot >
41
42 <! -- al l ta ble con ten t is enc los ed -->
43 <! -- wi thin th e <t bod y> -->
44 <t bod y>
45 <t r>
46 < td>A ppl e</t d> <!-- ins ert a d ata cel l -- >
47 < td>$ 0.2 5</t d>
48 8 </ tr >
49
50 <tr>
51 <td>Orange</td>
52 <td>$0.50</td>
53 </tr>
54
55 <tr>
56 <td>Banana</td>
57 <td>$1.00</td>
58 </tr>
59
60 <tr>
61 <td>Pineapple</td>
62 <td>$2.00</td> table.html
63 </tr>
64 </tbody>
(3 of 3)
65
66 </table>
67
68 </body>
69 </html>
9
10
Intermediate HTML Tables and Formatting
` Element <colgroup>
` Groups and formats columns
` Element <col>
` Attribute align
` Determines the alignment of text in the column
` Attribute span
` Determines how many columns the col element formats
` rowspan and colspan
… Specify the number of rows or columns occupied by a cell
` valign
` Aligns data vertically
` One of the four values: “top”, “middle”, “bottom”, “baseline”

11
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- table2.html -->
6 <!-- Intermediate table design -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Tables</title>
11 </head>
12
13 <body>
14
15 <h1>Table Example Page</h1> table2.html
16
17 <table border = "1"> (1 of 4)
18 <caption>Here is a more complex sample table.</caption>
19
20 <!-- <colgroup> and <col> tags are used to -->
21 <!-- format entire columns -->
22 <colgroup>
23 12
24 <!-- span attribute determines how many columns -->
25 <!-- the <col> tag affects -->
26 <col align = "right" span = "1" />
27 </colgroup>
28
29 <thead>
30
31 <!-- rowspans and colspans merge the specified -->
32 <!-- number of cells vertically or horizontally -->
33 <tr>
34
35 <!-- merge two rows -->
36 <th rowspan = "2">
37 <img src = "camel.gif" width = "205"
38 height = "167" alt = "Picture of a camel" />
39 </th> table2.html
40
41 <!-- merge four columns -->
(2 of 4)
42 <th colspan = "4" valign = "top">
43 <h1>Camelid comparison</h1><br />
44 <p>Approximate as of 9/2002</p>
45 </th>
46 </tr>
47 13
48 <t r vali gn = "b ott om">
49 < th># of H um ps< /th>
50 < th>I n d i g e n o u s r e g i o n </ th>
51 < th>S pit s? </ th>
52 < th>P r o d u c e s W o o l ?< /t h>
53 </ tr >
54
55 < / t h e ad >
56
57 < t b o d y>
58
59 <t r>
60 < th>C a m e l s ( b a c t r i a n ) </ th>
61 < td>2 </t d>
62 < td>A f r i c a / A s i a </td >
63 < td>Y es< /t d>
64 < td>Y es< /t d>
table2.html
65 </ tr > (3 of 4)
66
67 <t r>
68 < th>L lam as </ th>
69 < td>1 </t d>
70 < td>A nde s Mo unt ains < / t d >
71 < td>Y es< /t d>
72 14 < td>Y es< /t d>
73 </tr>
74
75 </tbody>
76
77 </table>
78
79 </body>
80 </html>

15
Basic HTML Forms
` Element <form>
` Attribute method
` Specifies how the form’s data is sent to Web server
` method = “post”
… Appends form data to the browser request
` method = “get”
… Appends form data directly to the end of the URL
` Attribute action
` Specifies the URL of a script on the Web server
` input
` Specifies data to provide to the script that processes the form

16
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- form.html -->
6 <!-- Form Design Example 1 -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Forms</title>
11 </head>
12
13 <body>
14
15 <h1>Feedback Form</h1>
16
17 <p>Please fill out this form to help form.html
18 us improve our site.</p>
19
(1 of 3)
20 <!-- this tag starts the form, gives the -->
21 <!-- method of sending information and the -->
22 <!-- location of form scripts -->
23 <form method = "post" action = "/cgi-bin/formmail">
24

17
25 <p>
26 <!-- hidden inputs contain non-visual -->
27 <!-- information -->
28 <input type = "hidden" name = "recipient"
29 value = "deitel@deitel.com" />
30 <input type = "hidden" name = "subject"
31 value = "Feedback Form" />
32 <input type = "hidden" name = "redirect"
33 value = "main.html" />
34 </p>
35
36 <!-- <input type = "text"> inserts a text box -->
37 <p><label>Name:
38 <input name = "name" type = "text" size = "25"
39 maxlength = "30" />
40 </label></p>
41
42 <p> form.html
43 <!-- input types "submit" and "reset" insert -->
44 <!-- buttons for submitting and clearing the (2 of 3)
-->
45 <!-- form's contents -->
46 <input type = "submit" value =
47 "Submit Your Entries" />
48 <input type = "reset" value =
49 "Clear Your Entries" />
50 </p>

18
51
52 </form>
53
54 </body>
55 </html>

19
More Complex HTML Forms
` Element <textarea>
` Inserts a multiline text box (text area)
` Attribute rows
` Specifies the number of rows
` Attribute cols
` Specifies the number columns
` Input “password”
` Inserts a password box with the specified size
` Element <checkbox>
` Enable users to select from a set of options
` Element <select>
` Provides a drop-down list of items
` Element <option>
` Adds items to the drop-down list
` Attribute selected
` Specifies which item initially is displayed as the selected item
20
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- form2.html -->
6 <!-- Form Design Example 2 -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Forms</title>
11 </head>
12
13 <body>
14
15 <h1>Feedback Form</h1> form2.html
16
17 <p>Please fill out this form to help
(1 of 4)
18 us improve our site.</p>
19
20 <form method = "post" action = "/cgi-bin/formmail">
21

21
22 <p>
23 <input type = "hidden" name = "recipient"
24 value = "deitel@deitel.com" />
25 <input type = "hidden" name = "subject"
26 value = "Feedback Form" />
27 <input type = "hidden" name = "redirect"
28 value = "main.html" />
29 </p>
30
31 <p><label>Name:
32 <input name = "name" type = "text" size = "25" />
33 </label></p>
34
35 <!-- <textarea> creates a multiline textbox --> form2.html
<p><label>Comments:<br />
36
(2 of 4)
37 <textarea name = "comments" rows = "4" cols = "36">
38 Enter your comments here.
39 </textarea>
40 </label></p>
41
22
42 <!-- <input type = "password"> inserts a -->
43 <!-- textbox whose display is masked with -->
44 <!-- asterisk characters -->
45 <p><label>E-mail Address:
46 <input name = "email" type = "password"
47 size = "25" />
48 </label></p>
49
50 <p>
51 <strong>Things you liked:</strong><br />
52
53 <label>Site design
54 <input name = "thingsliked" type = "checkbox"
55 value = "Design" /></label>
56
57 <label>Links
58 <input name = "thingsliked" type = "checkbox"
59 value = "Links" /></label> form2.html
60
61 <label>Ease of use
(3 of 4)
62 <input name = "thingsliked" type = "checkbox"
63 value = "Ease" /></label>
64
65 <label>Images
66 <input name = "thingsliked" type = "checkbox"
67 value = "Images" /></label>
23
68
69 <label>Source code
70 <input name = "thingsliked" type = "checkbox"
71 value = "Code" /></label>
72 </p>
73
74 <p>
75 <input type = "submit" value =
76 "Submit Your Entries" />
77 <input type = "reset" value =
78 "Clear Your Entries" />
79 </p> form2.html
80
(4 of 4)
81 </form>
82
83 </body>
84 </html>

24
25
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- form3.html -->
6 <!-- Form Design Example 3 -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Forms</title>
11 </head>
12
13 <body>
14
15 <h1>Feedback Form</h1>
16
<p>Please fill out this form to help
17
18 us improve our site.</p>
form3.html
19
20 <form method = "post" action = "/cgi-bin/formmail">
(1 of 6)
21
22 <p>
23 <input type = "hidden" name = "recipient"
24 value = "deitel@deitel.com" />
25 <input type = "hidden" name = "subject"

26
26 value = "Feedback Form" />
27 <input type = "hidden" name = "redirect"
28 value = "main.html" />
29 </p>
30
31 <p><label>Name:
32 <input name = "name" type = "text" size = "25" />
33 </label></p>
34
35 <p><label>Comments:<br />
36 <textarea name = "comments" rows = "4"
37 cols = "36"></textarea>
38 </label></p>
39
40 <p><label>E-mail Address:
41 <input name = "email" type = "password"
42 size = "25" /></label></p> form3.html
43
44 <p> (2 of 6)
45 <strong>Things you liked:</strong><br />
46
47 <label>Site design
48 <input name = "thingsliked" type = "checkbox"
49 value = "Design" /></label>
50
27
51 <l ab el>L ink s
52 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
53 va lue = " Lin ks" /></ lab el>
54
55 <l ab el>E ase of use
56 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
57 va lue = " Eas e" / ></l abe l>
58
59 <l ab el>I mag es
60 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
61 va lue = " Ima ges" />< /la bel>
62
63 <l ab el>S our ce c ode
64 < inpu t n ame = " thin gsli ked " ty pe = "c heck box "
65 va lue = " Cod e" / ></l abe l>
66
67
</p>
form3.html
68 <! -- <i nput ty pe = "r adio " /> cr eate s a rad io (3 of 6)
-->
69 <! -- bu tton . T he d iff eren ce b etw een rad io b utto ns -->
70 <! -- an d ch eck boxe s i s th at o nly one ra dio butt on -->
71 <! -- in a g rou p ca n b e se lect ed. -->
72 <p >
73 <s tr ong>How did yo u ge t to ou r si te? :</s tron g>< br / >
74
28
75 <label>Search engine
76 <input name = "howtosite" type = "radio"
77 value = "search engine" checked = "checked" />
78 </label>
79
80 <label>Links from another site
81 <input name = "howtosite" type = "radio"
82 value = "link" /></label>
83
84 <label>Deitel.com Web site
85 <input name = "howtosite" type = "radio"
86 value = "deitel.com" /></label>
87
88 <label>Reference in a book
89 <input name = "howtosite" type = "radio"
90 value = "book" /></label> form3.html
91
92 <label>Other
(4 of 6)
93 <input name = "howtosite" type = "radio"
94 value = "other" /></label>
95
96 </p>
97

29
98 <p >
99 <l ab el>R ate our si te:
100
101 <!- - t he < sel ect> tag pr esen ts a dr op-d own -->
102 <!- - l ist wit h ch oice s i ndic ate d by the -->
103 <!- - < opti on> tag s -->
104 <sel ect nam e = "ra ting ">
105 < opt ion sel ecte d = "se lect ed" >Ama zing </o ptio n>
106 < opt ion> 10< /opt ion>
107 < opt ion> 9</ opti on>
108 < opt ion> 8</ opti on>
109 < opt ion> 7</ opti on>
110 < opt ion> 6</ opti on>
111 < opt ion> 5</ opti on>
112 < opt ion> 4</ opti on>
113
114
< opt ion> 3</ opti on>
< opt ion> 2</ opti on>
form3.html
115 < opt ion> 1</ opti on> (5 of 6)
116 < opt ion> Awf ul</ opti on>
117 </se lec t>
118
119 </l abel >
120 </p >
121
30
122 <p>
123 <input type = "submit" value =
124 "Submit Your Entries" />
125 <input type = "reset" value = "Clear Your Entries" />
126 </p>
127
128 </form>
129
130 </body>
131 </html>

form3.html
(6 of 6)

31
Internal Linking
` Enables the user to jump between locations in the same
document

32
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- links.html -->
6 <!-- Internal Linking -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - List</title>
11 </head>
12
13 <body>
14
15 <!-- id attribute creates an internal hyperlink destination -->
16 <h1 id = "features">The Best Features of the Internet</h1>
17
18 <!-- an internal link's address is "#id" -->
links.html
19 (1 of 3)
<p><a href = "#bugs">Go to <em>Favorite Bugs</em></a></p>
20
21 <ul>
22 <li>You can meet people from countries
23 around the world.</li>
24
25 <li>You have access to new media as it becomes public:

33
26 <ul>
27 <li>New games</li>
28 <li>New applications
29 <ul>
30 <li>For Business</li>
31 <li>For Pleasure</li>
32 </ul>
33 </li>
34
35 <li>Around the clock news</li>
36 <li>Search Engines</li>
37 <li>Shopping</li>
38 <li>Programming
39 <ul>
40 <li>XHTML</li>
41 <li>Java</li>
42 <li>Dynamic HTML</li>
43
44
<li>Scripts</li>
<li>New languages</li>
links.html
45
46
</ul>
</li>
(2 of 3)
47 </ul>
48 </li>
49
50 <li>Links</li>

34
51 <li>Keeping in touch with old friends</li>
52 <li>It is the technology of the future!</li>
53 </ul>
54
55 <!-- id attribute creates an internal hyperlink destination -->
56 <h1 id = "bugs">My 3 Favorite Bugs</h1>
57
58 <p>
59
60 <!-- internal hyperlink to features -->
61 <a href = "#features">Go to <em>Favorite Features</em>
62 </a></p>
63
64 <ol>
65 <li>Fire Fly</li>
66 <li>Gal Ant</li>
67 <li>Roman Tic</li>
68 </ol>
69 links.html
</body>
70
71 </html>
(3 of 3)

35
36
Creating and Using Image Maps
` Designate certain areas of an image (called hotspots) as
links
` Element <map>
` Attribute id
… Identifies the image map
` Element area
… Defines hotspot
… Attribute shape and coords
… Specify the hotspot’s shape and coordinates
… Rectangular ( shape = “rect” )
… Polygon ( shape = “poly” )
… Circle ( shape = “circle” )

37
1 <?xml version = "1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- picture.html -->
6 <!-- Creating and Using Image Maps -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Internet and WWW How to Program - Image Map
12 </title>
13 </head>
14
15 <body>
16
17 <p> picture.html
18
19 <!-- the <map> tag defines an image map --> (1 of 3)
20 <map id = "picture">
21
22 <!-- shape = "rect" indicates a rectangular -->
23 <!-- area, with coordinates for the upper-left -->
24 <!-- and lower-right corners -->

38
25 <area href = "form.html" shape = "rect"
26 coords = "2,123,54,143"
27 alt = "Go to the feedback form" />
28 <area href = "contact.html" shape = "rect"
29 coords = "126,122,198,143"
30 alt = "Go to the contact page" />
31 <area href = "main.html" shape = "rect"
32 coords = "3,7,61,25" alt = "Go to the homepage" />
33 <area href = "links.html" shape = "rect"
34 coords = "168,5,197,25"
35 alt = "Go to the links page" />
36
37 <!-- value "poly" creates a hotspot in the shape -->
38 <!-- of a polygon, defined by coords -->
39 <area shape = "poly" alt = "E-mail the Deitels"
40 coords = "162,25,154,39,158,54,169,51,183,39,161,26"
41
42
href = "mailto:deitel@deitel.com" />
picture.html
43 <!-- shape = "circle" indicates a circular --> (2 of 3)
44 <!-- area with the given center and radius -->
45 <area href = "mailto:deitel@deitel.com"
46 shape = "circle" coords = "100,36,33"
47 alt = "E-mail the Deitels" />
48 </map>
49

39
50 <!-- <img src =... usemap = "#id"> indicates that the -->
51 <!-- specified image map is used with this image -->
52 <img src = "deitel.gif" width = "200" height = "144"
53 alt = "Deitel logo" usemap = "#picture" />
54 </p>
55 </body>
56 </html>

picture.html
(3 of 3)

40
meta Elements
` Specify information about a document
` Attribute name
` Identifies the type of meta element
` “keywords” ( name = “keywords” )
… Provides search engines with a list of words that describe a page
` “description” ( name = “description” )
… Provides a description of a site
` Attribute content
` Provides the information search engine use to catalog pages

41
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- main.html -->
6 <!-- <meta> tag -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Welcome</title>
11
12 <!-- <meta> tags provide search engines with -->
13 <!-- information used to catalog a site -->
14 <meta name = "keywords" content = "Web page, design,
15 XHTML, tutorial, personal, help, index, form,
16 contact, feedback, list, links, frame, deitel" />
17 main.html
18 <meta name = "description" content = "This Web site will
19 (1 of 2)
help you learn the basics of XHTML and Web page design
20 through the use of interactive examples and
21 instruction." />
22
23 </head>
24

42
25 <body>
26
27 <h1>Welcome to Our Web Site!</h1>
28
29 <p>We have designed this site to teach about the wonders
30 of <strong><em>XHTML</em></strong>. <em>XHTML</em> is
31 better equipped than <em>HTML</em> to represent complex
32 data on the Internet. <em>XHTML</em> takes advantage of
33 XML’s strict syntax to ensure well-formedness. Soon you
34 will know about many of the great new features of
35 <em>XHTML.</em></p>
36
37 <p>Have Fun With the Site!</p>
38
39 </body>
40 </html>

main.html
(2 of 2)

43
frameset Element
` Allow browser display more than one document
simultaneously
` Element frameset
` Attribute cols
… Specifies the frameset’s column layout
` Attribute rows
… Specifies the number of rows and the size of each row
` Element frame
… Specifies the documents that will be loaded
… Attribute src
… Specifies URL of the page to display

44
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
4
5 <!-- index.html -->
6 <!-- XHTML Frames I -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Main</title>
11 <meta name = "keywords" content = "Webpage, design,
12 XHTML, tutorial, personal, help, index, form,
13 contact, feedback, list, links, frame, deitel" />
14
15 <meta name = "description" content = "This Web site will
16 help you learn the basics of XHTML and Web page design
17 through the use of interactive examples
18 and instruction." />
19
index.html
20
21
</head>
(1 of 2)
22 <!-- the <frameset> tag sets the frame dimensions -->
23 <frameset cols = "110,*">
24

45
25 <!-- frame elements specify which pages -->
26 <!-- are loaded into a given frame -->
27 <frame name = "leftframe" src = "nav.html" />
28 <frame name = "main" src = "main.html" />
29
30 <noframes>
31 <body>
32 <p>This page uses frames, but your browser does not
33 support them.</p>
34
35 <p>Please, <a href = "nav.html">follow this link to
36 browse our site without frames</a>.</p>
37 </body>
38 </noframes>
39
40 </frameset>
41 </html>

index.html
(2 of 2)

46
47
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- nav.html -->
6 <!-- Using images as link anchors -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9
10 <head>
11 <title>Internet and WWW How to Program - Navigation Bar
12 </title>
13 </head>
14
15 <body>
16
17 <p>
18 <a href = "links.html" target = "main">
19 <img src = "buttons/links.jpg" width = "65"
nav.html
20
21
height = "50" alt = "Links Page" />
</a><br />
(1 of 2)
22
23 <a href = "list.html" target = "main">
24 <img src = "buttons/list.jpg" width = "65"
25 height = "50" alt = "List Example Page" />

48
26 </a><br />
27
28 <a href = "contact.html" target = "main">
29 <img src = "buttons/contact.jpg" width = "65"
30 height = "50" alt = "Contact Page" />
31 </a><br />
32
33 <a href = "header.html" target = "main">
34 <img src = "buttons/header.jpg" width = "65"
35 height = "50" alt = "Header Page" />
36 </a><br />
37
38 <a href = "table1.html" target = "main">
39 <img src = "buttons/table.jpg" width = "65"
40 height = "50" alt = "Table Page" />
41 </a><br />
42
43 <a href = "form.html" target = "main">
44 <img src = "buttons/form.jpg" width = "65" nav.html
height = "50" alt = "Feedback Form" />
45
46 </a><br />
(2 of 2)
47 </p>
48
49 </body>
50 </html>

49
Nested framesets
` framesets within framesets

50
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
4
5 <!-- index2.html -->
6 <!-- XHTML Frames II -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Internet and WWW How to Program - Main</title>
11
12 <meta name = "keywords" content = "Webpage, design,
13 XHTML, tutorial, personal, help, index, form,
14 contact, feedback, list, links, frame, deitel" />
15
16 <meta name = "description" content = "This Web site will
17 help you learn the basics of XHTML and Web page design
18 through the use of interactive examples
19 and instruction." />
index2.html
20
21 </head>
(1 of 2)
22
23 <frameset cols = "110,*">
24 <frame name = "leftframe" src = "nav.html" />
25

51
26 <!-- nested framesets are used to change the -->
27 <!-- formatting and layout of the frameset -->
28 <frameset rows = "175,*">
29 <frame name = "picture" src = "picture.html" />
30 <frame name = "main" src = "main.html" />
31 </frameset>
32
33 <noframes>
34 <body>
35 <p>This page uses frames, but your browser does not
36 support them.</p>
37
38 <p>Please, <a href = "nav.html">follow this link to
39 browse our site without frames</a>.</p>
40 </body>
41 </noframes>
42
43 </frameset>
44 </html> index2.html
(2 of 2)

52
53
Web Resources
` www.vbxml.com/xhtml/articles/xhtml_tables
` www.webreference.com/xml/reference/xhtml.html

54
What is HTML ?

•HTML stands for Hyper Text Markup Language

•HTML is not a programming language, it is a markup language

•A markup language is a set of markup tags

•HTML uses markup tags to describe web pages

Pramudith_Kandambi@MIT_IMdepartment
HTML page

<html>

<body>

My First Heading
My first paragraph.

</body>

</html>

Pramudith_Kandambi@MIT_IMdepartment
HTML

<html>

<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>

</html>

Pramudith_Kandambi@MIT_IMdepartment
HTML Headings

<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>

HTML Paragraphs

<p>This is a paragraph</p>
<p>This is another paragraph</p>

Pramudith_Kandambi@MIT_IMdepartment
HTML Links

HTML links are defined with the <a> tag.

<a href="http://www.w3schools.com” > This is a link</a>

<a> attribute
href - provide the link address

Pramudith_Kandambi@MIT_IMdepartment
HTML Links

HTML links are defined with the < > tag.

<img src= "constr4.gif" width= "144" height= "50" />

<> attribute

Pramudith_Kandambi@MIT_IMdepartment
HTML image

<br> or <br />


<hr />

<table> defines an HTML table.


<table border="1">
Tag Description
<b> Defines bold text
<big> Defines big text
<em> Defines emphasized text
<i> Defines italic text
<small> Defines small text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted textPramudith_Kandambi@MIT_IMdepartment
HTML

<frameset >
<frame >
<frame >
</frameset>

<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

Pramudith_Kandambi@MIT_IMdepartment
HTML

<table >

<tr> <td>A</td> <td>B</td> </tr>

<tr> <td>C</td> <td>D</td> </tr>

</table>

Pramudith_Kandambi@MIT_IMdepartment
Outline
Introduction
Inline Styles
Embedded Style Sheets
Conflicting Styles
Linking External Style Sheets
W3C CSS Validation Service
Positioning Elements
Backgrounds
Element Dimensions
Text Flow and the Box Model
User Style Sheets
Web Resources

© Dept. of Industrial Management-2008 1


 In this lesson, you will learn:
◦ To control the appearance of a Web site by
creating style sheets.
◦ To use a style sheet to give all the pages of a
Web site the same look and feel.
◦ To use the class attribute to apply styles.
◦ To specify the precise font, size, color and other
properties of displayed text.
◦ To specify element backgrounds and colors.
◦ To understand the box model and how to
control the margins, borders and padding.
◦ To use style sheets to separate presentation
from content.

© Dept. of Industrial Management-2008 2


 selector {property: value}
 body {color: black}
 p {text-align:center ;color:red}

 Grouping
 h1,h2,h3,h4,h5,h6 { color: green }

© Dept. of Industrial Management-2008


• p {text-align: right}
• p.right {text-align: right}
• p.center {text-align: center}

• Ex: HTML
• <p class="center"> This paragraph will be center-aligned. </p>
• <p class="right"> This paragraph will be right-aligned. </p>

© Dept. of Industrial Management-2008


 <p style="color: sienna; margin-left: 20px"> This is
a paragraph </p>

© Dept. of Industrial Management-2008


 <head>
<style type="text/css">
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
</style>
</head>

© Dept. of Industrial Management-2008


<head>
<link rel="stylesheet" type="text/css"
href="mystyle.css" />
</head>

© Dept. of Industrial Management-2008


© Dept. of Industrial Management-2008
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- inline.html -->
6 <!-- Using inline styles -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Inline Styles</title>
11 </head>
12
13 <body>
14
15 <p>This text does not have any style applied to it.</p>
16
17 <!-- The style attribute allows you to declare -->
18 <!-- inline styles. Separate multiple styles -->
19 <!-- with a semicolon. -->
20 <p style = "font-size: 20pt">This text has the
21 <em>font-size</em> style applied to it, making it 20pt.
22 </p>
23

9
24 <p style = "font-size: 20pt; color: #0000ff">
25 This text has the <em>font-size</em> and
Outline
26 <em>color</em> styles applied to it, making it
27 20pt. and blue.</p>
28
29 </body>
30 </html>

10
 Embed an entire CSS document in an XHTML
document’s head section
◦ Multipurpose Internet Mail Extensions (MIME) type
 Describes a file’s content
◦ Property background-color
 Specifies the background color
◦ Property font-family
 Specifies the name of the font to use
◦ Property font-size
 Specifies a 14-point font

© Dept. of Industrial Management-2008 11


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- declared.html -->
6 <!-- Declaring a style sheet in the header section. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Style Sheets</title>
11
12 <!-- this begins the style sheet section -->
13 <style type = "text/css">
14
15 em { background-color: #8000ff;
16 color: white }
17
18 h1 { font-family: arial, sans-serif }
19
20 p { font-size: 14pt }
21
22 .special { color: blue }
23
24 </style>
25 </head>

12
26
27 <body>
Outline
28
29 <!-- this class attribute applies the .special style -->
30 <h1 class = "special">Deitel & Associates, Inc.</h1>
31
32 <p>Deitel &amp; Associates, Inc. is an internationally
33 recognized corporate training and publishing organization
34 specializing in programming languages, Internet/World
35 Wide Web technology and object technology education.
36 Deitel &amp; Associates, Inc. is a member of the World Wide
37 Web Consortium. The company provides courses on Java,
38 C++, Visual Basic, C, Internet and World Wide Web
39 programming, and Object Technology.</p>
40
41 <h1>Clients</h1>
42 <p class = "special"> The company's clients include many
43 <em>Fortune 1000 companies</em>, government agencies,
44 branches of the military and business organizations.
45 Through its publishing partnership with Prentice Hall,
46 Deitel &amp; Associates, Inc. publishes leading-edge
47 programming textbooks, professional books, interactive
48 CD-ROM-based multimedia Cyber Classrooms, satellite
49 courses and World Wide Web courses.</p>
50

13
51 </body>
52 </html>
Outline

14
 Inheritance
◦ Descendant’s properties have greater specificity
than ancestor’s properties

© Dept. of Industrial Management-2008 15


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- advanced.html -->
6 <!-- More advanced style sheets -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>More Styles</title>
11
12 <style type = "text/css">
13
14 a.nodec { text-decoration: none }
15
16 a:hover { text-decoration: underline;
17 color: red;
18 background-color: #ccffcc }
19
20 li em { color: red;
21 font-weight: bold }
22
23 ul { margin-left: 75px }
24

16
25 ul ul { text-decoration: underline;
26 margin-left: 15px }
Outline
27
28 </style>
29 </head>
30
31 <body>
32
33 <h1>Shopping list for <em>Monday</em>:</h1>
34
35 <ul>
36 <li>Milk</li>
37 <li>Bread
38 <ul>
39 <li>White bread</li>
40 <li>Rye bread</li>
41 <li>Whole wheat bread</li>
42 </ul>
43 </li>
44 <li>Rice</li>
45 <li>Potatoes</li>
46 <li>Pizza <em>with mushrooms</em></li>
47 </ul>
48

17
49 <p><a class = "nodec" href = "http://www.food.com">
50 Go to the Grocery store</a></p>
Outline
51
52 </body>
53 </html>

18
 External style sheets
◦ Can provide uniform look and feel to entire site

© Dept. of Industrial Management-2008 19


1 /* styles.css */
2 /* An external stylesheet */
Outline
3
4 a { text-decoration: none }
5
6 a:hover { text-decoration: underline;
7 color: red;
8 background-color: #ccffcc }
9
10 li em { color: red;
11 font-weight: bold;
12 background-color: #ffffff }
13
14 ul { margin-left: 2cm }
15
16 ul ul { text-decoration: underline;
17 margin-left: .5cm }

20
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- external.html -->
6 <!-- Linking external style sheets -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Linking External Style Sheets</title>
11 <link rel = "stylesheet" type = "text/css"
12 href = "styles.css" />
13 </head>
14
15 <body>
16
17 <h1>Shopping list for <em>Monday</em>:</h1>
18 <ul>
19 <li>Milk</li>
20 <li>Bread
21 <ul>
22 <li>White bread</li>
23 <li>Rye bread</li>
24 <li>Whole wheat bread</li>
25 </ul>

21
26 </li>
27 <li>Rice</li>
Outline
28 <li>Potatoes</li>
29 <li>Pizza <em>with mushrooms</em></li>
30 </ul>
31
32 <p>
33 <a href = "http://www.food.com">Go to the Grocery store</a>
34 </p>
35
36 </body>
37 </html>

22
 Validates external CSS documents
 Ensures that style sheets are syntactically
correct

© Dept. of Industrial Management-2008 23


Validating a CSS document. (Courtesy of World Wide Web Consortium (W3C).)

© Dept. of Industrial Management-2008 24


CSS validation results. (Courtesy of World Wide Web Consortium (W3C).)

© Dept. of Industrial Management-2008 25


 Absolute positioning
◦ z-index attribute
 Layer overlapping elements properly
 Relative positioning
◦ Elements are positioned relative to other elements

© Dept. of Industrial Management-2008 26


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- positioning.html -->
6 <!-- Absolute positioning of elements -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Absolute Positioning</title>
11 </head>
12
13 <body>
14
15 <p><img src = "i.gif" style = "position: absolute;
16 top: 0px; left: 0px; z-index: 1"
17 alt = "First positioned image" /></p>
18 <p style = "position: absolute; top: 50px; left: 50px;
19 z-index: 3; font-size: 20pt">Positioned Text</p>
20 <p><img src = "circle.gif" style = "position: absolute;
21 top: 25px; left: 100px; z-index: 2" alt =
22 "Second positioned image" /></p>
23
24 </body>
25 </html>

27
© Dept. of Industrial Management-2008 28
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- positioning2.html -->
6 <!-- Relative positioning of elements -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Relative Positioning</title>
11
12 <style type = "text/css">
13
14 p { font-size: 1.3em;
15 font-family: verdana, arial, sans-serif }
16
17 span { color: red;
18 font-size: .6em;
19 height: 1em }
20
21 .super { position: relative;
22 top: -1ex }
23
24 .sub { position: relative;
25 bottom: -1ex }
26

29
27 .shiftleft { position: relative;
28 left: -1ex }
Outline
29
30 .shiftright { position: relative;
31 right: -1ex }
32
33 </style>
34 </head>
35
36 <body>
37
38 <p>The text at the end of this sentence
39 <span class = "super">is in superscript</span>.</p>
40
41 <p>The text at the end of this sentence
42 <span class = "sub">is in subscript</span>.</p>
43
44 <p>The text at the end of this sentence
45 <span class = "shiftleft">is shifted left</span>.</p>
46
47 <p>The text at the end of this sentence
48 <span class = "shiftright">is shifted right</span>.</p>
49
50 </body>
51 </html>

30
© Dept. of Industrial Management-2008 31
 background-image
◦ Specifies the image URL
 background-position
◦ Places the image on the page
 background-repeat
◦ Controls the tiling of the background image
 background-attachment
◦ fixed
◦ scroll
 font-weight
◦ Specify the “boldness” of text

© Dept. of Industrial Management-2008 32


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- background.html -->
6 <!-- Adding background images and indentation -->
7
8 <html xmlns = "http://www.w3 .org/1999/xhtml">
9 <head>
10 <title>Background Images</title>
11
12 <style type = "text/css">
13
14 body { background-image: url(logo.gif);
15 background-position: bottom right;
16 background-repeat: no-repeat;
17 background-attachment: fixed; }
18
19 p { font-size: 18pt;
20 color: #aa5588;
21 text-indent: 1em;
22 font-family: arial, sans-serif; }
23
24 .dark { font-weight: bold; }
25

33
26 </style>
27 </head>
Outline
28
29 <body>
30
31 <p>
32 This example uses the background-image,
33 background-position and background-attachment
34 styles to place the <span class = "dark">Deitel
35 &amp; Associates, Inc.</span> logo in the bottom,
36 right corner of the page. Notice how the logo
37 stays in the proper position when you resize the
38 browser window.
39 </p>
40
41 </body>
42 </html>

34
© Dept. of Industrial Management-2008 35
 CSS rules can specify the actual dimensions
of each page element

© Dept. of Industrial Management-2008 36


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- width.html -->
6 <!-- Setting box dimensions and aligning text -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Box Dimensions</title>
11
12 <style type = "text/css">
13
14 div { background-color: #ffccff;
15 margin-bottom: .5em }
16 </style>
17
18 </head>
19
20 <body>
21
22 <div style = "width: 20%">Here is some
23 text that goes in a box which is
24 set to stretch across twenty percent
25 of the width of the screen.</div>

37
26
27 <div style = "width: 80%; text-align: center">
Outline
28 Here is some CENTERED text that goes in a box
29 which is set to stretch across eighty percent of
30 the width of the screen.</div>
31
32 <div style = "width: 20%; height: 30%; overflow: scroll">
33 This box is only twenty percent of
34 the width and thirty percent of the height.
35 What do we do if it overflows? Set the
36 overflow property to scroll!</div>
37
38 </body>
39 </html>

38
 Floating
◦ Move an element to one side of the screen
 Box model
◦ Margins
 margin-top, margin-right, margin-left, margin-bottom
◦ Padding
 padding-top, padding-right, padding-left, and padding-bottom
◦ Border
 border-width
 thin, medium, thick
 border-color
 Sets the color
 border-style
 none, hidden, dotted, dashed, solid, double, groove, ridge,
inset and outset

© Dept. of Industrial Management-2008 39


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- floating.html -->
6 <!-- Floating elements and element boxes -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Flowing Text Around Floating Elements</title>
11
12 <style type = "text/css">
13
14 div { background-color: #ffccff;
15 margin-bottom: .5em;
16 font-size: 1.5em;
17 width: 50% }
18
19 p { text-align: justify }
20
21 </style>
22
23 </head>
24

40
25 <body>
26
Outline
27 <div style = "text-align: center">
28 Deitel &amp; Associates, Inc.</div>
29
30 <div style = "float: right; margin: .5em;
31 text-align: right">
32 Corporate Training and Publishing</div>
33
34 <p>Deitel &amp; Associates, Inc. is an internationally
35 recognized corporate training and publishing organization
36 specializing in programming languages, Internet/World
37 Wide Web technology and object technology education.
38 The company provides courses on Java, C++, Visual Basic, C,
39 Internet and World Wide Web programming, and Object Technology.</p>
40
41 <div style = "float: right; padding: .5em;
42 text-align: right">
43 Leading-Edge Programming Textbooks</div>
44
45 <p>The company's clients include many Fortune 1000
46 companies, government agencies, branches of the military
47 and business organizations.</p>
48

41
49 <p style = "clear: right">Through its publishing
50 partnership with Prentice Hall, Deitel &amp; Associates,
Outline
51 Inc. publishes leading-edge programming textbooks,
52 professional books, interactive CD-ROM-based multimedia
53 Cyber Classrooms, satellite courses and World Wide Web
54 courses.</p>
55
56 </body>
57 </html>

42
Margin

Border
Content
Padding

Box model for block-level elements.

© Dept. of Industrial Management-2008 43


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- borders.html -->
6 <!-- Setting borders of an element -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Borders</title>
11
12 <style type = "text/css">
13
14 body { background-color: #ccffcc }
15
16 div { text-align: center;
17 margin-bottom: 1em;
18 padding: .5em }
19
20 .thick { border-width: thick }
21
22 .medium { border-width: medium }
23
24 .thin { border-width: thin }
25

44
26 .groove { border-style: groove }
27
Outline
28 .inset { border-style: inset }
29
30 .outset { border-style: outset }
31
32 .red { border-color: red }
33
34 .blue { border-color: blue }
35
36 </style>
37 </head>
38
39 <body>
40
41 <div class = "thick groove">This text has a border</div>
42 <div class = "medium groove">This text has a border</div>
43 <div class = "thin groove">This text has a border</div>
44
45 <p class = "thin red inset">A thin red line...</p>
46 <p class = "medium blue outset">
47 And a thicker blue line</p>
48
49 </body>
50 </html>

45
© Dept. of Industrial Management-2008 46
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- borders2.html -->
6 <!-- Various border-styles -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Borders</title>
11
12 <style type = "text/css">
13
14 body { background-color: #ccffcc }
15
16 div { text-align: center;
17 margin-bottom: .3em;
18 width: 50%;
19 position: relative;
20 left: 25%;
21 padding: .3em }
22 </style>
23 </head>
24
25 <body>

47
26
27 <div style = "border-style: solid">Solid border</div>
Outline
28 <div style = "border-style: double">Double border</div>
29 <div style = "border-style: groove">Groove border</div>
30 <div style = "border-style: ridge">Ridge border</div>
31 <div style = "border-style: inset">Inset border</div>
32 <div style = "border-style: outset">Outset border</div>
33
34 </body>
35 </html>

48
 Format pages based on preferences

© Dept. of Industrial Management-2008 49


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- user_absolute.html -->
6 <!-- User styles -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>User Styles</title>
11
12 <style type = "text/css">
13
14 .note { font-size: 9pt }
15
16 </style>
17 </head>
18
19 <body>
20
21 <p>Thanks for visiting my Web site. I hope you enjoy it.
22 </p><p class = "note">Please Note: This site will be
23 moving soon. Please check periodically for updates.</p>

50
24
25 </body>
Outline
26 </html>

51
1 /* Fig. 6.17: userstyles.css */
2 /* A user stylesheet */
Outline
3
4 body { font-size: 20pt;
5 color: yellow;
6 background-color: #000080 }

52
User style sheet in Internet Explorer 6.

© Dept. of Industrial Management-2008 53


User style sheet applied with pt measurement.

© Dept. of Industrial Management-2008 54


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
Outline
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- user_relative.html -->
6 <!-- User styles -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>User Styles</title>
11
12 <style type = "text/css">
13
14 .note { font-size: .75em }
15
16 </style>
17 </head>
18
19 <body>
20
21 <p>Thanks for visiting my Web site. I hope you enjoy it.
22 </p><p class = "note">Please Note: This site will be
23 moving soon. Please check periodically for updates.</p>

55
24
25 </body>
Outline
26 </html>

56
User style sheet applied with em measurement.

© Dept. of Industrial Management-2008 57


 www.w3.org/TR/css3-roadmap
 www.ddj.com/webreview/style
 tech.irt.org/articles/css.htm

© Dept. of Industrial Management-2008 58


Introduction to Scripting

By Pramudith Kandambi
Outline
 Introduction
 Simple Program: Printing a Line of Text in a Web Page
 Obtaining User Input with prompt Dialogs

 Dynamic Welcome Page


 Adding Integers

 Memory Concepts
 Arithmetic
 Decision Making: Equality and Relational Operators
 Web Resources

2
 In this lesson, you will be able to:

◦ write simple JavaScript programs.


◦ use input and output statements.
◦ understand basic memory concepts.
◦ use arithmetic operators.
◦ understand the precedence of arithmetic operators.
◦ write decision-making statements.
◦ use relational and equality operators.

3
 JavaScript was designed to add interactivity to HTML pages

 JavaScript is a scripting language

 A scripting language is a lightweight programming language

 JavaScript is usually embedded directly into HTML pages

 JavaScript is an interpreted language (means that scripts


execute without preliminary compilation)

 Everyone can use JavaScript without purchasing a license

4
 JavaScript's official name is ECMAScript.

 ECMAScript is developed and maintained by the ECMA


organization.

 ECMA-262 is the official JavaScript standard.

 The language was invented by Brendan Eich at


Netscape (with Navigator 2.0), and has appeared in all
Netscape and Microsoft browsers since 1996.

 The development of the standard is still in progress.


 NO!

 Java and JavaScript are two completely


different languages in both concept and
design!

 Java (developed by Sun Microsystems) is a


powerful and much more complex
programming language - in the same
category as C and C++.

6
 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

 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

 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

 JavaScript can read and write HTML elements –


◦ A JavaScript can read and change the content of an HTML element

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

 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

 JavaScript can be used to create cookies –


A JavaScript can be used to store and retrieve information on
the visitor's computer

8
 JavaScript is Case Sensitive

◦ <script> tag
 Indicate that the text is part of a script
 type attribute
 Specifies the type of file and the scripting language use
 writeln method
 Write a line in the document
 Escape character ( \ )
 Indicates “special” character is used in the string
 alert method
 Dialog box

9
 The HTML <script> tag is used to insert a JavaScript into an
HTML page.

<html>
<body>
<script type="text/javascript">

document.write("Hello World!");

</script>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function message()
{
alert(“Hello BIT !");
}
</script>
</head>
<body onload="message()">
</body>
</html>
 Browsers that do not support JavaScript,

◦ will display JavaScript as page content.


 To prevent them from doing this, and as a part of the JavaScript standard, the HTML
comment tag should be used to "hide" the JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>

 (//) is the JavaScript comment symbol. This prevents JavaScript from


executing the --> tag.
 JavaScripts in the body section will be
executed WHILE the page loads.

 JavaScripts in the head section will be


executed when CALLED.

 Where to Put the JavaScript


 JavaScript's in a page will be executed immediately
while the page loads into the browser. This is not
always what we want. Sometimes we want to execute a
script when a page loads, other times when a user
triggers an event.
 If you want to run the same JavaScript on several pages, without
having to write the same script on every page, you can write a
JavaScript in an external file.

 Save the external JavaScript file with a .js file extension.

 Note: The external script cannot contain the <script> tag!

 Example
<html>

<head>

<script type="text/javascript" src="xxx.js"> </script>


</head>

<body>
</body>

</html>
 Comments can be added to explain the
JavaScript, or to make the code more readable.

 Single line comments start with //.

 Multi line comments


◦ start with /*
◦ end with */.
 Rules for JavaScript variable names:

◦ Variable names are case sensitive (y and Y are two different variables)
◦ Variable names must begin with a letter or the underscore character

 Declaring (Creating) JavaScript Variables

 You can declare JavaScript variables with the var statement:


◦ var x;
◦ var carname;

 However, you can also assign values to the variables when you
declare them:

◦ var x=5;
◦ var carname=“Mazda3”;
 As with algebra, you can do arithmetic
operations with JavaScript variables:

 y=x-5;
 z=y+5;
Escape Description
sequence
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the current
line; do not advance to the next line. Any characters output after the
carriage return overwrite the characters previously output on that line.
\\ Backslash. Used to represent a backslash character in a string.
\" Double quote. Used to represent a double quote character in a string
contained in double quotes. For example,
window.alert( "\"in quotes\"" );
displays "in quotes" in an alert dialog.
\' Single quote. Used to represent a single quote character in a string. For
example,
window.alert( '\'in quotes\'' );
displays 'in quotes' in an alert dialog.
Some common escape sequences.

18
 A script can adapt the content based on input
from the user or other variables

19
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- welcome5.html -->
6 <!-- Using Prompt Boxes -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using Prompt and Alert Boxes</title>
11
12 <script type = "text/javascript">
13 <!--
14 var name; // string entered by the user
15
16 // read the name from the prompt box as a string
17 name = window.prompt( "Please enter your name", "GalAnt" );
18
19 document.writeln( "<h1>Hello, " + name +
20 ", welcome to JavaScript programming!</h1>" );
21 // -->
22 </script>
20
23
24 </head>
25
26 <body>
27 <p>Click Refresh (or Reload) to run this script again.</p>
28 </body>
29 </html>

21
When the user clicks OK, the
value typed by the user is
returned to the program as a
This is the string.
prompt
to the user.

This is the text field in


This is the default value
which the user types the
that appears when the
value.
dialog opens.

Prompt dialog displayed by the window object’s prompt method.

22
 Prompt user for two integers and calculate
the sum
 NaN (not a number)
 parseInt
◦ Converts its string argument to an integer

23
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Addition.html -->
6 <!-- Addition Program -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>An Addition Program</title>
11
12 <script type = "text/javascript">
13 <!--
14 var firstNumber, // first string entered by user
15 secondNumber, // second string entered by user
16 number1, // first number to add
17 number2, // second number to add
18 sum; // sum of number1 and number2
19
20 // read in first number from user as a string
21 firstNumber =
22 window.prompt( "Enter first integer", "0" );
23

24
24 // read in second number from user as a string
25 secondNumber =
26 window.prompt( "Enter second integer", "0" );
27
28 // convert numbers from strings to integers
29 number1 = parseInt( firstNumber );
30 number2 = parseInt( secondNumber );
31
32 // add the numbers
33 sum = number1 + number2;
34
35 // display the results
36 document.writeln( "<h1>The sum is " + sum + "</h1>" );
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>

25
26
 Variable names correspond to locations in the
computer’s memory
 Every variable has a name, a type, and a value
 Read value from a memory location
◦ nondestructive

27
number1 45

Memory location showing the name and value of variable number1.

28
number1 45

number2 72

Memory locations after values for variables number1 and number2 have been input.

29
number1 45

number2 72

sum 117

Memory locations after calculating the sum of number1 and number2.

30
 Many scripts perform arithmetic calculations
◦ Expressions in JavaScript must be written in
straight-line form

31
Operator Description Example Result

+ Addition x=y+2 x=7

- Subtraction x=y-2 x=3

* Multiplication x=y*2 x=10

/ Division x=y/2 x=2.5

% Modulus (division x=y%2 x=1


remainder)
++ Increment x=++y x=6

-- Decrement x=--y x=4


Operator(s) Operation(s) Order of evaluation (precedence)
*, / or % Multiplication Evaluated second. If there are several such
Division operations, x--they are evaluated from left to
y
Modulus right.
+ or - Addition Evaluated last. If there are several such
Subtraction operations, they are evaluated from left to
right.
Precedence of arithmetic operators.

33
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;
2 * 5 is 10 (Leftmost multiplication)

Step 2. y = 10 * 5 + 3 * 5 + 7;

10 * 5 is 50 (Leftmost multiplication)

Step 3. y = 50 + 3 * 5 + 7;
3 * 5 is 15 (Multiplication before addition)

Step 4. y = 50 + 15 + 7;
50 + 15 is 65 (Leftmost addition)

Step 5. y = 65 + 7;
65 + 7 is 72 (Last addition)

Step 6.y = 72;


Order in which a second-degree polynomial is evaluated. (Last operation—place
34
 Decision based on the truth or falsity of a
condition
◦ Equality operators
◦ Relational operators

35
Operator Example Same As Result

= x=y x=5

+= x+=y x=x+y x=15

-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0


Operator Description Example

== is equal to x==8 is false

=== is exactly equal to (value and x===5 is true


type) x==="5" is false

!= is not equal x!=8 is true

> is greater than x>8 is false

< is less than x<8 is true

>= is greater than or equal to x>=8 is false

<= is less than or equal to x<=8 is true

37
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- welcome6.html -->
6 <!-- Using Relational Operators -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using Relational Operators</title>
11
12 <script type = "text/javascript">
13 <!--
14 var name, // string entered by the user
15 now = new Date(), // current date and time
16 hour = now.getHours(); // current hour (0-23)
17
18 // read the name from the prompt box as a string
19 name = window.prompt( "Please enter your name", "GalAnt" );
20
21 // determine whether it is morning
22 if ( hour < 12 )
23 document.write( "<h1>Good Morning, " );
24

38
25 // determine whether the time is PM
26 if ( hour >= 12 )
27 {
28 // convert to a 12 hour cl ock
29 hour = hour - 12;
30
31 // determine whether it is before 6 PM
32 if ( hour < 6 )
33 document.write( "<h1>Go od Afternoon, " );
34
35 // determine whether it is after 6 PM
36 if ( hour >= 6 )
37 document.write( "<h1>Go od Evening, " );
38 }
39
40 do cument.writeln( name +
41 ", welcome to JavaScript p rogramming!</h1>" );
42 // -->
43 </scr ipt>
44
45 </head>
46

39
47 <body>
48 <p>Click Refresh (or Reload) to run this script again.</p>
49 </body>
50 </html>

40
Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true

41
 Use the if....else statement to execute some code if a
condition is true and another code if the condition is not
true.

 Syntax
if (condition)
{
code to be executed if condition is true
}

else
{
code to be executed if condition is not true
}
 Use the if....else statement to execute some code if a
condition is true and another code if the condition is not
true.

 Syntax
if (condition)
{
code to be executed if condition is true
}

else
{
code to be executed if condition is not true
}
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>
 Use the switch statement to select one of
many blocks of code to be executed.
 Syntax
switch(n)
{
case 1:
execute code block 1
break;

case 2:
execute code block 2
break;

default:
code to be executed if n is different from case 1 and 2
}
 First we have a single expression n (most often a
variable), that is evaluated once.

 The value of the expression is then compared


with the values for each case in the structure.

 If there is a match, the block of code associated


with that case is executed.

 Use break to prevent the code from running into


the next case automatically.
 <script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();

switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
 Controlling expression
 Case labels
 Default case

48
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SwitchTest.html -->
6 <!-- Using the switch statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Switching between XHTML List Formats</title>
11
12 <script type = "text/javascript">
13 <!--
14 var choice, // user’s choice
15 startTag, // starting list item tag
16 endTag, // ending list item tag
17 validInput = true, // indicates if input is valid
18 listType; // list type as a string
19
20 choice = window.prompt( "Select a list style:\n" +
21 "1 (bullet), 2 (numbered), 3 (lettered)", "1" );
22

49
23 switch ( choice ) {
24 case "1":
25 startTag = "<ul>";
26 endTag = "</ul>";
27 listType = "<h1>Bullet List</h1>";
28 break;
29 case "2":
30 startTag = "<ol>";
31 endTag = "</ol>";
32 listType = "<h1>Ordered List: Numbered</h1>";
33 break;
34 case "3":
35 startTag = "<ol type = \"A\">";
36 endTag = "</ol>";
37 listType = "<h1>Ordered List: Lettered</h1>";
38 break;
39 default:
40 validInput = false;
41 }
42
43 if ( validInput == true ) {
44 document.writeln( listType + startTag );
45
46 for ( var i = 1; i <= 3; ++i )
47 document.writeln( "<li>List item " + i + "</li>" );

50
48
49 document.writeln( endTag );
50 }
51 else
52 document.writeln( "Invalid choice: " + choice );
53 // -->
54 </script>
55
56 </head>
57 <body>
58 <p>Click Refresh (or Reload) to run the script again</p>
59 </body>
60 </html>

51
52
53
case a true
case a action(s) break

false

true
case b case b action(s) break

false

.
.
.

true
case z case z action(s) break

false

default action(s)

54
 Syntax

function functionname (var1,var2,...,varX)


{
some code
}
 The parameters var1, var2, etc. are variables or values passed into the
function.

 Note: A function with no parameters must include the parentheses ()


after the function name.

 Note: Do not forget about the importance of capitals in JavaScript! The


word function must be written in lowercase letters, otherwise a
JavaScript error occurs! Also note that you must call a function with the
exact same capitals as in the function name.
<html>
<head>

<script type="text/javascript">

function displaymessage()
{
alert("Hello World!");
}
</script>

</head>
<body>
<form>
<input type="button" value="Click me!“ onclick="displaymessage()" />
</form>
</body>

</html>
By Pramudith Kandambi

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 1


Outline
9 Introduction
9 Essentials of Counter-Controlled Repetition
9 for Repetition Statement
9 Examples Using the for Statement
9 switch Multiple-Selection Statement
9 do…while Repetition Statement
9 break and continue Statements
9 Labeled break and continue Statements
9 Logical Operators
9 Summary of Structured Programming
9 Web Resources
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 2
Objectives

y End of this lesson, you will be able to:


y to use the for and do…while repetition statements to
execute statements in a program repeatedly.
y To understand multiple selection using the switch selection
statement.
y to use the break and continue program-control statements.
y to use the logical operators.

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 3


JavaScript Loops

y In JavaScript, there are two different kind of loops:

y for - loops through a block of code a specified number of


times

y while - loops through a block of code while a specified


condition is true

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 4


The for Loop

y when you know in advance how many times the script


should run.
Syntax
for (var=startvalue; var<=endvalue; var=var+increment)
{
code to be executed
}
y Note: The increment parameter could also be negative, and
the <= could be any comparing statement

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 5


for keyword Control variable name Final value of control variable
for which the condition is true

for ( var counter = 1; counter <= 7; ++counter )

Initial value of control variable Increment of control variable


Loop-continuation condition

for statement header components.

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 6


Establish
initial value
of control
variable.
var counter = 1

document.writeln(
true "<p style=\"font-size: "
counter <= 7 ++counter
+ counter +
"ex\">XHTML font size " + Increment
counter + "ex</p>" ); the control
false variable.
Determine Body of loop
(this may be many
if final value
of control statements)
variable
has been
reached.

for repetition structure flowchart.

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 7


Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 8


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- ForCounter.html -->
6 <!-- Counter-Controlled Repetition with for statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Counter-Controlled Repetition</title>
11
12 <script type = "text/javascript">
13 <!--
14 // Initialization, repetition condition and
15 // incrementing are all included in the for
16 // statement header.
17 for ( var counter = 1; counter <= 7; ++counter )
18 document.writeln( "<p style = \"font-size: " +
19 counter + "ex\">XHTML font size " + counter +
20 "ex</p>" );
21 // -->
22 </script>
23
24 </head><body></body>
25 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 9


Out Put

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 10


Examples Using the for
Statement

y Summation with for


y Compound interest calculation with for loop
y Math object
y Method pow
y Method round

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 11


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Sum.html -->
6 <!-- Using the for repetition statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Sum the Even Integers from 2 to 100</title>
11
12 <script type = "text/javascript">
13 <!--
14 var sum = 0;
15
16 for ( var number = 2; number <= 100; number += 2 )
17 sum += number;
18
19 document.writeln( "The sum of the even integers " +
20 "from 2 to 100 is " + sum );
21 // -->
22 </script>
23
24 </head><body></body>
25 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 12


Out Put

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 13


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Interest.html -->
6 <!-- Using the for repetition statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Calculating Compound Interest</title>
11
12 <script type = "text/javascript">
13 <!--
14 var amount, principal = 1000.0, rate = .05;
15
16 document.writeln(
17 "<table border = \"1\" width = \"100%\">" );
18 document.writeln(
19 "<caption>Calculating Compound Interest</caption>" );
20 document.writeln(
21 "<thead><tr><th align = \"left\">Year</th>" );
22 document.writeln(
23 "<th align = \"left\">Amount on deposit</th>" );
24 document.writeln( "</tr></thead>" );
25
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 14
26 for ( var year = 1; year <= 10; ++year ) {
27 amount = principal * Math.pow( 1.0 + rate, year );
28 document.writeln( "<tbody><tr><td>" + year +
Outline
29 "</td><td>" + Math.round( amount * 100 ) / 100 +
30 "</td></tr>" );
31 }
32
33 document.writeln( "</tbody></table>" );
34 // -->
35 </script>
36
37 </head><body></body>
38 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 15


The while Loop

y loops through a block of code while a specified condition


is true.
Syntax
while (var<=endvalue)
{
code to be executed
}
y Note: The <= could be any comparing statement.

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 16


Example

<html>
<body>
<script type="text/javascript">

var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 17
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- WhileCounter.html -->
6 <!-- Counter-Controlled Repetition -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Counter-Controlled Repetition</title>
11
12 <script type = "text/javascript">
13 <!--
14 var counter = 1; // initialization
15
16 while ( counter <= 7 ) { // repetition condition
17 document.writeln( "<p style = \"font-size: " +
18 counter + "ex\">XHTML font size " + counter +
19 "ex</p>" );
20 ++counter; // increment
21 }
22 // -->
23 </script>
24

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 18


25 </head><body></body>
Outline
26 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 19


The do...while Loop

y Variant of the while loop. This loop will execute the block
of code ONCE, and then it will repeat the loop as long as
the specified condition is true.
Syntax
do
{
code to be executed
}
while (var<=endvalue);

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 20


Example

<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 21


action(s)

true
condition

false

do…while repetition statement flowchart.

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 22


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- DoWhileTest.html -->
6 <!-- Using the do...while statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the do...while Repetition Statement</title>
11
12 <script type = "text/javascript">
13 <!--
14 var counter = 1;
15
16 do {
17 document.writeln( "<h" + counter + ">This is " +
18 "an h" + counter + " level head" + "</h" +
19 counter + ">" );
20
21 ++counter;
22 } while ( counter <= 6 );
23 // -->
24 </script>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 23


25
Outline
26 </head><body></body>
27 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 24


break and continue
Statements

y break
Immediate exit from the structure
y
y Used to escape early from a loop
y Skip the remainder of a switch statement
y continue
y Skips the remaining statements in the body of the structure
y Proceeds with the next iteration of the loop

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 25


JavaScript Break Statements
y The break Statement

y The break statement will break the loop and continue executing the code that
follows after the loop (if any).
y Example
y
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 26
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- BreakTest.html -->
6 <!-- Using the break statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Using the break Statement in a for Structure
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 for ( var count = 1; count <= 10; ++count ) {
17 if ( count == 5 )
18 break; // break loop only if count == 5
19
20 document.writeln( "Count is: " + count + "<br />" );
21 }
22

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 27


23 document.writeln(
24 "Broke out of loop at count = " + count ); Outline
25 // -->
26 </script>
27
28 </head><body></body>
29 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 28


The continue Statement
y Will break the current loop and continue with the next value.

<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}

document.write("The number is " + i);


document.write("<br />");

}
</script>
11/1/2009 Pramudith Kandambi_MIT_2009_BIT 29
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- ContinueTest.html -->
6 <!-- Using the break statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Using the continue Statement in a for Structure
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 for ( var count = 1; count <= 10; ++count ) {
17 if ( count == 5 )
18 continue; // skip remaining code in loop
19 // only if count == 5
20
21 document.writeln( "Count is: " + count + "<br />" );
22 }
23

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 30


24 document.writeln( "Used continue to skip printing 5" );
25 // --> Outline
26 </script>
27
28 </head><body></body>
29 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 31


Labeled break and
continue Statements
y Labeled break statement
y Break out of a nested set of structures
y Immediate exit from that structure and enclosing repetition
structures
y Execution resumes with first statement after enclosing labeled
statement
y Labeled continue statement
y Skips the remaining statements in structure’s body and enclosing
repetition structures
y Proceeds with next iteration of enclosing labeled repetition
structure
y Loop-continuation test evaluates immediately after the continue
statement executes

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 32


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- BreakLabelTest.html -->
6 <!-- Using the break statement with a Label -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the break Statement with a Label</title>
11
12 <script type = "text/javascript">
13 <!--
14 stop: { // labeled block
15 for ( var row = 1; row <= 10; ++row ) {
16 for ( var column = 1; column <= 5 ; ++column ) {
17
18 if ( row == 5 )
19 break stop; // jump to end of stop block
20
21 document.write( "* " );
22 }
23
24 document.writeln( "<br />" );
25 }

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 33


26
27 // the following line is skipped
Outline
28 document.writeln( "This line should not print" );
29 }
30
31 document.writeln( "End of script" );
32 // -->
33 </script>
34
35 </head><body></body>
36 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 34


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- ContinueLabelTest.html -->
6 <!-- Using the continue statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the continue Statement with a Label</title>
11
12 <script type = "text/javascript">
13 <!--
14 nextRow: // target label of continue statement
15 for ( var row = 1; row <= 5; ++row ) {
16 document.writeln( "<br />" );
17
18 for ( var column = 1; column <= 10; ++column ) {
19
20 if ( column > row )
21 continue nextRow; // next iteration of
22 // labeled loop
23
24 document.write( "* " );
25 }

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 35


26 }
27 // --> Outline
28 </script>
29
30 </head><body></body>
31 </html>

11/1/2009 Pramudith Kandambi_MIT_2009_BIT 36


By Pramudith Kandambi
Outline
Introduction
Thinking About Objects

String Object
Fundamentals of Characters and Strings
Methods of the String Object
Character-Processing Methods
Searching Methods
Splitting Strings and Obtaining Substrings
Math Object
Date Object
Boolean and Number Objects
document Object
window Object
Web Resources
© Pramudith_Kandambi_MIT_BIT_2009 2
JavaScript Objects
Introduction
 Define your own objects and own variable types.
 An object is just a special kind of data.
 Properties and methods.

© Pramudith_Kandambi_MIT_BIT_2009 3
Properties
 Properties are the values associated with an object.
 length property of the String object

<script type="text/javascript">

var txt="Hello World!";


document.write(txt.length);

</script>
 To return the number of characters in a string:

© Pramudith_Kandambi_MIT_BIT_2009 4
Methods
 Actions that can be performed on objects.
 ToUpperCase() method of the String object

<script type="text/javascript">

var str="Hello world!";


document.write(str.toUpperCase());
</script>

• To display a text in uppercase letters:

© Pramudith_Kandambi_MIT_BIT_2009 5
String Object
Property Description FF IE
constructor A reference to the function that created the object 1 4
length Returns the number of characters in a string 1 3
prototype Allows you to add properties and methods to the object 1 4

Method Description FF IE
anchor() Creates an HTML anchor 1 3
big() Displays a string in a big font 1 3
blink() Displays a blinking string 1
bold() Displays a string in bold 1 3
charAt() Returns the character at a specified position 1 3
charCodeAt() Returns the Unicode of the character at a specified position 1 4
concat() Joins two or more strings 1 4
fixed() Displays a string as teletype text 1 3
fontcolor() Displays a string in a specified color 1 3
fontsize() Displays a string in a specified size 1 3

© Pramudith_Kandambi_MIT_BIT_2009 6
String Object Cont…
fromCharCode() Takes the specified Unicode values and returns a string 14
indexOf() Returns the position of the first occurrence of a specified string value in a 13
string
italics() Displays a string in italic 13
lastIndexOf() Returns the position of the last occurrence of a specified string value, 13
searching backwards from the specified position in a string
link() Displays a string as a hyperlink 13
match() Searches for a specified value in a string 14
replace() Replaces some characters with some other characters in a string 14
search() Searches a string for a specified value 14
slice() Extracts a part of a string and returns the extracted part in a new string 14
small() Displays a string in a small font 13
split() Splits a string into an array of strings 14
strike() Displays a string with a strikethrough 13
sub() Displays a string as subscript 13
substr() Extracts a specified number of characters in a string, from a start index 14
substring() Extracts the characters in a string between two specified indices 13
sup() Displays a string as superscript 13
toLowerCase() Displays a string in lowercase letters 13
toUpperCase() Displays a string in uppercase letters 13
toSource() Represents the source code of an object 1-
valueOf() Returns the primitive value of a String object 14

© Pramudith_Kandambi_MIT_BIT_2009 7
Example –object Property

<html>
<body>

<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
</body>
</html>
© Pramudith_Kandambi_MIT_BIT_2009 8
Methods generate XHTML
tags
Methods that generate
XHTML tags
anchor( name ) Wraps the source string in an anchor element
(<a></a>) with name as the anchor name.
blink() Wraps the source string in a <blink></blink>
element.
fixed() Wraps the source string in a <tt></tt>
element.
link( url ) Wraps the source string in an anchor element
(<a></a>) with url as the hyperlink location.
strike() Wraps the source string in a
<strike></strike> element.
sub() Wraps the source string in a <sub></sub>
element.
sup() Wraps the source string in a <sup></sup>
element.
String object methods.

© Pramudith_Kandambi_MIT_BIT_2009 9
Example –object method
<html>
<body>

<script type="text/javascript">

var txt="Hello World!";

document.write("<p>Big: " + txt.big() + "</p>");


document.write("<p>Small: " + txt.small() + "</p>");

document.write("<p>Bold: " + txt.bold() + "</p>");


document.write("<p>Italic: " + txt.italics() + "</p>");

document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>");


document.write("<p>Fixed: " + txt.fixed() + "</p>");

© Pramudith_Kandambi_MIT_BIT_2009 10
Example –object method
Cont…
document.write("<p>Strike: " + txt.strike() + "</p>");

document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>");


document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>");

document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>");


document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>");

document.write("<p>Subscript: " + txt.sub() + "</p>");


document.write("<p>Superscript: " + txt.sup() + "</p>");

document.write("<p>Link: " + txt.link("http://www.w3schools.com")+"</p>");

</script>

</body>
</html>
© Pramudith_Kandambi_MIT_BIT_2009 11
Example –object method
<html>
<body>

<script type="text/javascript">
var str="Hello world!";
document.write(str.match("world") + "<br />");
document.write(str.match("World") + "<br />");
document.write(str.match("worlld") + "<br />");
document.write(str.match("world!"));
</script>

</body>
</html>
© Pramudith_Kandambi_MIT_BIT_2009 12
Searching Methods Try Your
Self

 indexOf and lastIndexOf


 Search for a specified substring in a string

© Pramudith_Kandambi_MIT_BIT_2009 13
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SearchingStrings.html -->
6 <!-- Searching Strings -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Searching Strings with indexOf and lastIndexOf
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm";
17
18 function buttonPressed()
19 {
20 searchForm.first.value =
21 letters.indexOf( searchForm.inputVal.value );
22 searchForm.last.value =
23 letters.lastIndexOf( searchForm.inputVal.value );
24 searchForm.first12.value =
25 letters.indexOf( searchForm.inputVal.value, 12 );
26 s e a r ch F o r m. l a st 1 2 . va l u e =
27 l e tt e r s. l a st I n d ex O f (
28 s e a rc h F or m . i np u t V al . v al u e , 1 2 ) ;
29 }
30 // - - >
31 < /s cr ip t >
32
33 </ he ad >
34 <b od y>
35 < fo rm n a m e = " s ea r c hF o r m " a c t io n = " " >
36 <h 1> T h e s t r i ng t o s e a rc h is : < b r / >
37 a b c de f g h ij k l mn o p q rs t u vw x y z ab c d ef g h i jk l m < /h 1 >
38 <p >E n t e r s u b st r i ng t o s e a r ch f or
39 <i np u t na m e = " i np u t V al " t yp e = " t ex t " / >
40 <i np u t n am e = " s ea r c h " t y pe = "b u t to n " va l u e = " Se a r ch "
41 o nc l i ck = " b u t to n P re s s e d( ) " / > < b r / > < /p >
42
43 <p >F i r s t o c c ur r e nc e l oc a t e d a t i n d ex
44 <i np u t na m e = " f ir s t " t y p e = " te x t " s i z e = " 5" / >
45 <b r / > L a st o cc u r re n c e l o c a te d at i nd e x
46 <i np u t n am e = " l as t " ty p e = " t ex t " s i z e = " 5 " / >
47 <b r / > F i rs t oc c u rr e n c e f r o m i n de x 12 l o ca t e d a t in d e x
48 <i np u t n am e = " f ir s t 1 2" t y pe = " t e xt " s i ze = " 5 " / >
49 <b r / > L a st o cc u r re n c e f r o m i n d ex 1 2 l o c at e d at i nd e x
50 <i np u t n am e = " l as t 1 2 " t y pe = "t e x t" s i ze = "5 " /> < / p>
51 </form>
52 </body>
53 </html>
© Pramudith_Kandambi_MIT_BIT_2009 17
Splitting and Substrings Try your
Self

 Tokenization
 The process of breaking a string into tokens
 Tokens
 Individual words
 Separated by delimiters

© Pramudith_Kandambi_MIT_BIT_2009 18
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SplitAndSubString.html -->
6 <!-- String Method split and substring -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>String Method split and substring</title>
11
12 <script type = "text/javascript">
13 <!--
14 function splitButtonPressed()
15 {
16 var strings = myForm.inputVal.value.split( " " );
17 myForm.output.value = strings.join( "\n" );
18
19 myForm.outputSubstring.value =
20 myForm.inputVal.value.substring( 0, 10 );
21 }
22 // -->
23 </script>
24 </head>
25
26 <body>
27 <form name = "myForm" action = "">
28 <p>Enter a sentence to split into words<br />
29 <input name = "inputVal" type = "text" size = "40" />
30 <input name = "splitButton" type = "button" value =
31 "Split" onclick = "splitButtonPressed()" /></p>
32
33 <p>The sentence split into words is<br />
34 <textarea name = "output" rows = "8" cols = "34">
35 </textarea></p>
36
37 <p>The first 10 characters of the input string are
38 <input name = "outputSubstring" type = "text"
39 size = "15" /></p>
40 </form>
41 </body>
42 </html>
© Pramudith_Kandambi_MIT_BIT_2009 21
Math Object

 Allow the programmer to perform many common


mathematical calculations

© Pramudith_Kandambi_MIT_BIT_2009 22
Math Object
Method Description Example
abs( x ) absolute value of x abs( 7.2 ) is 7.2
abs( 0.0 ) is 0.0
abs( -5.6 ) is 5.6
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
integer not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential method ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
integer not greater than x floor( -9.8 ) is -10.0
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
(base e) log( 7.389056 ) is 2.0
max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
Math object methods.
© Pramudith_Kandambi_MIT_BIT_2009 23
min( x, y ) smaller value of x min( 2.3, 12.7 ) is 2.3
and y min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y pow( 2.0, 7.0 ) is 128.0
(xy) pow( 9.0, .5 ) is 3.0
round( x ) rounds x to the round( 9.75 ) is 10
closest integer round( 9.25 ) is 9
sin( x ) trigonometric sine of sin( 0.0 ) is 0.0
x (x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent tan( 0.0 ) is 0.0
of x
(x in radians)
Math object methods.

© Pramudith_Kandambi_MIT_BIT_2009 24
Constant Description Value
Math.E Base of a natural Approximately 2.718.
logarithm (e).
Math.LN2 Natural logarithm of 2. Approximately 0.693.
Math.LN10 Natural logarithm of 10. Approximately 2.302.
Math.LOG2E Base 2 logarithm of e. Approximately 1.442.
Math.LOG10E Base 10 logarithm of e. Approximately 0.434.
Math.PI —the ratio of a circle’s Approximately
circumference to its 3.141592653589793.
diameter.
Math.SQRT1_2 Square root of 0.5. Approximately 0.707.
Math.SQRT2 Square root of 2.0. Approximately 1.414.
Properties of the Math object.

© Pramudith_Kandambi_MIT_BIT_2009 25
Method Description
getDate() Returns a number from 1 to 31 representing the day of the month in local time or
getUTCDate() UTC, respectively.
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the
getUTCDay() week in local time or UTC, respectively.
getFullYear() Returns the year as a four-digit number in local time or UTC, respectively.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time or
getUTCHours() UTC, respectively.
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in local
getUTCMilliSeconds() time or UTC, respectively. The time is stored in hours, minutes, seconds and
milliseconds.
getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time
getUTCMinutes() or UTC, respectively.
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in
getUTCMonth() local time or UTC, respectively.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time
getUTCSeconds() or UTC, respectively.
getTime() Returns the number of milliseconds between January 1, 1970 and the time in the
Date object.
getTimezoneOffset() Returns the difference in minutes between the current time on the local computer
and UTC—previously known as Greenwich Mean Time (GMT).
setDate( val ) Sets the day of the month (1 to 31) in local time or UTC, respectively.
setUTCDate( val )
Methods of the Date object.
© Pramudith_Kandambi_MIT_BIT_2009 26
Method Description
setFullYear( y, m, d ) Sets the year in local time or UTC, respectively. The second and third
setUTCFullYear( y, m, d ) arguments representing the month and the date are optional. If an
optional argument is not specified, the current value in the Date object
is used.
setHours( h, m, s, ms ) Sets the hour in local time or UTC, respectively. The second, third and
setUTCHours( h, m, s, ms ) fourth arguments representing the minutes, seconds and milliseconds
are optional. If an optional argument is not specified, the current value
in the Date object is used.

setMilliSeconds( ms ) Sets the number of milliseconds in local time or UTC, respectively.


setUTCMilliseconds( ms )
setMinutes( m, s, ms ) Sets the minute in local time or UTC, respectively. The second and
setUTCMinutes( m, s, ms ) third arguments representing the seconds and milliseconds are optional.
If an optional argument is not specified, the current value in the Date
object is used.
setMonth( m, d ) Sets the month in local time or UTC, respectively. The second
setUTCMonth( m, d ) argument representing the date is optional. If the optional argument is
not specified, the current date value in the Date object is used.

setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second
setUTCSeconds( s, ms ) argument representing the milliseconds is optional. If this argument is
not specified, the current millisecond value in the Date object is used.

© Pramudith_Kandambi_MIT_BIT_2009 27
Methods of the Date object.
Method Description
setTime( ms ) Sets the time based on its argument—the number of elapsed
milliseconds since January 1, 1970.
toLocaleString() Returns a string representation of the date and time in a form
specific to the computer’s locale. For example, September 13,
2001 at 3:42:22 PM is represented as 09/13/01 15:47:22 in
the United States and 13/09/01 15:47:22 in Europe.
toUTCString() Returns a string representation of the date and time in the
form: 19 Sep 2001 15:47:22 UTC
toString() Returns a string representation of the date and time in a form
specific to the locale of the computer (Mon Sep 19 15:47:22
EDT 2001 in the United States).
valueOf() The time in number of milliseconds since midnight, January
1, 1970.
Methods of the Date object.

© Pramudith_Kandambi_MIT_BIT_2009 28
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- DateTime.html -->
6 <!-- Date and Time Methods -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Date and Time Methods</title>
11
12 <script type = "text/javascript">
13 <!--
14 var current = new Date();
15
16 document.writeln(
17 "<h1>String representations and valueOf</h1>" );
18 document.writeln( "toString: " + current.toString() +
19 "<br />toLocaleString: " + current.toLocaleString() +
20 "<br />toUTCString: " + current.toUTCString() +
21 "<br />valueOf: " + current.valueOf() );
22
23 document.writeln(
24 "<h1>Get methods for local time zone</h1>" );
25 do cu m e n t. w r i te l n ( " g e tD a t e: " + c u rr e n t .g e t D at e ( ) +
26 " < b r /> g e tD a y : " + c u r r en t . ge t D ay ( ) +
27 " < b r /> g e tM o n th : " + c ur r e n t. g e tM o n t h( ) +
28 " < b r /> g e tF u l lY e a r : " + c u r re n t .g e t F ul l Y e ar ( ) +
29 " < b r /> g e tT i m e: " + c u rr e n t .g e t Ti m e ( ) +
30 " < b r / > g e tH o u rs : " + c ur r e n t. g e tH o u r s( ) +
31 " < b r /> g e tM i n ut e s : " + c u r r en t . ge t M i nu t e s( ) +
32 " < b r /> g e tS e c on d s : " + c u r r en t . ge t S e co n d s( ) +
33 " < b r /> g e tM i l li s e c on d s : " +
34 c u r r e nt . g et M i ll i s e co n d s () +
35 " < b r /> g e tT i m ez o n e Of f s e t: " +
36 c u r r en t . g et T i me z o n eO f f se t ( ) ) ;
37
38 do cu m e n t .w r i te l n (
39 " < h 1 > Sp e c if y i ng a r gu m e n ts f or a n e w Da t e < /h 1 > " ) ;
40 va r a n o t he r D at e = n e w D a t e( 2 0 01 , 2, 1 8 , 1 , 5, 0 , 0 );
41 do cu m e n t. w r i te l n ( " D a te : " + a no t h er D a t e ) ;
42
43 do cu m e n t. w r i te l n (
44 " < h 1 >S e t me t h od s f or l oc a l ti m e z o n e </ h 1 > " ) ;
45 an ot h e r Da t e . se t D at e ( 31 ) ;
46 an ot h e r Da t e . se t M on t h ( 1 1 ) ;
47 an ot h e r Da t e . se t F ul l Y e ar ( 2 00 1 );
48 an ot h e r Da t e . se t H ou r s ( 2 3 ) ;
49 an ot h e r Da t e . se t M in u t e s( 5 9 ) ;
50 anotherDate.setSeconds( 59 );
51 document.writeln( "Modified date: " + anotherDate );
52 // -->
53 </script>
54
55 </head><body></body>
56 </html>
Boolean and Number Objects

 Object wrappers for boolean true/false values and


numbers

Method Description
toString() Returns the string “true” if the value of the Boolean object is
true; otherwise, returns the string “false.”
valueOf() Returns the value true if the Boolean object is true; otherwise,
returns false.
Boolean object methods.

© Pramudith_Kandambi_MIT_BIT_2009 32
Method or Property Description
toString( radix ) Returns the string representation of the number. The optional radix
argument (a number from 2 to 36) specifies the number’s base. For
example, radix 2 results in the binary representation of the number,
8 results in the octal representation, 10 results in the decimal
representation and 16 results in the hexadecimal representation.
See Appendix E, Number Systems for a review of the binary, octal,
decimal and hexadecimal number systems.
valueOf() Returns the numeric value.
Number.MAX_VALUE This property represents the largest value that can be stored in a
JavaScript program—approximately 1.79E+308
Number.MIN_VALUE This property represents the smallest value that can be stored in a
JavaScript program—approximately
2.22E–308
Number.NaN This property represents not a number—a value returned from an
arithmetic expression that does not result in a number (e.g., the
expression parseInt( "hello" ) cannot convert the string
"hello" into a number, so parseInt would return
Number.NaN. To determine whether a value is NaN, test the
result with function isNaN, which returns true if the value is
NaN; otherwise, it returns false.
Number.NEGATIVE_INFINITY This property represents a value less than
-Number.MAX_VALUE.
Number.POSITIVE_INFINITY This property represents a value greater than
Number.MAX_VALUE.
Number object methods and properties.
© Pramudith_Kandambi_MIT_BIT_2009 33
document Object
 Manipulate document that is currently visible in the
browser window
Method or Property Description
write( string ) Writes the string to the XHTML document as
XHTML code.
writeln( string ) Writes the string to the XHTML document as
XHTML code and adds a newline character at
the end.
document.cookie This property is a string containing the values of
all the cookies stored on the user’s computer for
the current document. See Section 12.9, Using
Cookies.
document.lastModified This property is the date and time that this
document was last modified.
Important document object methods and properties.

© Pramudith_Kandambi_MIT_BIT_2009 34
window Object

 Provides methods for manipulating browser window

© Pramudith_Kandambi_MIT_BIT_2009 35
Method or Property Description
open( url, name, options ) Creates a new window with the URL of the window set to
url, the name set to name, and the visible features set by
the string passed in as option.
prompt( prompt, default ) Displays a dialog box asking the user for input. The text
of the dialog is prompt, and the default value is set to
default.
close() Closes the current window and deletes its object from
memory.
window.focus() This method gives focus to the window (i.e., puts the
window in the foreground, on top of any other open
browser windows).
window.document This property contains the document object representing
the document currently inside the window.
window.closed This property contains a boolean value that is set to true if
the window is closed, and false if it is not.
window.opener This property contains the window object of the window
that opened the current window, if such a window exists.
Important window object methods and properties.

© Pramudith_Kandambi_MIT_BIT_2009 36
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- window.html -->
6 <!-- Using the Window Object -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the Window Object</title>
11
12 <script type = "text/javascript">
13 <!--
14 var childWindow; // variable to control the child window
15
16 function createChildWindow()
17 {
18 // these variables all contain either "yes" or "no"
19 // to enable or disable a feature in the child window
20 var toolBar // specify if toolbar will appear in child window
21 var menuBar; // specify if menubar will appear in child window
22 var location; // specify if address bar will appear in child window
23 var scrollBars; // specify if scrollbars will appear in child window
24 var status; // specify if status bar will appear in child window
25 var resizable; // specify if the child window will be resizable
26
27 / / d e t er mi n e w h et he r t h e T o o l Ba r c h ec k b ox is c he c k ed
28 i f ( t oo l B a rC h e ck Bo x. c h e ck e d )
29 t o o lB ar = " y es " ;
30 e l se
31 t o o lB ar = " n o" ;
32
33 / / d e t er mi n e w h et he r t h e M e n u Ba r c h ec k bo x is c he c k ed
34 i f ( m en u B a rC h e ck Bo x. c h e ck e d )
35 m e n uB ar = " y es " ;
36 e l se
37 m e n uB ar = " n o" ;
38
39 / / d e t er mi n e w h et he r t h e A d d re ss B a r c h e ck b ox i s c h ec k e d
40 i f ( l oc a t i on C h ec kB ox . c h ec k e d )
41 l o c at io n = " ye s" ;
42 e l se
43 l o c at io n = " no ";
44
45 / / d e t er mi n e w h et he r t h e S c r ol l Ba r ch e c kb o x i s c h e ck e d
46 i f ( s cr o l l Ba r s Ch ec kB o x . ch e c ke d )
47 s c r ol lB a rs = " ye s" ;
48 e l se
49 s c r ol lB a rs = " no ";
50
51 // determi ne w hether the Sta tus Bar checkbox is checked
52 if ( statusCheckBox.chec ked )
53 status = "yes";
54 else
55 status = "n o";
56
57 // determi ne w hether the Res izab le checkbox is che cked
58 if ( resizableCheckBox.c heck ed )
59 resizab le = "yes";
60 else
61 resizab le = "no";
62
63 // display win dow with s elec ted features
64 childWindo w = window.ope n( " ", " ", "resizable = " + resizable +
65 ", tool bar = " + tool Bar + ", menubar = " + menuBar +
66 ", stat us = " + statu s + ", l ocation = " + location +
67 ", scro llba rs = " + s crol lBar s );
68
69 // disable but tons
70 closeButto n.di sabled = f alse ;
71 modifyButt on.d isabled = fals e;
72 getURLButt on.d isabled = fals e;
73 setURLButt on.d isabled = fals e;
74 } // end function createChi ldWi ndow
75
76 // insert text from the textbox into the child window
77 function modifyChildWindow()
78 {
79 if ( childWindow.closed )
80 alert( "You attempted to interact with a closed window" );
81 else
82 childWindow.document.write( textForChild.value );
83 } // end function modifyChildWindow
84
85 // close the child window
86 function closeChildWindow()
87 {
88 if ( childWindow.closed )
89 alert( "You attempted to interact with a closed window" );
90 else
91 childWindow.close();
92
93 closeButton.disabled = true;
94 modifyButton.disabled = true;
95 getURLButton.disabled = true;
96 setURLButton.disabled = true;
97 } // end function closeChildWindow
98
99 // copy the U RL o f the chil d wi ndow into the parent window’s myChildURL
100 function getChildWindowURL()
101 {
102 if ( childWindow .closed )
103 alert( "You attempted to intera ct w ith a closed windo w" );
104 else
105 myChildURL.value = childWindow. loca tion;
106 } // end function getChildWindowURL
107
108 // set the URL of the child window to the URL
109 // in the parent wi ndow ’s myChildURL
110 function setChildWindowURL()
111 {
112 if ( childWindow .closed )
113 alert( "You attempted to intera ct w ith a closed windo w" );
114 else
115 childWindow.location = myChildU RL.v alue;
116 } // end function setChildWindowURL
117 //-->
118 </script>
119
120 </head>
121
122 <body>
123 <h1>Hello, This is the main window</h1>
1 24 <p>Please ch eck the features to e nabl e f or the child wi ndo w <br/>
1 25 <input id = "too lBarCheckBox" type = "checkbox" valu e = ""
1 26 che cke d = "checked" />
1 27 <la bel >To ol B ar</label>
1 28 <input id = "men uBarCheckBox" type = "checkbox" valu e = ""
1 29 che cke d = "checked" />
1 30 <la bel >Me nu B ar</label>
1 31 <input id = "loc ationCheckBox" typ e = "checkbox" val ue = ""
1 32 che cke d = "checked" />
1 33 <la bel >Ad dres s Bar</label>< br/>
1 34 <input id = "scr ollBarsCheckBo x" t ype = "checkbox" v alu e = ""
1 35 che cke d = "checked" />
1 36 <la bel >Sc roll Bars</label>
1 37 <input id = "sta tusCheckBox" t ype = " checkbox" value = ""
1 38 che cke d = "checked" />
1 39 <la bel >St atus Bar</label>
1 40 <input id = "res izableCheckBox " ty pe = "checkbox" va lue = ""
1 41 che cke d = "checked" />
1 42 <la bel >Re siza ble</label><br /></ p>
1 43
1 44 <p>Please en ter the text that you wou ld like to display
1 45 in the ch ild win dow<br/>
1 46 <input id = "tex tForChild" typ e = "te xt"
1 47 val ue = " <h1> Hello, I am a chi ld window</h1> <br \>" />
148 <input id = "createButton" type = "button"
149 value = "Create Child Window" onclick = "createChildWindow()" />
150 <input id= "modifyButton" type = "button" value = "Modify Child Window"
151 onclick = "modifyChildWindow()" disabled = "disabled"/>
152 <input id = "closeButton" type = "button" value = "Close Child Window"
153 onclick = "closeChildWindow()" disabled = "disabled"/></p>
154
155 <p>The other window's URL is: <br/>
156 <input id = "myChildURL" type = "text" value = "./"/>
157 <input id = "setURLButton" type = "button" value = "Set Child URL"
158 onclick = "setChildWindowURL()" disabled = "disabled"/>
159 <input id = "getURLButton" type = "button" value = "Get URL From Child"
160 onclick = "getChildWindowURL()" disabled = "disabled"/></p>
161
162 </body>
163 </html>
© Pramudith_Kandambi_MIT_BIT_2009 44
© Pramudith_Kandambi_MIT_BIT_2009 45
Web Resources
www.javascript.com
www.iboost.com/build/programming/js/tutorial/885.htm
www.javascriptsearch.com
www.a1javascripts.com

© Pramudith_Kandambi_MIT_BIT_2009 46
By Pramudith Kandambi
JavaScript: Arrays
Outline
Introduction
Arrays
Declaring and Allocating Arrays
Examples Using Arrays
Random Image Generator Using Arrays
References and Reference Parameters
Passing Arrays to Functions
Sorting Arrays
Searching Arrays: Linear Search and Binary Search
Multidimensional Arrays
Building an Online Quiz
Web Resources

2
Array
• In this section, you will learn:
– To introduce the array data structure.
– To understand the use of arrays to store, sort and search lists
and tables of values.
– To understand how to declare an array, initialize an array
and refer to individual elements of an array.
– To be able to pass arrays to functions.
– To be able to search and sort an array.
– To be able to declare and manipulate multi-dimensional
arrays.

3
` An array is a special variable, which can hold
more than one value, at a time.

` If you have a list of items.


cars1="Saab";
cars2="Volvo";
cars3="BMW";
` However, what if you want to loop through the
cars and find a specific one? And what if you had
not 3 cars, but 300?

` The best solution here is to use an array!


c[ 0 ] -45
Name of array
c[ 1 ] 6

c[ 2 ] 0

c[ 3 ] 72

c[ 4 ] 1543

c[ 5 ] -89

c[ 6 ] 0

c[ 7 ] 62

c[ 8 ] -3

c[ 9 ] 1
Position number (index
or subscript) of the c[ 10 ] 6453
element within c
c[ 11 ] 78
array

A 12-element array.

5
` The following code creates an Array object
called myCars:

` var myCars=new Array();

` There are two ways of adding values to an


array (you can add as many values as you
need to define as many variables you
require).
` Normal way
var myCars=new Array();

myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

` You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
`
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

` var myCars=new Array("Saab","Volvo","BMW");

` Note: If you specify numbers or true/false values inside the array then
the type of variables will be numeric or Boolean instead of string.
` You can refer to a particular element in an
array by referring to the name of the array
and the index number. The index number
starts at 0.
` EX

The following code line:


document.write(myCars[0]);
will result in the following output:
Saab
` To modify a value in an existing array, just
add a new value to the array with a specified
index number:
` EX

myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel
<html>
<body>

<script type="text/javascript">

var mycars = new Array();


mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br />");
}
</script>

</body>
</html>
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
<html>
<body>

<script type="text/javascript">
var arr = new Array(3);
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";

document.write(arr.join("-") + "<br />");


document.write(arr.join(""));
</script>

</body>
</html>
<html>
<body>

<script type="text/javascript">

var arr = new Array(6);


arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
arr[5] = "Tove";

document.write(arr + "<br />");


document.write(arr.sort());
</script>

</body>
</html>
` Arrays
◦ Data structures of related items
x Also called Collections
◦ Dynamic

15
` Arrays in JavaScript
◦ Each element referenced by a number
x Start at “zeroth element”
x Subscript or index
◦ Accessing a specific element
x Name of array
x Brackets
x Number of element
◦ Arrays know their length
x length property

16
` Arrays in memory
◦ Objects
◦ Operator new
x Allocates memory for objects
x Dynamic memory allocation operator

var c;
c = new Array( 12 );

17
` Arrays grow dynamically
◦ Allocate more space as items are added
` Must initialize array elements
◦ Default value is undefined
◦ for loops convenient
◦ Referring to uninitialized elements or elements
outside array bounds is an error

18
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- InitArray.html -->
6 <!-- Initializing an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Initializing an Array</title>
11
12 <script type = "text/javascript"> Array n1 has five elements.
13 <!--
14 // this function is called when the <body> element's
15 // onload event occurs Array n2 is an empty array.
16 function initializeArrays()
17 {
18 var n1 = new Array( 5 ); // allocate 5-element Array
19 var n2 = new Array(); // allocate empty Array
The for loop initializes the elements in n1
20
21 // assign values to each element of
to their subscript numbers (0 to 4).
Array n1
22 for ( var i = 0; i < n1.length; ++i )
23 n1[ i ] = i;

19
24
25 // create and initialize five-elements in Array n2
26 for ( i = 0; i < 5; ++i )
27 n2[ i ] = i; The for loop adds Each
five elements
function to theand
Array n2
displays
28 initialize each element to itsofsubscript
contents number (0 to
its respective
29 outputArray( "Array n1 4).n1 );
contains", Array in an XHTML table.
30 outputArray( "Array n2 contains", n2 );
31 }
32
33 // output "header" followed by a two-column table
34 // containing subscripts and elements of "theArray"
35 function outputArray( header, theArray )
36 {
37 document.writeln( "<h2>" + header + "</h2>" );
38 document.writeln( "<table border = \"1\" width =" +
The second time
first time function
function ouputArray
ouputArray is is
39 "\"100%\">" );
40
called, variable header gets the value of
41 “Array n2 "<thead><th and
n1 contains”
document.writeln( widthvariable
= \"100\"" +
42 theArray
"align gets the value of n2
n1.+
= \"left\">Subscript</th>"
43 "<th align = \"left\">Value</th></thead><tbody>" );

20
44
45 for ( var i = 0; i < theArray.length; i++ )
46 document.writeln( "<tr><td>" + i + "</td><td>" +
47 theArray[ i ] + "</td></tr>" );
48
49 document.writeln( "</tbody></table>" );
50 }
51 // -->
52 </script>
53
54 </head><body onload = "initializeArrays()"></body>
55 </html>

21
Initializing the elements of an array.

22
` Possible to declare and initialize in one step
◦ Specify list of values
x Initializer list
var n = [ 10, 20, 30, 40, 50 ];
var n = new Array( 10, 20, 30, 40, 50 );
◦ Also possible to only initialize some values
x Leave uninitialized elements blank
x Uninitialized elements default to “undefined”
var n = [ 10, 20, , 40, 50 ];

23
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- InitArray2.html -->
6 <!-- Initializing an Array with a Declaration -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Initializing an Array with a Declaration</title>
11
12 <script type = "text/javascript">
Array integers1 is initialized using an initializer list.
13 <!--
14 function start()
15 { Two values are not supplied for
16 // Initializer list specifies number of elements
integers2 and will be displayed as
, which
17 // value for each element.
undefined.
18 var colors = new Array( "cyan", "magenta",
19 "yellow", "black" );
20 var integers1 = [ 2, 4, 6, 8 ];
21 var integers2 = [ 2, , , 8 ];
22
23 outputArray( "Array colors contains", colors );
24 outputArray( "Array integers1 contains", integers1 );
25 outputArray( "Array integers2 contains", integers2 );
26 }

24
27
28 // output "header" followed by a two-column table
29 // containing subscripts and elements of "theArray"
30 function outputArray( header, theArray )
31 {
32 document.writeln( "<h2>" + header + "</h2>" );
33 document.writeln( "<table border = \"1\"" +
34 "width = \"100%\">" );
35 document.writeln( "<thead><th width = \"100\" " +
36 "align = \"left\">Subscript</th>" +
37 "<th align = \"left\">Value</th></thead><tbody>" );
38
39 for ( var i = 0; i < theArray.length; i++ )
40 document.writeln( "<tr><td>" + i + "</td><td>" +
41 theArray[ i ] + "</td></tr>" );
42
43 document.writeln( "</tbody></table>" );
44 }
45 // -->
46 </script>
47
48 </head><body onload = "start()"></body>
49 </html>

25
Initializing the elements of an array.

26
` for…in statement
◦ Perform an action for each element in an array
◦ Iterates over array elements
x Assigns each element to specified variable one at a
time
◦ Ignores non-existent elements

27
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- SumArray.html -->
6 <!-- Summing Elements of an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Sum the Elements of an Array</title>
11
12 <script type = "text/javascript">
13 <!--
14 function start()
The for loop sums the values contained in the
15 { 10-element integer array called theArray.
16 var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
17 var total1 = 0, total2 = 0;
18
19 for ( var i = 0; i < theArray.length; i++ )
20 total1 += theArray[ i ];
21
22 document.writeln( "Total using subscripts: " + total1 );
23

28
24 for ( var element in theArray )
25 total2 += theArray[ element ];
26
Variable element is assigned a
27 document.writeln( "<br />Total using for...in: " +
subscript in the range of 0 up to, but
28 total2 );
29 }
not including, theArray.length.
30 // -->
31 </script>
32
33 </head><body onload = "start()"></body>
34 </html>

29
Calculating the sum of the elements of an array.

30
` Arrays can provide shorter and cleaner
substitute for switch statements
◦ Each element represents one case

31
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- RollDie.html -->
6 <!-- Roll a Six-Sided Die 6000 Times -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Roll a Six-Sided Die 6000 Times</title>
11
12 <script type = "text/javascript">
13 <!-- Referencing Array frequency replaces the switch
14 var face, frequency = [ , statement
0, 0, 0, 0, used in Chapter 10’s example.
0, 0 ];
15
16 // summarize results
17 for ( var roll = 1; roll <= 6000; ++roll ) {
18 face = Math.floor( 1 + Math.random() * 6 );
19 ++frequency[ face ];
20 }
21

32
22 document.writeln( "<table border = \"1\"" +
23 "width = \"100%\">" );
24 document.writeln( "<thead><th width = \"100\"" +
25 " align = \"left\">Face<th align = \"left\">" +
26 "Frequency</th></thead></tbody>" );
27
28 for ( face = 1; face < frequency.length; ++face )
29 document.writeln( "<tr><td>" + face + "</td><td>" +
30 frequency[ face ] + "</td></tr>" );
31
32 document.writeln( "</tbody></table>" );
33 // -->
34 </script>
35
36 </head>
37 <body>
38 <p>Click Refresh (or Reload) to run the script again</p>
39 </body>
40 </html>

33
Dice-rolling program using arrays instead of a switch.

34
` Cleaner approach than previous version
◦ Specify any file name rather than integers 1-7
◦ Result of Math.random call is index into array of
image file names

35
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- RandomPicture2.html -->
6 <!-- Randomly displays one of 7 images -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Random Image Generator</title>
11
12 <script type = "text/javascript">
13 <!--
14 var pictures =
15 [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];

36
16
17 document.write ( "<img src = \"" +
18 pictures[ Math.floor( Math.random() * 7 ) ] +
19 ".gif\" width = \"105\" height = \"100\" />" );
20 // -->
21 </script>
22
23 </head>
24
25 <body>
26 <p>Click Refresh (or Reload) to run the script again</p>
27 </body>
28 </html>

37
Random image generation using arrays.

38
` Two ways to pass parameters
◦ Pass-by-value
x Pass copy of original value
x Default for numbers and booleans
x Original variable is unchanged
◦ Pass-by-reference
x How objects are passed, like arrays
x Pass location in memory of value
x Allows direct access to original value
x Improves performance

39
` Name of array is argument
◦ Not necessary to also pass size of array
x Arrays know their size
◦ Passed by reference
x Individual elements are passed by value if numbers or
booleans
` Array.join
◦ Creates string containing all array elements
◦ Specify separator

40
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- PassArray.html -->
6 <!-- Passing Arrays -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Passing Arrays and Individual Array
11 Elements to Functions</title>
12
13 <script type = "text/javascript">
14 <!--
15 function start() The first call to function outputArray displays
16 { the contents of the Array a before it is modified.
17 var a = [ 1, 2, 3, 4, 5 ];
18
19 document.writeln( "<h2>Effects of passing entire " +
20 "array call-by-reference</h2>" );
21 outputArray( Function modifyArray multiplies each element by
22 "The values of the original2.array are: ", a );
23
24 modifyArray( a ); // array a passed call-by-reference
25

41
26 outputArray(
27 "The values of the modified array are: ", a );
28
29 Again, function
document.writeln( "<h2>Effects of passing outputArray
array " + is called to
30 show that
"element call-by-value</h2>" + the contents of Array a have been
31 modified.
"a[3] before modifyElement: " + a[ 3 ] );
32
33 modifyElement( a[ 3 ] ); Function modifyElement multiplies
34 the contents of a[ 3 ] by 2.
35 document.writeln(
36 The value of a[ 3 ] is output to show its
"<br />a[3] after modifyElement: " + a[ 3 ] );
37 } contents before it is modified.
38
39 // outputs "header" followed by the contents of "theArray"
40 function outputArray( header, theArray )
41 {
42 document.writeln(
43 header + theArray.join( " " ) + "<br />" );
44 }
45
Method join takes as its argument a string
containing a separator that should be used
to separate the elements of the array in the
string that is returned.

42
46 // function that modifies the elements of an array
47 function modifyArray( theArray )
48 {
49 for ( var j in theArray )
50 theArray[ j ] *= 2;
51 }
52
53 // function that attempts to modify the value passed
54 function modifyElement( e ) Multiply each element in theArray by 2.
55 {
56 e *= 2;
57 document.writeln( "<br />value in modifyElement: " + e );
58 }
59 // -->
60 </script>
61
62 </head><body onload = "start()"></body>
63 </html>

43
Passing arrays and individual array elements to functions.

44
` Sorting
◦ Important computing task
` Array.sort
◦ Defaults to string comparison
◦ Optional comparator function
x Return negative if first argument less than second
x Return zero if arguments equal
x Return positive if first argument greater than second

45
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- sort.html -->
6 <!-- Sorting an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Sorting an Array with Array Method sort</title>
11
12 <script type = "text/javascript">
13 <!--
Method sort takes as its optional argument the
14 function start() name of a function that compares two arguments
15 { and returns a value of –1, 0 or 1.
16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
17
18 document.writeln( "<h1>Sorting an Array</h1>" );
19 outputArray( "Data items in original order: ", a );
20 a.sort( compareIntegers ); // sort the array
21 outputArray( "Data items in ascending order: ", a );
22 }

46
23
24 // outputs "header" followed by the contents of "theArray"
25 function outputArray( header, theArray )
26 {
27 document.writeln( "<p>" + header +
28 theArray.join( " " ) + "</p>" );
29 }
30
31 // comparison function for use with sort
32 function compareIntegers( value1, value2 )
33 {
34 return parseInt( value1 ) - parseInt( value2 );
35 } Function compareIntegers calculates the
36 // -->
difference between the integer values of its
37 </script>
arguments.
38
39 </head><body onload = "start()"></body>
40 </html>

47
Fig. 11.9 Sorting an array with sort.

48
` Searching
◦ Look for matching key value
` Linear search
◦ Iterate through each element until match found
◦ Inefficient
x Worst case scenario, must test entire array
` Binary search
◦ Requires sorted data
◦ Cuts search range in half each iteration
◦ Efficient
x Only look at small fraction of elements

49
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- LinearSearch.html -->
6 <!-- Linear Search of an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head> Array a is initiated with 100 elements.
10 <title>Linear Search of an Array</title>
11
12 <script type = "text/javascript">
13 <!--
14 var a = new Array( 100 ); Array
// create ais populated with the even integers 0 to
an Array
15 198.
16 // fill Array with even integer values from 0 to 198
17 for ( var i = 0; i < a.length; ++i )
18 a[ i ] = 2 * i;
19

50
20 // function called when "Search" button is pressed
21 function buttonPressed()
22 {
23 var searchKey = searchForm.inputVal.value;
24
25 // Array a is passed to linearSearch even though it
26 Get value of search key from the input
// is a global variable. Normally an array will
27 // be passed to a method for field in the XHTML form.
searching.
28 var element = linearSearch( a, parseInt( searchKey ) );
29
30 if ( element != -1 ) Calling function linearSearch and passing
31 searchForm.result.value = it the Array a and the value of variable
32 "Found value in element " + element;
searchKey as an integer.
33 else
34 searchForm.result.value = "Value not found";
35 }
36

51
37 // Search "theArray" for the specified "key" value
38 function linearSearch( theArray, key )
39 {
40 for ( var n = 0; n < theArray.length; ++n )
41 if ( theArray[ n ] == key )
42 return n;
43
Variable theArray gets the value
44 return -1;
45 }
of Array a and variable key gets
Function linearSearch compares
46 // --> the value of variable searchKey.
each each element with a search key.
47 </script>
48
49 </head>
50
51 <body>
52 <form name = "searchForm" action = "">
53 <p>Enter integer search key<br />
54 <input name = "inputVal" type = "text" />
55 <input name = "search" type = "button" value = "Search"
56 onclick = "buttonPressed()" /><br /></p>
57
58 <p>Result<br />
59 <input name = "result" type = "text" size = "30" /></p>
60 </form>
61 </body>
62 </html>

52
Linear search of an array.

53
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- BinarySearch.html -->
6 <!-- Binary search -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Binary Search</title>
11 Array ais initialized with 15
12 <script type = "text/javascript"> elements.
13 <!--
14 var a = new Array( 15 );
15
16 for ( var i = 0; i < a.length; ++i )
17 a[ i ] = 2 * i;
18

54
19 // function called when "Search" button is pressed
20 function buttonPressed()
21 {
22 var searchKey = searchForm.inputVal.value;
23
24 searchForm.result.value =
25 "Portions of array searched\n";
26 Function binarySearch receives two
27 // Array a is passed to binarySearch arguments: the Array a and the search key,
even though it
28 // is a global variable. This is donesearchKey
because .
29 // normally an array is passed to a method
30 // for searching.
31 var element =
32 binarySearch( a, parseInt( searchKey ) );
33
34 if ( element != -1 )
35 searchForm.result.value +=
36 "\nFound value in element " + element;
37 else
38 searchForm.result.value += "\nValue not found";
39 }
40

55
41 // Binary search
42 function binarySearch( theArray, key )
43 {
44 var low = 0; // low subscript
45 var high = theArray.length - 1; // high subscript
46 var middle; // middle subscript
47
48 while ( low <= high ) {
49 middle = ( low + high ) / 2;
50
51 // The following line is used to display the
52 // part of theArray currently being manipulated
If the key matches the middle element of a
53 // during each iteration of the binary
54 // search loop.
subarray, the subscript of the current element
55 buildOutput( theArray, low, is less
If middle,
key is returned.
high than
); the middle element, the
56 high subscript is set to middle – 1.
57 if ( key == theArray[ middle ] ) // match
58 return middle;
59 else if ( key < theArray[ middle ] )
60 If is greater then the middle elements,
key low end of array
high = middle - 1; // search
61 else the high subscript is set to middle + 1.
62 low = middle + 1; // search high end of array
63 }

56
64
65 return -1; // searchKey not found
66 }
67
68 // Build one row of output showing the current
69 // part of the array being processed.
70 function buildOutput( theArray, low, mid, high )
71 {
72 for ( var i = 0; i < theArray.length; i++ ) {
73 Function buildOutput creates the markup
if ( i < low || i > high )
74 searchForm.result.value += " the";results of the search.
that displays
75 // mark middle element in output
76 else if ( i == mid )
77 searchForm.result.value += theArray[ i ] +
78 ( theArray[ i ] < 10 ? "* " : "* " );
79 else
80 searchForm.result.value += theArray[ i ] +
81 ( theArray[ i ] < 10 ? " " : " " );
82 }
83
84 searchForm.result.value += "\n";
85 }
86 // -->
87 </script>
88 </head>
89

57
90 <body>
91 <form name = "searchForm" action = "">
92 <p>Enter integer search key<br />
93 <input name = "inputVal" type = "text" />
94 <input name = "search" type = "button" value =
95 "Search" onclick = "buttonPressed()" /><br /></p>
96 <p>Result<br />
97 <textarea name = "result" rows = "7" cols = "60">
98 </textarea></p>
99 </form>
100 </body>
101 </html>

58
Binary search of an array.

59
` Two-dimensional arrays analogous to tables
◦ Rows and columns
x Specify row first, then column
◦ Two subscripts

60
Column 0 Column 1 Column 2 Column 3

Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript (or index)

Row subscript (or index)

Array name

Two-dimensional array with three rows and four columns.

61
` Declaring and initializing multidimensional
arrays
◦ Group by row in square brackets
◦ Treated as arrays of arrays
◦ Creating array b with one row of two elements and a
second row of three elements:
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];

62
` Also possible to use new operator
◦ Create array b with two rows, first with five columns
and second with three:
var b;

b = new Array( 2 );
b[ 0 ] = new Array( 5 );
b[ 1 ] = new Array( 3 );

63
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- InitArray3.html -->
6 <!-- Initializing Multidimensional Arrays -->
7
8 Array array1
<html xmlns = "http://www.w3.org/1999/xhtml"> provides six initializers
9 <head>
in two rows.
10 <title>Initializing Multidimensional Arrays</title>
11
12 <script type = "text/javascript">
Array array2 provides six initializers in
13 <!--
three rows.
14 function start()
15 {
16 var array1 = [ [ 1, 2, 3 ], // first row
17 [ 4, 5, 6 ] ]; // second row
18 var array2 = [ [ 1, 2 ], // first row
19
Function outputArray
[ 3 ],
displays each array’s
// second row
20 [ elements in a //
4, 5, 6 ] ]; Web page.
third row
21
22 outputArray( "Values in array1 by row", array1 );
23 outputArray( "Values in array2 by row", array2 );
24 }

64
25
26 function outputArray( header, theArray )
27 {
28 document.writeln( "<h2>" + header + "</h2><tt>" );
29
30 for ( var i in theArray ) {
31
32 for ( var j in theArray[ i ] )
33 document.write( theArray[ i ][ j ] + " " );
34
35 document.writeln( "<br />" );
36 }
37 Referencing the
38 document.writeln( "</tt>" ); multidimensional array theArray.
39 }
40 // -->
41 </script>
42
43 </head><body onload = "start()"></body>
44 </html>

65
Initializing multidimensional arrays.

66
` Radio buttons
◦ Represented as an array
x Name of radio buttons is name of array
x One element per button
◦ checked property is true when selected
` XHTML Forms
◦ Contain controls, including radio buttons
◦ action property specifies what happens when
submitted
x Can call JavaScript code

67
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- quiz.html -->
6 <!-- Online Quiz -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Online Quiz</title>
11
12 <script type = "text/JavaScript">
13
14 function checkAnswers()
15 {
16 // determine whether the answer is correct
17 if ( myQuiz.radiobutton[ 1 ].checked )
18 document.write( "Congratulations, your answer is correct" );
19 else // if the answer is incorrect
20 document.write( "Your answer is incorrect. Please try again" );
21 } Determining the value of
22 property checked.
23 </script>
24
25 </head>

68
26
27 <body>
28 <form id = "myQuiz" action = "JavaScript:checkAnswers()">
29 <p>Select the name of the tip that goes with the image shown:<br />
30 <img src="EPT.gif" width="108" height="100" alt="mystery tip"/>
31 <br />
Call the checkAnswers function
32
33 <input type = "radio"
when the form is submitted.
name = "radiobutton" value = "CPE" />
34 <label>Common Programming Error</label>
35
36 <input type = "radio" name = "radiobutton" value = "EPT" />
37 <label>Error-Prevention Tip</label>
38
39 <input type = "radio" name = "radiobutton" value = "PERF" />
40 <label>Performance Tip</label>
41
42 <input type = "radio" name = "radiobutton" value = "PORT" />
43 <label>Portability Tip</label><br />
44
45 <input type = "submit" name = "submit" value = "Submit" />
46 <input type = "reset" name = "reset" value = "Reset" />
47 </p>
48 </form>
49 </body>
50 </html>

69
Online quiz graded with JavaScript.

70
By Pramudith Kandambi
` Detect the visitor's browser, and then serve
up the appropriate information.

` JavaScript includes an object called the


Navigator object, that can be used for this
purpose.

` The Navigator object contains information


about the visitor's
` browser name, version, and more.
` Two properties of the Navigator object:

◦ appName - holds the name of the browser

◦ appVersion - holds, among other things, the


version of the browser
<html>
<body>
<script type="text/javascript">
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
document.write("Browser name: "+ browser);
document.write("<br />");
document.write("Browser version: "+ version);
</script>
</body>
</html>
` A cookie is often used to identify a user.

` A cookie is a variable
` Stored on the visitor's computer.
` Each time the same computer requests a
page with a browser,
` It will send the cookie too.
` Name cookie –
◦ The first time a visitor arrives to your web page, he or
she must fill in her/his name. The name is then stored in
a cookie. Next time the visitor arrives at your page, he or
she could get a welcome message like "Welcome Omana”
The name is retrieved from the stored cookie

` Password cookie –
◦ The first time a visitor arrives to your web page, he or
she must fill in a password. The password is then stored
in a cookie. Next time the visitor arrives at your page,
the password is retrieved from the cookie
` Date cookie –
◦ The first time a visitor arrives to your web page, the
current date is stored in a cookie. Next time the visitor
arrives at your page, he or she could get a message like
"Your last visit was on Tuesday june 11, 2009!" The date
is retrieved from the stored cookie
` 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:

◦ has the user left required fields empty?


◦ has the user entered a valid e-mail address?
◦ has the user entered a valid date?
◦ has the user entered text in a numeric field?
Client-side form validation (usually with JavaScript embedded in the Web page)

Server-side form validation (usually performed by a CGI or ASP script)


` <script type="text/javascript">
function validate_form ( )
{

if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );

}
</script>
<script type='text/javascript'>
function notEmpty(elem, helperMsg)
{
if(elem.value.length == 0)
{
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
</script>
<form> Required Field: <input type='text' id='req1'/> <input
type='button' onclick="notEmpty(document.getElementById('req1'),
'Please Enter a Value')" value='Check Field' /> </form>
<script type='text/javascript'>

function isNumeric(elem, helperMsg)


{
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression))
{
return true;
}
Else
{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form>
Numbers Only: <input type='text' id='numbers'/>
<input type='button' onclick="isNumeric(document.getElementById('numbers'), 'Numbers
Only Please')" value='Check Field' /> </form>
<script type='text/javascript'>
function isAlphabet(elem, helperMsg)
{
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp))
{
return true;
}
Else
{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>

<form> Letters Only: <input type='text' id='letters'/>


<input type='button' onclick="isAlphabet(document.getElementById('letters'), 'Letters Only Please')"
value='Check Field' /> </form>
<script type='text/javascript'>
function lengthRestriction(elem, min, max)
{
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max)
{
return true;
}
Else
{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
</script>
<form> Username(6-8 characters): <input type='text' id='restrict'/>
<input type='button' onclick="lengthRestriction(document.getElementById('restrict'),
6, 8)" value='Check Field' /> </form>
http://www.tizag.com/javascriptT/java
scriptform.php
` It is possible to use JavaScript to create
animated images.
` The trick is to let a JavaScript change between
different images on different events.
<html>
<head>
<script type="text/javascript">
function mouseOver()
{
document.getElementById("b1").src ="b_blue.gif";
}
function mouseOut()
{
document.getElementById("b1").src ="b_pink.gif";
}
</script>
</head>

<body>
<a href="http://www.w3schools.com" target="_blank">
<img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1" width="26" height="26"
onmouseover="mouseOver()" onmouseout="mouseOut()" /></a>
</body>
</html>
` With JavaScript, it is possible to execute some
code after a specified time-interval. This is
called timing events.

` The two key methods that are used are:


x setTimeout() - executes a code some time in the future
x clearTimeout() - cancels the setTimeout()

` Note: The setTimeout() and clearTimeout() are


both methods of the HTML DOM Window
object.
Syntax
var t=setTimeout("javascript statement",milliseconds);

` The setTimeout() method returns a value –


` In the statement above, the value is stored in
a variable called t.
` If you want to cancel this setTimeout(), you
can refer to it using the variable name.
<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
</script>
</head>
<body>
<form>
<input type="button" value="Display timed alertbox!"
onClick="timedMsg()" />
</form>
</body>
</html>
Syntax
clearTimeout(setTimeout_variable)

Example
The example below is the same as the "Infinite
Loop" example above. The only difference is
that we have now added a "Stop Count!" button
that stops the timer:
By Pramudith Kandambi
 PHP is a server-side scripting language.

 What You Should Already Know


◦ Before you continue you should have a basic understanding of the
following:
◦ HTML/XHTML
◦ JavaScript

 What is PHP?
◦ PHP stands for PHP: Hypertext Preprocessor
◦ PHP is a server-side scripting language, like ASP
◦ PHP scripts are executed on the server
◦ PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, etc.)
◦ PHP is an open source software
◦ PHP is free to download and use

 What is a PHP File?


◦ PHP files can contain text, HTML tags and scripts
◦ PHP files are returned to the browser as plain HTML 
◦ PHP files have a file extension of ".php", ".php3", or ".phtml"
 What is MySQL?
◦ MySQL is a database server
◦ MySQL is ideal for both small and large applications
◦ MySQL supports standard SQL
◦ MySQL compiles on a number of platforms
◦ MySQL is free to download and use

 PHP + MySQL
◦ PHP combined with MySQL are cross-platform (you can develop in
Windows and serve on a Unix platform)

 Why PHP?
◦ PHP runs on different platforms (Windows, Linux, Unix, etc.)
◦ PHP is compatible with almost all servers used today (Apache, IIS, etc.)
◦ PHP is FREE to download from the official PHP resource: www.php.net
◦ PHP is easy to learn and runs efficiently on the server side

 Where to Start?
◦ Install Apache (or IIS) on your own server, install PHP, and MySQL
 PHP code is executed on the server, and the
plain HTML result is sent to the browser.

 Basic PHP Syntax


◦ A PHP scripting block always starts with
<?php and ends with ?>.

◦ A PHP can be placed anywhere in the document.

◦ On some servers with shorthand support enabled


you can start with <? and end with ?>.
<html>
<body>

<?php

echo "Hello World";


?>
</body>
</html>

 code line in PHP must end with a semicolon(;).


 // to make a single-line comment
 /* and */ to make a large comment block.

<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
 Variables are used for storing a values
◦ text strings, numbers or arrays.

 When a variable is declared, it can be used over


and over again in your script.

 All variables in PHP start with a $ sign symbol.

 The correct way of declaring a variable in PHP:


$name = value;
 A variable name must start
◦ with a letter or an underscore "_“

 A variable name can only contain


◦ alpha-numeric characters and underscores (a-z, A-Z, 0-
9, and _ )

 A variable name should not contain spaces.

 If a variable name is more than one word,


◦ it should be separated with an underscore
 ($my_string),
◦ or with capitalization
 ($myString)
<?php

$txt="Hello World";
echo $txt;

?>
 String variables are used for values that contains
characters.

 After we create a string we can manipulate it.


◦ A string can be used directly in a function
◦ it can be stored in a variable

<?php

$txt="Hello World";
echo $txt;

?>
 There is only one string operator in PHP.

 The concatenation operator(.)   is used to put two string


values together.

<?php
$txt1="Hello World!";
$txt2="What a nice day!";

echo $txt1 . " " . $txt2;


?>

The output of the code above will be:

 Hello World! What a nice day!


 The strlen() function is used to return the
length of a string.

 Let's find the length of a string:

<?php
echo strlen("Hello world!");
?>
The output of the code above will be:
 12
 The strpos() function is used to search for character
within a string.

 If a match is found, this function will return the


position of the first match. If no match is found, it
will return FALSE.

 Let's see if we can find the string "world" in our


string:

<?php
echo strpos("Hello world!","world");
?>

The output of the code above will be:


 6
Operator Description Example Result
+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or 5>=8 returns false
equal to
<= is less than or equal to 5<=8 returns true
Operator Description Example
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
 if statement - use this statement to execute
some code only if a specified condition is true

 if...else statement - use this statement to


execute some code if a condition is true and
another code if the condition is false

 if...elseif....else statement - use this statement to


select one of several blocks of code to be
executed

 switch statement - use this statement to select


one of many blocks of code to be executed
 Syntax
if (condition)
code to be executed if condition is true;

The following example will output "Have a nice weekend!" if the


current day is Friday:

<html>
<body>
<?php
$d=date("D");

if ($d=="Fri")
echo "Have a nice weekend!";
?>
</body>
</html>
Syntax
if (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;
<html>
<body>
<?php

$d=date("D");

if ($d=="Fri")
   echo "Have a nice weekend!";
else
   echo "Have a nice day!";
?>
</body>
</html>
Syntax

if (condition)
  code to be executed if condition is true;
elseif (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;
<html>
<body>
<?php
$d=date("D");

if ($d=="Fri")
   echo "Have a nice weekend!";
elseif ($d=="Sun")
   echo "Have a nice Sunday!";
else
   echo "Have a nice day!";
?>
</body>
</html>
 Syntax

switch (n)
{
case label1:
  code to be executed if n=label1;
  break;
case label2:
  code to be executed if n=label2;
  break;
default:
  code to be executed if n is different from both label1 and label2;
}
<html>
<body>

<?php
switch ($x)
{
case 1:
   echo "Number 1";
   break;

case 2:
   echo "Number 2";
   break;

case 3:
   echo "Number 3";
   break;

default:
   echo "No number between 1 and 3";
}
?>
</body>
</html>
 What is an Array?
◦ An array is a special variable, which can hold more
than one value, at a time.
 Numeric array - An array with a numeric
index

 Associative array - An array where each ID


key is associated with a value

 Multidimensional array - An array containing


one or more arrays
 A numeric array stores each array element with a
numeric index.

 There are two methods to create a numeric array.

◦ 1. automatically assigned (the index starts at 0):


 $cars=array("Saab","Volvo","BMW","Toyota");

◦ 2. In the following example we assign the index


manually:
 $cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
referring to the array name and index:
<?php

$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

echo $cars[0] . " and " . $cars[1] . " are Swedish


cars.";

?>
 An associative array, each ID key is associated with a value.

 When storing data about specific named values, a numerical


array is not always the best way to do it.

 Example 1
In this example we use an array to assign ages to the different
persons:

◦ $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

 Example 2
 This example is the same as example 1, but shows a different
way of creating the array:

◦ $ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
 The ID keys can be used in a script:
<?php

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";

?>
 In a multidimensional array, each element in the
main array can also be an array. And each
element in the sub-array can be an array, and so
on.

Example
$families = array ( "Griffin"=>array ( "Peter", "Lois","Megan"),
  “fox"=>array ( "Glenn" ),
  "Brown"=>array ("Cleveland","Loretta")
   );
 while
◦ loops through a block of code while a specified condition
is true
 do...while
◦ loops through a block of code once, and then repeats
the loop as long as a specified condition is true
 for
◦ loops through a block of code a specified number of
times
 foreach
◦ loops through a block of code for each element in an
array
 The while loop executes a block of code while
a condition is true.

Syntax
while (condition)
 {
  code to be executed;
 }
The example below defines a loop that starts with i=1. The loop will continue to run
as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

<html>
<body>
<?php

$i=1;
while($i<=5)
   {
   echo "The number is " . $i . "<br />";
   $i++;
   }
?>

</body>
</html>

Output:

 The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
 The do...while statement will always execute
the block of code once, it will then check the
condition, and repeat the loop while the
condition is true.
 Syntax
do
 {
  code to be executed;
 }
while (condition);
<html>
<body>
<?php
$i=1;

do
  {
   $i++;
   echo "The number is " . $i . "<br />";
  }
while ($i<=5);

?>
</body>
</html>
Output:
 The number is 2
The number is 3
The number is 4
The number is 5
The number is 6 The for loop and the foreach loop will be explained in the next
chapter.
 The for loop is used when you know in
advance how many times the script should
run.

 Syntax

for (init; condition; increment)


 {
  code to be executed;
  } Parameters:
<html>
<body>
<?php

for ($i=1; $i<=5; $i++)


  {
   echo "The number is " . $i . "<br />";
  }
?>
</body>
</html>

Output:
 The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
 The foreach loop is used to loop through arrays.
 Syntax

foreach ($array as $value)


 {
  code to be executed;
 }
For every loop iteration, the value of the current
array element is assigned to $value (and the
array pointer is moved by one) - so on the next
loop iteration, you'll be looking at the next array
value.
<html>
<body>
<?php
$x=array("one","two","three");

foreach ($x as $value)


  {
   echo $value . "<br />";
  }
?>
</body>
</html>

Output:
 one
two
three
 The real power of PHP comes from its
functions.
 In PHP, more than 700 built-in functions.
 A function will be executed by a call to the
function.
 Syntax

function functionName()
{
code to be executed;
}
 Give the function a name that reflects what
the function does
 The function name can start with a letter or
underscore (not a number)
 A simple function that writes my name when it is called:

<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>

Output:
 My name is Kai Jim Refsnes
 Example 1
 The following example will write different first names, but equal last
name:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
 The following function has two parameters:
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>
</body>
</html>

Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?  
 To let a function return a value, use the return statement.
Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output:
1 + 16 = 17
 The most important thing to notice when
dealing with HTML forms.

 PHP is that any form element in an HTML


page will automatically be available to your
PHP scripts.
Example
 The example below contains an HTML form with two
input fields and a submit button:
<html>
<body>
<f orm ac t i on=" wel c ome. php"
met hod=" pos t " >

Name: <input type="text" name="fname" / >


Age: <input type="text" name="age" / >
<input type="submit" / >
</f orm>
</ body>
</ html>
When a user fills out the form above and click on the
submit button, the form data is sent to a PHP file,
called "welcome.php":
<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>!<br/>

You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>
Output
Welcome John!
You are 28 years old.
Variable name Description
$_SERVER Data about the currently running server.
$_ENV Data about the client’s environment.
$_GET Data posted to the server by the get method.
$_POST Data posted to the server by the post method.
$_COOKIE Data contained in cookies on the client’s computer.
$GLOBALS Array containing all global variables.
Some useful global arrays.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 <!-- env.php -->
5 <!-- Program to display environment variables -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Environment Variables</title>
10 </head>
11
12 <body>
13 <table border = "0" cellpadding = "2" cellspacing = "0"
14 width = "100%">
15 <?php
16
17 // print the key and value for each element
18 // in the $_ENV array
19 foreach ( $_ENV as $key => $value )
20 print( "<tr><td bgcolor = \"#11bbff\">
21 <strong>$key</strong></td>
22 <td>$value</td></tr>" );
23 ?>
24 </table>
25 </body>
26 </html>
 The built-in $_GET function.
 Used to collect values from a form sent with
method="get".

 Information sent from a form with the GET


method is visible to everyone (it will be
displayed in the browser's address bar) and
has limits on the amount of information to
send (max. 100 characters).
<form action="welcome.php" method="get">

Name:<input type="text" name="fname" />


Age: <input type="text" name="age" />
<input type="submit" />

</form>

The URL sent to the server could look something like this:

http://www.w3schools.com/welcome.php?
fname=Peter&age=37 The "welcome.php"

Welcome <?php echo $_GET["fname"]; ?>.<br />


You are <?php echo $_GET["age"]; ?> years old!
 Note: should not be used when sending
passwords or other sensitive information!

 However, because the variables are displayed


in the URL, it is possible to bookmark the
page. This can be useful in some cases.

 Note: not suitable for large variable values;


the value cannot exceed 100 characters.
 The built-in $_POST function.

 used to collect values from a form sent with


method="post".

 Information sent from a form with the POST


method is invisible to others.

 Has no limits on the amount of information to


send.

 Note: However, there is an 8 Mb max size for the


POST method, by default (can be changed by
setting the post_max_size in the php.ini file).
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
The URL will look like this:

http://www.w3schools.com/welcome.php

Welcome <?php echo $_POST["fname"]; ?>!<br />


You are <?php echo $_POST["age"]; ?> years old.
 Information sent from a form with the POST
method is invisible.

 Has no limits on the amount of information to


send.

 However, because the variables are not displayed


in the URL, it is not possible to bookmark the
page.
 The PHP built-in $_REQUEST function
contains the contents of both $_GET, $_POST,
and $_COOKIE.

 The $_REQUEST function can be used to


collect form data sent with both the GET and
POST methods.

 Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.
Server side programming
Server software
IIS -ASP
Apache --PHP
Tomcat --JSP
Server technologies
Macromedia ColdFusion
Microsoft ASP.NET
Microsoft Active Server Pages (ASP)
Sun JavaServer Pages (JSP)
PHP: Hypertext Preprocessor (PHP)
Server executes the script and send the HTML results to the
client’s browser
What is PHP
PHP (Hypertext Preprocessor") is a widely-used
Open Source general-purpose scripting language
that is especially suited for Web development and
can be embedded into HTML.
How we include PHP code
1.
<?php
echo("if you want to serve XHTML or XML documents,
do like this\n");
?>
is the preferred method, as it allows the use of PHP in
XML-conformant code such as XHTML.
2.
<?
echo ("this is the simplest, an SGML processing
instruction\n");
?>
   
3.
<script language="php">
       echo ("some editors (like FrontPage) don't
             like processing instructions");
   </script>

4.
<%
echo ("You may optionally use ASP-style tags");
%>
  
<html>
   <head>
       <title>Example</title>
   </head>
   <body>
 <?php
       echo “This is my first PHP script!";
    ?>
 </body>
</html>
What distinguishes PHP from something like client-side
JavaScript is that the code is executed on the server. If
you were to have a script similar to the above on your
server, the client would receive the results of running
that script, with no way of determining what the
underlying code may be
Five important characteristics of PHP
• Familiarity
• Simplicity
• Efficiency
• Security
• Flexibility
it’s free!
Familiarity
Many of the language’s constructs are borrowed
from C and Perl, and in many cases PHP code is
almost indistinguishable from that found in
the typical C or Pascal program. This minimizes
the learning curve considerably.
Simplicity
A PHP script can consist of 10,000 lines or one
line: whatever you need to get the job done.
There is no need to include libraries, special
compilation directives, or anything of the sort. The
PHP begins executing the code included
between (<?) and ?>) tags
Efficiency
Efficiency is an extremely important consideration
for working in a multi user environment such as
the WWW. resource allocation mechanisms
and more pronounced support for object-oriented
programming, in addition to session management
features and also eliminate unnecessary memory
allocation.
Security
PHP provides developers and administrators with
a flexible and efficient set of security safeguards.
Two types
system level and application level.
System-Level Security Safeguards
PHP furnishes a number of security mechanisms
that administrators can manipulate,
providing for the maximum amount of freedom
and security when PHP is properly configured.
(refer programmers Introduction to PHP4 Page
409)
How to embed PHP code
<?
$site_title = "PHP code ";
$bg_color = "cian";
$user_name = "Amara";
?>
<html><head>
<title><? print $site_title; ?></title>
</head>
<body bgcolor="<? print $bg_color; ?>" >
<?
print " Today's date is ".date("F d, Y")." <br>
Welcome , $user_name! <br> ";
?>
</body></html>
When PHP parses a file, it simply passes the text
of the file through until it encounters one of the
special tags which tell it to start interpreting the
text as PHP code. The parser then executes all
the code it finds, until it runs into a PHP closing
tag, which tells the parser to just start passing the
text through again. This is the mechanism which
allows you to embed PHP code inside HTML:
everything outside the PHP tags is left utterly
alone, while everything inside is parsed as code.
Terminate each statement with a semicolon.
Commnets
// This is a one-line c++ style comment
   /* This is a multi line comment
      yet another line of comment */
Eg.
<?php
   echo "This is a test"; // This is a one-line comment
   /* This is a multi line comment
      yet another line of comment */
   echo “multi line test";
  
?>
Data types in PHP
Four scalar types:
boolean
integer
float (floating-point number, aka 'double')
string
Two compound types:
array
object
Boolean
Syntax
To specify a boolean literal, use either the
keyword TRUE or FALSE. Both are case-
insensitive.
<?php
$res = TRUE;
If(res):
echo “it is boolean”;
endif;
?>
Integer type
An integer is a number of the set Z = {..., -2, -1, 0, 1,
2, ...}.
The size of an integer is platform-dependent, although a
maximum value of about two billion is the usual value
(that's 32 bits signed). (octal started with 0, hexadecimal
started with 0x )

Floating point numbers


Floating point numbers ("doubles" or "real numbers")
can be specified using any of the following syntaxes:
copy to clipboard
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
String Values
A string is a group of characters that are
represented as a single entity but can also
be examined on a character-by-character basis.
String Assignments
Strings can be delimited in two ways, using either
double quotation marks (“”) or single quotation
marks (‘’). There are two fundamental differences
between the two methods. First, variables in a
double-quoted string will be replaced with their
respective values, whereas the single-quoted
strings will be interpreted exactly as it is, even if
variables are enclosed in the string.
eg.
$name="Jaja";
$name='jaya';
Both are same but ..
echo "myname is $name"."<br>";
echo 'myname is $name'."<br>";
Rsults are different
Myname is Jaya …mynameis$name
while a double quoted string recognizes all available
delimiters, a single-quoted string recognizes only the
delimiters “\\” and “\”.
$double_list = "item1\nitem2\nitem3";
$single_list = 'item1\nitem2\nitem3'; (take it as a
character)
Strings can be accessed on a character-by-
character basis, much like a sequentially
indexed array.
$sequence_number = "04efgh";
$letter = $sequence_number[4];
echo $letter ……….resulted g
Variable Declaration
A variable is a named memory location that
contains data that may be manipulated
throughout the execution of the program.
A variable always begins with a dollar sign, $.
Eg. $name
Variable Scope
Scope can be defined as the range of availability
a variable has to the program in which it is
declared. PHP variables can be one of four scope
types:
• Local variables
• Function parameters
• Global variables
• Static variables
Local Variables
A variable declared in a function is considered
local; that is, it can be referenced
solely in that function.
Function parameters
Function parameters are declared after the
function name and inside parentheses.
They are declared much like a typical variable
would be:
function myfunc ($value) {
$value = $value * 10;
return $value;
}
Global Variables
In contrast to local variables, a global variable can be accessed in
any part of the
program.
by placing the keyword GLOBAL in front of the
variable that should be recognized as global.
<?php
$a = 1;
$b = 2;
function Sum()
{
   global $a, $b;
   $b = $a + $b;
}
Sum();
echo $b;
?>
An alternative method for declaring a variable to
be global is to use PHP’s
Static variable
a static variable will not lose its value when the
function exits and will still hold that value should
the function be called again. You can declare a
variable to be static simply by placing the
keyword STATIC in front of the variable name.
Syntax :STATIC $somevar;

function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "<br>";
}
keep_track();
keep_track();
keep_track();
Output is 1 2 3
Cast Operators for Variables
CAST OPERATORS CONVERSION
(int) or (integer) Integer
(real) or (double) or (float) Double
(string) String
(array) Array
(object) Object
$variable1 = 13;
// $variable1 is assigned the integer value 13.
$variable2 = (double) $variable1;
// $variable2 is assigned the value 13.0
$variable1 = 4.0;
$variable2 = 5;
$variable3 = (int) $variable1 + $variable2;
// $variable3 = 9
It is also possible to cast a string or other data
type to be a member of an array. The variable
being cast simply becomes the first element of
the array:
$variable1 = 1114;
$array1 = (array) $variable1;
print $array1[0];
// The value 1114 is printed.
Constants
A constant is essentially a value that cannot be
modified throughout the execution of a program.
constants are defined using the define() function.
define("PI", "3.141592");
And subsequently used in the following listing:
print "The value of pi is". PI.".<br>";
$pi2 = 2 * PI;
Arithmetic Operators

$a + $b
$a - $b
$a * $b
$a / $b Division
$a % $b Modulus Remainder of $a / $b
Assignment Operators

$a = 5; Assignment $a equals 5
$a += 5; Addition-assignment $a equals $a plus 5
$a *= 5; Multiplication-assignment $a equals $a
multiplied by 5
$a /= 5; Division-assignment $a equals $a divided
by 5
$a .= 5; Concatenation-assignment $a equals $a
concatenated with 5
String Operators

$a = ‘abc’.’def’; Concatenation $a equals the


concatenation of the two strings $a and $b
$a .= ‘ghijkl’;
Concatenation-assignment $a equals its current
value concatenated with “ghijkl”.

Output is ……abcdefghijk
Logical Operators

$a && $b - True if both $a and $b are true.


$a AND $b - True if both $a and $b are true.
$a || $b Or True if either $a or $b are true.
$a OR $b Or True if either $a or $b are true.
! $a Not True if $a is not true.
NOT $a Not True if $a is not true.
$a XOR $b Exclusive or True if only $a or only $b
is true.
Equality Operators
EXAMPLE LABEL OUTCOME
$a == $b Is equal to True if $a and $b are
equivalent.
$a != $b Is not equal to True if $a is not equal to
$b
$a === $b Is identical to True if $a and $b are
equivalent and $a and =$b have the same type.
Arrays
An array in PHP is actually an ordered map. A
map is a type that maps values to keys.
A single-dimension array can be created as
follows:
$meat[0] = "chicken";Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys.
$meat[1] = “beef";
$meat[2] = “mutton";
If you execute this command:
print $meat[1];
Single-Dimension Associative Arrays
Associative arrays are particularly convenient
when it makes more sense to map
an array using words rather than integers.
An array can be created by the array() language-
construct. It takes a certain number of comma-
separated key => value pairs.
<?php
$arr = array(“name" => "Sunil" , "pass" =>
true ,"marks" => 50);
echo 'Name ' .$arr[“name"]. '<br>';
echo 'pass '. $arr["pass"]. '<br>' ;
echo 'marks '. $arr["marks"] ;
?>
If you do not specify a key for a given value, then
the maximum of the integer indices is taken, and
the new key will be that maximum value + 1.
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
Multidimensional Indexed Arrays
Multidimensional indexed arrays function much
like their single-dimension
counterparts, except that more than one index
array is used to specify an element.
There is no limit as to the dimension size,
although it is unlikely that anything
beyond three dimensions would be used in most
applications.
The general syntax of a multidimensional array is:
$name[index1] [index2]..[indexN];
$student = $tudrec[5][4];
Multidimensional Associative Arrays
Multidimensional associative arrays are also
possible (and quite useful) in PHP.
$stud[“batch1"] [“sad"] = 55;
$stud[“batch3"] [“web"] = 60;
$stud[“batch2"] [“bio"] = 40;

print $stud[“batch1”][“sad”];
Control Structures
Selection
if (expression):
statement block;
endif;
If else……
if (expression) {
statement block

}
else {
statement block;
endif;
}
elseif
The elseif statement provides another level of
evaluation for the if control structure,
adding depth to the number of expressions that
can be evaluated:
if (expression) {
statement block
}
elseif (expression) {
statement block
}
while
The while structure provides a way to repetitively
loop through a statement
block. The number of times the statement block is
executed depends on the total
times the expression evaluates to true.
The general form of the while loop is:
while (expression) :
statement block
endwhile;
$n = 1;
$ncopy = $n;
$factorial = 1; // set initial factorial value
while ($n >1 0) :
$sum = $n + sum;
$n++;
endwhile;
print "The sum is $sum.";
do :
statement block
while (expression);
for ($i = 10; $i <= 100; $i+=10) :
print "\$i = $i <br>";
endfor;
$x = 5;
for (; ; $x += 2) :
print " $x ";
if ($x == 15) :
break; // break out of this for loop
endif;
endfor; (output will be 5 7 9 11 13 15)
foreach
The foreach construct is a variation of the for structure,
included in the language. There are two general
forms of the foreach statement, each having its own
specific purpose:
Expressions, Operators, and Control Structures
1
foreach (array_expression as $value) {
statement
}
foreach (array_expression as $key => $value) {
statement
}
1.
$menu = array("pasta", "steak", "potatoes", "fish", "fries");
foreach ($menu as $item) {
print "$item <BR>";
}
2.
<?
$submarks = array (
"phy" => 55,
"com" => 47,
"che" => 32
);
foreach ($submarks as $i => $item_count) {
print " sub marks of $i $item_count ";
}
?>
switch
The switch statement functions much like an if
statement, testing an expression value against a list of
potential matches. It is particularly useful when you need
to compare many values, as the switch statement
provides clean and compact code.
The t of the switch statement is:
switch (expression) {
case (condition) :
statement block
case (condition) :
statement block
...
default :
statement block
}
$user_input = "recipes"; // assume $user_input is
passed in to the script
switch ($user_input) :
case("search") :
print "Let's perform a search!";
break;
case("dictionary") :
print "What word would you like to look up?";
break;
case("recipes") :
print "Here is a list of recipes…";
break;
default:
print "Here is the menu…";
break;
endswitch;
Functions
Variable Functions
An interesting capability of PHP is the possibility
to execute variable functions.
A variable function is a dynamic call to a function
whose name is determined at the time of
execution. Although not necessary in most Web
applications, variable functions can significantly
reduce code size and complexity, often
eliminating unnecessary if conditional statements.
<?
function computer() {
print "I do computer.";
}

function phy() {
print "i do physics.";
}

$subject = "phy";
// execute the variable function
$subject();
?>
Variablefunc.php
String-Specific Functions
chop()
The chop() function returns a string minus any
ending whitespace and newlines.
Its syntax is:
string chop (string str)
This example uses chop() to remove
unnecessary newlines:
$header = "Table of Contents:\n\n";
$header = chop($header);
// $header = "Table of Contents"
trim()
The trim() function will remove all whitespace
from both the left and right sides of string,
returning the resulting string.
syntax
string trim (string string)
It will also remove the special characters “\n”, “\r”,
“\t”, “\v” and “\0”.
Finding Out the Length of a String
You can determine the length of a string through
use of the strlen() function.
This function returns the length of a string
$length=strlen (string str)
Comparing Two Strings
String comparison is arguably one of the most
important features of the string handling
two strings can be compared for equality
PHP provides four functions for performing
this task:
• strcmp()
• strcasecmp()
• strspn()
• strcspn()
strcmp()
The strcmp() function performs a case-sensitive
comparison of two strings.
syntax
int strcmp (string string1, string string2)
On completion of the comparison, strcmp() will return
one of three possible
values:
• 0 if string1 and string2 are equal
• < 0 if string1 is less than string2
• > 0 if string2 is less than string1
$string1=nimal,$string2 = “nimal";
if ((strcmp($string1, $string2)) == 0) :
print "Strings are equivalent!";
endif;
Strcmp.php
strcasecmp()
The strcasecmp() function operates exactly like strcmp(),
except that its comparison is case insensitive.
syntax
int strcasecmp (string string1, string string2)
The following example compares two equivalent string
values:
$string1 = "butter";
$string2 = "Butter";
if ((strcasecmp($string1, $string2)) == 0) :
print "Strings are equivalent!";
endif;
// If statement will evaluate to true
strcspn()
The strcspn() function returns the length of the
first segment in string1 containing characters not
in string2. Its syntax is:
$password = "12345";
if (strcspn($password, "1234567890")
==strlen($password)) :
print "Password cannot consist only numbers!";
endif;
Strcspn.php
strstr()
The strstr() function returns the remainder of
string beginning at the first occurrence.
syntax
string strstr (string string, string occurrence)
This example uses strstr() to return the domain
name of a URL:
$url = "http://www.apress.com";
$domain = strstr($url, ".");
// $domain = ".apress.com"
substr()
The substr() function returns the part of the string
between the start and start+length parameters.
syntax
string substr (string string, int start[,int length] )
$car = “laserFord";
$yr = substr($car, 0, 4);
// $yr = “laser"
Substr.php
Converting a String into Uppercase and
Lowercase
Letters
Four functions are available to aid you in
accomplishing this task:
• strtolower()
• strtoupper()
• ucfirst()
• ucwords()
The strtolower() function does exactly what you
would expect it to: it converts a
string to all lowercase letters. Its syntax is:
string strtolower (string string)
Non alphabetical characters are not affected. The
following example uses
strtolower() to convert a string to all lowercase
letters:
$sentence = "COOKING and PROGRAMMING
PHP are my TWO favorite pastimes!";
$sentence = strtolower($sentence);
ucfirst()
The ucfirst() function capitalizes the first letter of
a string, provided that it is alphabetical.
Its syntax is:
string ucfirst (string string)
$sentence = “programming and analisyss!";
$sentence = ucfirst($sentence);
== Programming and analisyss!";
Processing Form Data
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
</head><body>
<p>form data processing</p>
<p>&nbsp; </p>
<form name="form1" method="post" action="form2.php" >
<p>name
<input type="text" name="name" value="">
</p> <p>age
<input type="text" name="age">
</p> <p>
<input type="submit" name="Submit" value="Submit">
</p>
</form><p>&nbsp;</p></body></html>
<?
$n=$_POST["name"];
$age=$_POST["age"];
print "your entered name is $n <br>";
print "entered age is $age<br>";
print "good luck";
?>
Files
Opening and Closing I/O
Before you can perform any I/O operation on a
file, you must open it using the
fopen() function.
fopen()
The fopen() function opens a file, assuming that it
exists, and returns an integer, better known as a
file handle.
syntax
$handler= fopen (file name(string) ,mode(string)
MODE MEANING
r Read only. The file pointer is placed at the beginning
of the file.
r+ Reading and writing. The file pointer is placed at the
beginning of the file.
w Write only. The file pointer is placed at the beginning
of the file, and the file contents are erased. If the file
does not exist, create it.
w+ Reading and writing. The file pointer is placed at the
beginning of the file, and the file contents are erased. If
the file does not exist, create it.
a (append)Write only. The file pointer is placed at the
end of the file. If the file does not exist, create it.
a+ Reading and writing. The file pointer is placed at the
end of the file. If the file does not exist, create it.
fwrite()
The fwrite() function will simply write the contents of
string to the file specified by filepointer.
syntax
fwrite (file handler, string string)
Read file
$fh = fopen('pastry.txt', "r") or die("Can't open file!");
$file = fread($fh, filesize($fh));
print $file;
fclose($fh);
<?
$file = "dat.txt";
if (is_file($file)) :
print "The file $file is valid and exists!";
$data = "this is record";
$fh= fopen("dat.txt","w");
fwrite($fh, $data);
else :
print "Either $file does not exist or it is not a valid
file!";
endif;
fclose($fh);
?>
<?
$file = "dat.txt";
if (is_file($file)) :
print "The file $file is valid and exists!<br>";

$fh= fopen("dat.txt","r");
$success = fread($fh, 2040);
print "read ok<br>";
print $success."<br>";
else :
print "Either $file does not exist or it is not a valid file!";
endif;
fclose($fh);
?>
$fh = fopen('pastry.txt', "r") or die("Can't open
file!");
$file = fread($fh, filesize($fh));
print $file;
fclose($fh);
By using filesize() to retrieve the byte size of
pastry.txt, you ensure that
fread() will read in the entire contents of the file.
File related functions
file_exists()
The file_exists() function will ensure that file
exists, returning true if it does,
and false otherwise.
$filename = "userdata.txt";
if (! file_exists ($filename)) :
print "File $filename does not exist!";
endif;
is_file()
The is_file() function will return true if file exists and is a
readable/writable file.
Essentially, is_file() is a bullet-proof version of file_exists(),
verifying not
only the file’s existence but also whether it can be read from or
written to:
bool is_file (string file)
This example shows how to verify the existence and validity of a
file:
$file = "somefile.txt";
if (is_file($file)) :
print "The file $file is valid and exists!";
else :
print "Either $file does not exist or it is not a valid file!";
endif;
filesize()
The filesize() function will return the size, in
bytes, of the file designated by filename,
or false should an error occur. Its syntax is:
int filesize (string filename)
Assume that you want to know the size of a file
named pastry.txt. You can use
filesize() to retrieve this information:
$fs = filesize("pastry.txt");
print "Pastry.txt is $fs bytes.";
fputs()
The fputs() function is an alias to fwrite() and is
implemented in exactly the
same way. Its syntax is:
int fputs (int filepointer, string string [, int length])
fgets()
The fgets() function returns a string read from a
file pointed to by the file
pointer. The file pointer must point to an opened
file that is readable
fgets (int filepointer, int length)
Reading will stop when one of the following
conditions has been met:
• Length: 1 byte is read.
• A newline is read (returned with the string).
• An end of file (EOF) is read.
$fh = fopen("pastry.txt", "r");
while (! feof($fh)) :
$line = fgets($fh, 4096);
print $line."<br>";
endwhile;
fclose($fh);
<?
$file = "dat.txt";
if (is_file($file)) :
//print "The file $file is valid and exists!<br>";
$fh= fopen("dat.txt","r");
$success = fread($fh, 1080);
$success=$success+1;
fclose($fh);

$fh= fopen("dat.txt","w");
fwrite ($fh,$success);
print "number of hits = $success <br>";
print "write ok";
else : print "Either $file does not exist or it is not a valid file!";
endif;
fclose($fh);
?>
Database-PHP
The general order of events that take place during the
MySQL server communications process:
1. Establish a connection with the MySQL server. If the
connection attempt fails, display an appropriate
message and exit process.
2. Select a database on the MySQL server. If you cannot
select the database, display an appropriate message
and exit process. It’s possible to simultaneously have
several databases open for querying.
3. Perform necessary queries on selected database(s).
4. Once the querying is complete, close the database
server connection.
mysql_connect()
The function mysql_connect() is used to establish
an initial connection with the MySQL server.
Once a successful connection is established, a
database residing on that server can be selected.
An example connection call follows:
@mysql_connect("localhost", “username",
“password") or die("Could not connect to MySQL
server!");
mysql_select_db()
Once a successful connection is established with
the MySQL server, a database residing on that
server can be selected.
@mysql_select_db("company") or die("Could not select
company database!");
mysql_close()
Once you have finished querying the MySQL server, you
should close the connection.
Example…
<?
@mysql_connect("localhost", “user", “amara")
or die("Could not connect to MySQL server!");
@mysql_select_db("company") or die("Could not select
company database!");
print "You're connected to a MySQL database!";
mysql_close();
?>
mysql_query()
The function mysql_query() provides the
functional interface from which a database can be
queried.
int mysql_query (string query )
The input parameter query corresponds to an
SQL query. If you are concerned that you are
using up too much memory when making various
query calls, call the predefined PHP function
mysql_free_result().
This function, which takes as input the result_id
returned from mysql_query(), will free up all
memory associated with that query call.
mysql_query()
The function mysql_query() provides the functional
interface from which a database can be queried.
<?
@mysql_connect("localhost", “root", “abcd")
or die("Could not connect to MySQL server!");
@mysql_select_db(“student") or die("Could not select
company database!");
$query = "SELECT stud_marks FROM marks WHERE
name=“amara”;
// execute the query
$result = mysql_query($query);
print “amara’s marks is ($result);
mysql_close();?>
Example 2
<?
@mysql_connect("localhost", “root", "fabcd") or die("Could not connect to MySQL
server!");
@mysql_select_db("company") or die("Could not select company database!");
// Select all rows in the products table
$query = "SELECT * FROM stuent";
$result = mysql_query($query);
$x = 0;
print "<table>";
print "<tr><th>Product ID</th><th>Product Name</th><th>Product Price</th></tr>";
while ($x < mysql_numrows($result)) :

$name = mysql_result($result, $x, 'name');


$price = mysql_result($result, $x, ‘marks');
print "<tr>";
print "<td>$id</td><td>$name</td><td>$marks</td>";
print "</tr>";
$x++;
endwhile;
</table>
mysql_close();
?>
mysql_fetch_array()
It is typically much more convenient to simultaneously
assign an entire row to an
indexed array (starting at offset 0), rather than make
multiple calls to mysql_result() to assign column values.

$query = "SELECT * FROM products";


$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) :
print "<tr>\n";
print "<td>".$row["prod_id"]."</td>\n
<td>".$row["prod_name"]."</td>\n
<td>".$row["prod_price"]."</td>\n";
print "</tr>\n";
endwhile;
Microsoft Access and PHP
how you can connect to an MS Access database using
PHP.
odbc_connect()
Before querying an ODBC-enabled database, you must
first establish a connection.
odbc_connect().
$conn = new COM("ADODB.Connection") or
die("Cannot start ADO");
// Microsoft Access connection string.
$conn->Open("DRIVER={Microsoft Access Driver
(*.mdb)}; DBQ=“.realpath(“student.mdb");
// SQL statement to build recordset.
$rs = $conn->Execute("select * from marks");
<?
$conn = new COM("ADODB.Connection") or die("Cannot start
ADO");
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};
DBQ=d:\phptute\student.mdb");
$rs = $conn->Execute("select * from marks");
echo "<p>Below is a list of values in the student.MDB database,
Marks table.</p>";
while (!$rs->EOF) {
$fv = $rs->Fields("name");
echo "Value: ".$fv->value."<br>\n";
$fa=$rs->Fields("age");
echo "Value: ".$fa->value."<br>\n";
$fad=$rs->Fields("add");
echo "Value: ".$fad->value."<br>\n";
$fmk=$rs->Fields("marks");
echo "Value: ".$fmk->value."<br>\n";
$rs->MoveNext();
} $rs->Close();
Insert form data to database
$nm=$_POST[‘name’];
$add=$_POST[‘add’];
$age=$_POST[‘age’];
$marks=$_POST[‘marks’];
$conn = new COM("ADODB.Connection")
or die("Cannot start ADO");
$conn->Open("DRIVER={Microsoft Access
Driver (*.mdb)};
DBQ=d:\phptute\student.mdb");
$conn->Execute(“insert into marks values
(“’$nm,$add,$age,$marks’”);
Insert form data to database
$nm=$_POST[‘name’];
$add=$_POST[‘add’];
$age=$_POST[‘age’];
$mks=$_POST[‘marks’];
$conn = new COM("ADODB.Connection")
or die("Cannot start ADO");
$conn->Open("DRIVER={Microsoft Access
Driver (*.mdb)};
DBQ=“.realpath(“student.mdb");
$conn->Execute(“update marks set
marks=$mks where name=$na”);
Cookies
What Is a Cookie?
A cookie is nothing more than a small parcel of
information that is sent by a Web server and
stored on a client browser.
Cookie Components
Interestingly, other pieces of information are also
stored in the cookie, enabling the developer to
tailor its usage in terms of domain, time frame,
path, and security.
name—The cookie name is a mandatory
parameter because the name is the parameter
from which the cookie is referenced.
value—A cookie value is simply a piece of data
mapped to the cookie name.
expiration date—This date defines the lifetime of
the cookie.
domain—This is the domain that both created
and can read the cookie.
path—The path setting specifies the URL path
from which the cookie is valid.
security—This determines whether or not the
cookie can be retrieved in a nonsecure setting.
The function setcookie() stores a cookie on a user’s
machine.
$uid = “abcs";
$cookie_set = setcookie ("uid", $value, time()+3600, "/",
".rusl.lk", 0);
After reloading or navigating to any subsequent page,
the variable $uid becomes available, producing the user
id abcs
• This cookie will expire (thus be rendered unusable)
exactly one hour (3600 seconds) after it has been sent.
• The cookie is available for retrieval in all directories on
the server.
• This cookie is only accessible via the rusl.lk domain.
• This cookie is accessible via a nonsecured protocol.
<?
if(isset($unic_id)):
print $unic_id;
else:
$uniq_id="aaa";
setcookie ("myfirst", $uniq_id, time()+2592000);
print "ok set";
endif;
?>
Example
<?php
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(AboutVisit, date("Y-m-d H:i:s"), $Month);
?>
<?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last;
}
else
{
echo "Welcome to our site!";
}
?>
Session Handling
A session is best defined as the period of time
beginning when a user enters your site and
ending when the user exits.
The first concept that you need to know is that a
session is initiated with the function
session_start()

The function session_start() is twofold in purpose.


Once called, it checks to see if the user has
already started a session, and if the user has not,
it starts one.
session_destroy()
The function session_destroy() will destroy all persistent
data corresponding to
the current user session.
session_id()
The function session_id() returns the user’s SID
originally created by
session_start().

<?
session_start ();
print "Your session identification number is
".session_id();
session_destroy();
?>
creating your own session variables using
The function session_ register()
The function session_register() registers one or more
variable names with the
user’s current session.
<?php
session_start();
$my_session_variable = “username";
session_register("my_session_variable");
?>
<?php
session_start();
print "Value of 'my_session_variable':
$my_session_variable";
?>
<?php
session_start();
($_SESSION['count']) ? $_SESSION['count']++ : $_SESSION['count'] = 1;
?>
<html>
<head>
<title>Stuff by tedd</title>
</head>

<body>
<h1>tedd's session stuff (page 2)</h1>
<hr>
<h3>PHPSESSID = <?php echo session_id(); ?></h3>
<hr>
<h2>You have been here <?php echo( $_SESSION['count'] ); ?> times in

this session.</h2>
<a href="session1.php?<?php echo( SID ); ?>">Previous page</a>
</body>
</html>
</html>
<?php
session_start();
?>

<html>
<head>

<title>Stuff by tedd</title>
</head>

<body>

<h1>tedd's session stuff (page 1)</h1>


<hr>
<h3>PHPSESSID = <?php echo session_id(); ?></h3>
<hr>
<h2>Click the next page and see numbr of visits during this visit.</h2>
<a href="session2.php?<?php echo( SID ); ?>">Next page</a>
</body>
</html>
Applets
import javax.swing.JApplet; import
java.awt.Graphics;
public class HelloWorld extends JApplet
{ public void paint(Graphics g)
{ g.drawRect(0, 0,
getSize().width - 1, getSize().height - 1);
g.drawString("Hello world!", 5, 15); }
}
<Html>
<Head>
<Title>Java Example</Title>
</Head>

<Body>
This is my page<br>
Below you see an applet<br>
<br>
<Applet
Code=“HelloWorld.class" width=200 Height=100>
</Applet>
</Body>
</Html>
Attribute -Explanation -Example
Code - Name of class file --- Code="myapplet.class“
Width=n ……n=Width of applet -------- Width=200
Height=n …. n=Height of applet ------ Height=100
Codebase ….. Library where the applet is stored. If the applet is in same
directory as your page this can be omitted.

Codebase="applets/"
Alt="Text alt="Menu Applet”
Align=
Left
Justifies the applet
according to the
Align=Right
Right,Top,Texttop text and images
Middle,Absmiddle surrounding it.
Baseline,Bottom
Absbottom

V/hspace=n Space V/Hspace=20


over(under)/left(right)
and under the applet.
GOOD LUCK
By Pramudith Kandambi
 The PHP date() function is used to format a
time and/or date.
 The PHP date() function formats a timestamp
to a more readable date and time.
 A timestamp is a sequence of characters,
denoting the date and/or time at which a
certain event occurred.
 Syntax
date(format,timestamp)
Parameter Description

format Required. Specifies the format of the timestamp

timestamp Optional. Specifies a timestamp. Default is the current date and time
 Here are some characters that can be used:
◦ d - Represents the day of the month (01 to 31)
◦ m - Represents a month (01 to 12)
◦ Y - Represents a year (in four digits)

 Other characters, like"/", ".", or "-" can also be inserted


between the letters to add additional formatting:

<?php
echo date("Y/m/d") . "<br />";
echo date("Y.m.d") . "<br />";
echo date("Y-m-d")
?>
The output of the code above could be something like this:
◦ 2009/05/11
2009.05.11
2009-05-11
 The optional timestamp parameter in the date() function
specifies a timestamp.

 If you do not specify a timestamp, the current date and time will
be used.

 The mktime() function returns the timestamp for a date.

 Syntax for mktime()

◦ mktime(hour,minute,second,month,day,year,is_dst)

<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));

echo "Tomorrow is ".date("Y/m/d", $tomorrow);


?>
 The output of the code above could be something like this:
◦ Tomorrow is 2009/05/12
 You can insert the content of one PHP file into another PHP
file before the server executes it, with the
◦ include()
◦ require() .

 include() generates a warning, but the script will continue


execution

 require() generates a fatal error, and the script will stop

 These two functions are used to create functions, headers,


footers, or elements that will be reused on multiple pages.
 The include() function takes all the content in a specified file and
includes it in the current file.

 If an error occurs, the include() function generates a warning, but the


script will continue execution.

Example 1
 Assume that you have a standard header file, called "header.php". To
include the header file in a page, use the include() function:
<html>
<body>
<?php include("header.php"); ?>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
</body>
</html>
 The require() function is identical to include(), except that it
handles errors differently

Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>

 The echo statement is not executed, because the script


execution stopped after the fatal error.

 It is recommended to use the require() function instead of


include(), because scripts should not continue after an error.
 The fopen() function is used to open files in PHP.

 The first parameter of this function contains the name of the file
to be opened and the second parameter specifies in which mode
the file should be opened:

<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
Note: If the fopen() function is unable to open the specified file, it
returns 0 (false).
 Databases
◦ Store and maintain data
◦ MySQL is a free database product
◦ PHP supports many database operations
 Access databases from Web pages

10
 Interacting with databases
◦ SQL
 Structured Query Language
 Used to manipulate databases
◦ Several useful functions
 mysql_connect
 mysql_select_db
 mysql_query
 mysql_error
 mysql_fetch_row
 mysql_close

12
 The free MySQL database is very often used
with PHP.
 Before you can access data in a database, you
must create a connection to the database.

 In PHP, this is done with the mysql_connect()


function.
 Syntax

mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to connect to. Default value is "localhost:3306"
username Optional. Specifies the username to log in with. Default value is the name of
the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
<?php
$con = mysql_connect("localhost","peter","abc123");

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code
?>
<?php
$con=mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code

mysql_close($con);
?>
<?php
$con = mysql_connect("localhost","peter","abc123");

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
<?php
$con = mysql_connect("localhost","peter","abc123");

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
mysql_close($con);
?>
<?php

$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons


WHERE FirstName='Peter'");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }
?>
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons ORDER BY age");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'];
  echo " " . $row['LastName'];
  echo " " . $row['Age'];
  echo "<br />";
  }
mysql_close($con);
?>
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 PHP, you can both create and


retrieve cookie values.
 Cookies
◦ Store information on client computer
◦ Track preferences and other information
◦ Stored as text files on hard drive
◦ Never store sensitive information, such as credit
card numbers, in a cookie
 Security risk
 Cookies and PHP
◦ setcookie function
 Name
 Value
 Expiration date

22
 How to Create a Cookie?
◦ The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear


BEFORE the <html> tag.

Syntax
setcookie(name, value, expire, path, domain);
 You can also set the expiration time of the cookie in another way. It may be easier
than using seconds.

<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
..... In the example above the expiration time is set to a month (60 sec * 60 min *
24 hours * 30 days).

 How to Retrieve a Cookie Value?


 The PHP $_COOKIE variable is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and
display it on a page:

<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
<html>
<body>

<?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
  echo "Welcome guest!<br />";
?>

</body>
</html>
Example:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
Gathering data to be written as a cookie.

27
1 <?php
2 // Fig. 26.21: cookies.php
3 // Program to write a cookie to a client's machine
4
5 extract( $_POST );
6 // write each form field’s value to a cookie and set the
7 // cookie’s expiration date
8 setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 );
9 setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
10 setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
11 ?> Function setcookie takes the name of
12 the cookie to be set as the first
13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
argument, followed by the value to be
14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
15
stored in the cookie. The optional third
16 <html xmlns = "http://www.w3.org/1999/xhtml">
argument specifies the expiration date of
17 <head> the cookie.
18 <title>Cookie Saved</title>
19 </head>
20
21 <body style = "font-family: arial, sans-serif">
22 <p>The cookie has been set with the following data:</p>
23

28
24 <!-- print each form field’s value -->
25 <br /><span style = "color: blue">Name:</span>
Each form field’s value is printed to
26 <?php print( $NAME ) ?><br />
confirm the data that has been set as a
27
28 <span style = "color: blue">Height:</span>
cookie with the user.
29 <?php print( $HEIGHT ) ?><br />
30
31 <span style = "color: blue">Favorite Color:</span>
32
33 <span style = "color: <?php print( "$COLOR\">$COLOR" ) ?>
34 </span><br />
35 <p>Click <a href = "readCookies.php">here</a>
36 to read the saved cookie.</p>
37 </body>
38 </html> Hyperlink to readCookies.php.

29
Writing a cookie to the client.

30
 Reading cookies
◦ $_COOKIE environment variable
 Array
◦ foreach loop to access each element
 Split into key and value

31
 Cookie storage
◦ Internet Explorer
 Stores cookies in Cookies directory
 Text file

32
Cookies directory before a cookie is written.

Cookies directory after a cookie is written.

33
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 <!-- readCookies.php -->
5 <!-- Program to read cookies from the client's computer -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head><title>Read Cookies</title></head>
9
10 <body style = "font-family: arial, sans-serif">
11
12 <p>
13 <strong>
14 The following data is saved in a cookie on your
15 computer.
16 </strong>
17 </p>
18

34
19 <table border = "5" cellspacing = "0" cellpadding = "10">
20 <?php
The foreach PHPloop iterates
creates through
array the which
$_COOKIE
21
$_COOKIE array andall
contains prints the values
cookie name and valueby
indexed
22 // iterate through array $_COOKIE and print
23 // name and valueofofeach
each cookie
their in
cookie an XHTML table.
names.
24 foreach ( $_COOKIE as $key => $value )
25 print( "<tr>
26 <td bgcolor=\"#F0E68C\">$key</td>
27 <td bgcolor=\"#FFA500\">$value</td>
28 </tr>" );
29 ?>
30
31 </table>
32 </body>
33 </html>

35
Displaying the cookie’s content.

36
 When you are working with an application, you open it, do
some changes and then you close it. This is much like a
Session.
 But 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.

 A PHP session solves this problem by allowing you to store


user information on the server for later use (i.e. username,
shopping items, etc).
 However, session information is temporary and will be
deleted after the user has left the website.
 If you need a permanent storage you may want to store the
data in a database.
 Sessions work by creating a unique id (UID) for each visitor
and store variables based on this UID. The UID is either
stored in a cookie or is propagated in the URL.
 Before you can store user information in your PHP
session, you must first start up the session.

 Note: The session_start() function must appear


BEFORE the <html> tag:

<?php session_start(); ?>

<html>
<body>
</body>
</html>
The code above will register the user's session with
the server, allow you to start saving user information,
and assign a UID for that user's session.
 The correct way to store and retrieve session variables is to use the PHP
$_SESSION variable:

<?php
session_start(); // store session data

$_SESSION['views']=1;
?>
<html>
<body>
<?php //retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:
◦ Pageviews=1
40
By Pramudith Kandambi
Outline
Introduction
HTTP Request Types
System Architecture
Client-Side Scripting versus Server-Side Scripting
Accessing Web Servers
Microsoft Internet Information Services (IIS)
Microsoft Internet Information Services (IIS) 5.0
Microsoft Internet Information Services (IIS) 6.0
Apache Web Server
Requesting Documents
XHTML
ASP.NET
Perl
PHP
Python
Web Resources

2
` In this lesson, you will learn:
◦ To understand a Web server’s functionality.
◦ To introduce Microsoft Internet Information Services
(IIS) and Apache Web server.
◦ To learn how to request documents from a Web
server.

3
` Web server
◦ Responds to client requests by providing resources
` URI (Uniform Resource Identifier)
` Web server and client communicate with
platform-independent Hypertext Transfer
Protocol (HTTP)

4
IIS 5.0 IIS 6.0 Apache Web server
Company Microsoft Microsoft Apache Software
Corporation Corporation Foundation
Version 5.0 6.0 2.0.47
Released 2/17/00 3/28/03 7/10/03
Platforms Windows 2000, Windows Server 2003 Windows NT/2000/XP,
Windows XP Mac OS X, Linux and
other UNIX-based
platforms,
experimentally supports
Windows 95/98
Brief The most popular The newest release of Currently the most
description Web server for IIS from Microsoft. popular Web server.
Windows 2000.
Price Included with Included with Freeware.
Windows 2000 Windows Server 2003
and Windows XP.
Web servers discussed in this chapter.

5
` Request methods
◦ get
◦ post
◦ Retrieve and send client form data to Web server
◦ Post data to a server-side form handler

6
` Multi-tier application (n-tier application)
◦ Information tier (data or bottom tier)
x Maintains data for the application
x Stores data in a relational database management
system (RDBMS)
◦ Middle tier
x Implements business logic and presentation logic
x Control interactions between application clients and
application data
◦ Client tier (top tier)
x Application’s user interface
x Users interact directly with the application through the
client tier

7
` Client-side scripts
◦ Validate user input
x Reduce requests needed to be passed to server
x Access browser
x Enhance Web pages with DHTML, ActiveX controls, and
applets
` Server-side scripts
◦ Executed on server
◦ Generate custom response for clients
◦ Wide range of programmatic capabilities
◦ Access to server-side software that extends server
functionality

8
` Request documents from Web servers
◦ Host names
◦ Local Web servers
x Access through machine name or localhost
◦ Remote Web servers
x Access through machine name
◦ Domain name or Internet Protocol (IP) address
x Domain name server (DNS)
x Computer that maintains a database of host names and
their corresponding IP address

9
` An enterprise-level Web server that is
included with Windows

10
` FTP Site
◦ Used for transferring large files across the Internet
` HTTP Site
◦ Used most frequently to request documents from
Web servers
` SMTP Virtual Server
◦ Sends and receives electronic mail
` Web Site Content Directory
◦ Directory containing the documents that clients will
view

11
Internet Information Services window of Internet Services Manager.

12
Virtual Directory Creation Wizard welcome dialog.

13
Virtual Directory Alias dialog of the Virtual Directory Creation Wizard.

14
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.

15
Access Permissions dialog of the Virtual Directory Creation Wizard.

16
Internet Information (IIS) Services Manager window.

17
Virtual Directory Creation Wizard welcome dialog.

18
Virtual Directory Alias dialog of the Virtual Directory Creation Wizard.

19
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.

20
Access Permissions dialog of the Virtual Directory Creation Wizard.

21
` Currently the most popular Web server
` Stability
` Efficiency
` Portability
` Open-source

22
Apache Web server starting. (Courtesy of The Apache Software Foundation.)

23
` Requesting five different documents
◦ XHTML
◦ ASP.NET
◦ Perl
◦ PHP
◦ Python

24
` Request XHTML documents from IIS 6.0 or
Apache
◦ Launch Internet Explorer
◦ Enter XHTML document’s location in Address field

25
Requesting test.html from IIS 5.

Requesting test.html from IIS 6 or Apache.

26
` Request ASP.NET document from IIS 5 or 6
◦ Launch Internet Explorer
◦ Enter ASP.NET document’s location in Address field
` Apache support ASP Classic but doesn’t
support ASP.NET

27
Requesting test.aspx from IIS 5.

Requesting test.aspx from IIS 6.

28
` Request Perl document from IIS 5 or 6
◦ Launch Internet Explorer
◦ Enter the Perl document’s location in the Address
field
` Request Perl document on Apache Web server
◦ Put all Perl documents in cgi-bin directory
◦ Launch Internet Explorer
◦ Enter Perl document’s location in Address field

29
Requesting test.pl from IIS 5.

Requesting test.pl from IIS 6.

30
Requesting test.pl from Apache.

31
` Request PHP documents from IIS 5 and 6
◦ Launch Internet Explorer
◦ Enter PHP document’s location in the Address field
` Request PHP documents from Apache
◦ Save PHP documents in the htdocs directory
◦ Launch Internet Explorer
◦ Enter PHP document’s location in Address field

32
Requesting test.php from IIS 5.

Requesting test.php from IIS 6.

33
Requesting test.php from Apache.

34
` Request Python documents from IIS 5 and 6
◦ Launch Internet Explorer
◦ Enter Python document’s location in the Address
field
` Request Python documents from Apache Web
server
◦ Put Python documents in cgi-bin directory
◦ Launch Internet Explorer
◦ Enter Python document’s location in Address field

35
Requesting test.py from IIS.

Requesting test.py from IIS 6.

36
Requesting test.py from Apache.

37
` www.microsoft.com/msdownload/ntoptionpack/askwiz.asp
` www.w3.org/Protocols
` www.apache.org
` httpd.apache.org
` httpd.apache.org/docs-2.0
` www.apacheweek.com
` linuxtoday.com/stories/18780.html
` www.iisanswers.com
` www.iisadministrator.com

38

Você também pode gostar