Anda di halaman 1dari 271

IBM Global Business Services

HTML Forms & JavaScript


Copyright IBM Corporation 2009

IBM Global Business Services

Welcome!

Copyright IBM Corporation 2009

IBM Global Business Services

Day 1

Copyright IBM Corporation 2009

IBM Global Business Services

Housekeeping

Breaks Washrooms Transportation / parking No pagers or cell phones Participation Parking lot issues Questions

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course objectives

After completing this course, you should be able to: Create HTML Forms Put in your own words an introduction to JavaScript Explain JavaScript operators and expressions Define flow control and functions Identify objects and arrays Describe document object model Describe Cookies Explain session outline

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module1 : HTML Forms Module 2: Introduction to JavaScript Module 3: JavaScript operators and expressions Module 4: Flow control and functions Module 5: Objects and arrays Module 6: Document object model Module 7: Cookies Module 8: Session outline

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Developing HTML Forms

Copyright IBM Corporation 2009

IBM Global Business Services

Form

An HTML form is a section of a document containing normal content, markup, special elements called controls (checkboxes, radio buttons, menus, etc.), and labels on those controls. Users generally "complete" a form by modifying its controls (entering text, selecting menu items, etc.), before submitting the form to an agent for processing (e.g., to a Web server, to a mail server, etc.)

Copyright IBM Corporation 2009

IBM Global Business Services

Form (Contd.)

A form is defined with the <form> tag.

Copyright IBM Corporation 2009

IBM Global Business Services

Form Controls
TextField: Are used to accept user input. It is a single line input control. CheckBox Checkboxes are used when you want the user to select one or more options of a limited number of choices. RadioButton Radio Buttons are used when you want the user to select one of a limited number of choices. Select Are used when you want users to choose options from a selectable lists. TextArea Are used to accept user input. TextArea allows entry of multiple lines.

Copyright IBM Corporation 2009

IBM Global Business Services

Form Controls (Contd.)

PushButton Each push button may have client side script associated with the element's event attributes. When an event occurs (e.g., the user presses the button, releases it, etc.), the associated script is triggered. Submit Button When activated, a submit button submits a form. A form may contain more than one submit button. Reset Button When activated, a reset button resets all controls to their initial values.

Copyright IBM Corporation 2009

IBM Global Business Services

Form Controls (Contd)


Form Component TextField Checkbox RadioButton ComboBox TextArea

Tag <input> <input> <input> <select> <option> type type type name value

Attribute name name name

Usage value <input type="text" name="t1" value="Paul"> value <input type="checkbox" name="c1" value="v1"> value <input type="radio" name="r1" value="v2"> <select name="s1"><option value="v1">Display item</option></select> name <textarea name="n1" row="5" col="20"> value <input type="button" name="b1" value="Click"> <input type="submit" name="s1" value="Submit"> <input type="reset" value="Reset">

Output
Paul

O Select an item

<textarea> row <input> type

col name

Click
Submit

PushButton

Reset

Copyright IBM Corporation 2009

IBM Global Business Services

Form Controls using Attributes:


INPUT Attribute definitions type = text|password|checkbox|radio|submit|reset|file|hidden|image|button This attribute specifies the type of control to create. The default value for this attribute is "text". name = cdata This attribute assigns the control name. value = cdata This attribute specifies the initial value of the control. It is optional except when the type attribute has the value "radio" or "checkbox". size = cdata This attribute tells the initial width of the control. The width is given in pixels except when type attribute has the value "text" or "password". In that case, its value refers to the (integer) number of characters.

Copyright IBM Corporation 2009

IBM Global Business Services

Form Controls using Attributes:


INPUT Attribute definitions (Contd ) maxlength = number When the type attribute has the value "text" or "password", this attribute specifies the maximum number of characters the user may enter. This number may exceed the specified size, in which case the user should offer a scrolling mechanism. The default value for this attribute is an unlimited number. Checked When the type attribute has the value "radio" or "checkbox", this boolean attribute specifies that the button is on. src = uri When the type attribute has the value "image", this attribute specifies the location of the image to be used to decorate the graphical submit button.

Copyright IBM Corporation 2009

IBM Global Business Services

Form Controls using Attributes:


SELECT Attribute definitions name = cdata This attribute assigns the control name. size = number If a SELECT element is presented as a scrolled list box, this attribute specifies the number of rows in the list that should be visible at the same time. Multiple If set, this boolean attribute allows multiple selections. If not set, the SELECT element only permits single selections.

Copyright IBM Corporation 2009

IBM Global Business Services

Pre Selected Options:


Zero or more choices may be pre-selected for the user. Users should determine which choices are pre-selected as follows: If no OPTION element has the selected attribute set, the initial state has the first option selected. If one OPTION element has the selected attribute set, it should be pre-selected. If the SELECT element has the multiple attribute set and more than one OPTION element has the selected attribute set, they should all be pre-selected. It is considered an error if more than one OPTION element has the selected attribute set and the SELECT element does not have the multiple attribute set.

Copyright IBM Corporation 2009

IBM Global Business Services

Example of a Form
<html> <head> <title> Form Example</title> </head> <body bgcolor=pink > <center> <h3> Data Entry Form</h3> <form> <table> <tr><td>Name</td><td> <input type="text" name="t1"> </td></tr> <tr><td>Gender</td><td> <input type="radio" name=r1 value=m> Male <input type="radio" name=r1 value=f>Female</td></tr> <tr><td>Qualification</td><td><select name=s> <option >Select</option> <option value=M.Sc>M Sc</option> <option value=M.A.>MA</option> <option value="other">other</option></select> </td></tr> <tr><td> <input type="submit" value="submit"> </td> <td> <input type="reset" value="reset"> </td></tr> </table> </center> </form> </body> </html>

Copyright IBM Corporation 2009

IBM Global Business Services

Output of the Form

Copyright IBM Corporation 2009

IBM Global Business Services

Fieldset & Legend Tag

The fieldset tag is used to group the form elements whilst the legend tag provides a label for the fieldset. The HTML legend tag is used for labelling the fieldset element. By using the fieldset tag and the legend tag, you can make your forms much easier to understand for your users.

Copyright IBM Corporation 2009

IBM Global Business Services

Output Required

Copyright IBM Corporation 2009

IBM Global Business Services

Code Snippet
<html> <body> <fieldset style="text-align:right;"> <legend><b>Address Details</b></legend> Favorite Address <input type="text" /><br/> Least Favorite Address <input type="text" /><br/> Current Address <input type="text" /><br/> Your Next Address <input type="text" /><br/> </fieldset> <br> <fieldset align="left"> <legend>Personal Info</legend> Name : <input type="text"> Age : <input type="text"> Gender : <input type="radio" name="r1">Male <input type="radio" name="r1">Female </fieldset> </body> </html>
Copyright IBM Corporation 2009

IBM Global Business Services

<fieldset> tag is used to group the form elements


<html> <body> <fieldset style="text-align:right;"> <legend><b>Address Details</b></legend> Favorite Address <input type="text" /><br/> Least Favorite Address <input type="text" /><br/> Current Address <input type="text" /><br/> Your Next Address <input type="text" /><br/> </fieldset> <br> <fieldset align="left"> <legend>Personal Info</legend> Name : <input type="text"> Age : <input type="text"> Gender : <input type="radio" name="r1">Male <input type="radio" name="r1">Female </fieldset> </body> </html>
Copyright IBM Corporation 2009

IBM Global Business Services

<legend> tag is used give a suitable label to the group.


<html> <body> <fieldset style="text-align:right;"> <legend><b>Address Details</b></legend> <legend> Favorite Address <input type="text" /><br/> Least Favorite Address <input type="text" /><br/> Current Address <input type="text" /><br/> Your Next Address <input type="text" /><br/> </fieldset> <br> <fieldset align="left"> <legend>Personal Info</legend> <legend> Name : <input type="text"> Age : <input type="text"> Gender : <input type="radio" name="r1">Male <input type="radio" name="r1">Female </fieldset> </body> </html>
Copyright IBM Corporation 2009

IBM Global Business Services

Given a Label using legend tag

Created groups using fieldset tag

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module1 : HTML Forms Module 2: Introduction to JavaScript Module 3: JavaScript operators and expressions Module 4: Flow control and functions Module 5: Objects and arrays Module 6: Document object model Module 7: Cookies Module 8: Session outline

25

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Introduction to JavaScripts

What is JavaScript?
JavaScript is a scripting language created by Netscape Scripting language is a lightweight programming language.

What is a What is a scripting scripting language? language?

Scripting languages are not needed to be compiled. The language is interpreted at runtime.

26

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Introduction to JavaScript (continued)

A JavaScript is usually directly embedded in an HTML page. External JavaScripts can be created which can be used by HTML pages. JavaScript adds interactivity to HTML pages. JavaScript's are integrated into the browsing environment.

27

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Introduction to JavaScript (continued)


Java is a programming language which requires compilation and interpretation. Java is used to make large scale applications. JavaScript is a scripting language which just requires interpretation. The script is some set of commands which the browser interprets. JavaScript is used to add interactivity in HTML Pages.

Is JavaScript same as Java?

28

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Types of JavaScript

Client-Side JavaScript (CSJS) This is an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers. Server-Side JavaScript (SSJS) This is an extended version of JavaScript that enables back-end access to databases, file systems, and servers. Core JavaScript This is the base JavaScript language.

29

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Core JavaScript
Core JavaScript encompasses all of the statements, operators, objects, and functions that make up the basic JavaScript language. The following objects are part of core JavaScript:
array date math number string

30

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Client-side Java scripting


CSJS is composed of core JavaScript and many additional objects, such as the following:
Document Form Frame Window Navigator History

31

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Server side JavaScript

SSJS is composed of core JavaScript and additional objects and functions for accessing databases and file systems, sending e-mail, and so on. SSJS enables developers to quickly and easily create database-driven web applications by leveraging their existing knowledge of JavaScript. It's used to create and/or customize server-based applications by scripting the interaction between objects.

32

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Uses of JavaScript (client side)


Menus for navigation Form validation Popup windows Password protecting Math functions Special effects with document and background Status bar manipulation Messages Mouse cursor effects Links

33

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

Client side JavaScript ________________ is an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers. Server side JavaScript Core JavaScript

34

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Syntax rules of JavaScript


Statements may or may not contain a semicolon at the end. Multiple statements on one line must be separated by a semicolon. JavaScript is case sensitive.

35

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Using <script> tag


The HTML <script> tag is used to enter JavaScript into a HTML. The <script> tag can be embedded within <head> tag. <body> tag. JavaScript in the head section will be executed when called. JavaScript in the body section will be executed while the HTML page is loaded. Unlimited number of JavaScripts can be placed both in head and body section in a HTML document.

36

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Using <script> tag


Example: <html> <head><title>Example</title> </head> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> Is a standard command for writing output to a page

37

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

How to handle older browsers


Browsers that do not support JavaScript will display the script as it is. Use the HTML comment tag to prevent this. Example <script type="text/javascript"> <!-document.write("Hello World!") // --> </script>
The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line.

38

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Using an external JavaScript


A JavaScript can be written in an external file, which can be used by different HTML pages. The external script cannot contain the <script> tag. The external file needs to end with the .js extension.

39

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Using external JavaScript (continued)


document.write ("This line has been writen in the External JavaScript!!!") External.js

<html> <head><title>Example</title> </head> <body> <script src="External.js"> </script>> <p > This line has been written in the html page!!! </p> </body> </html> JavaScript.html

40

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

<script></script> is embedded within Select the correct statement / s <head> </head> <script></script is embedded within <body></body> <script></script> is embedded within <title></title>

41

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

<script></script> is embedded within Select the correct statement / s <head> </head> <script></script is embedded within <body></body> <script></script> is embedded within <title></title>

42

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module1 : HTML Forms Module 2: Introduction to JavaScript Module 3: JavaScript operators and expressions Module 4: Flow control and functions Module 5: Objects and arrays Module 6: Document object model Module 7: Cookies Module 8: Session outline

43

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript variables and expression


JavaScript Variables Variable:
A variable is a symbolic name that represents some data in the memory. A variable value can change during the execution of the JavaScript. A variable can be referred by its name to see or change its value. Variables are name are case sensitive. Must begin with a letter or underscore.

44

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Rules of a variable
Variable declaration
Variables can be declared using the var statement var <variable name>=some value Variables can also be created without using var statement <variable name>=some value Example var firstname=Samuel OR firstname=Samuel

45

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Data type in JavaScript


JavaScript is a loosely typed language. Data Type of Variable need not be specified during declaration. Loosely Typed? Loosely Typed? Data types are automatically converted during script execution.

46

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Data type in JavaScript (continued)


JavaScript recognizes the following type of values:

Values

numbers string

boolean true or false null

9, 3.56

Samuel, Samuel J Palmisano

A special keyword which refers to nothing

47

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Data type in JavaScript (continued)

48

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators

Operators

Arithmetic

Assignment

Conditional

String Comparison typeof Logical

49

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators (continued)

Arithmetic

50

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators (continued)

Comparison

51

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators (continued)

Assignment

52

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators (continued)

Logical

53

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators (continued)

String

54

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators (continued)

Conditional

55

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript operators (continued)

typeof

56

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

x=20 x=Test typeof(x) evaluates to

Number String null

57

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module1 : HTML Forms Module 2: Introduction to JavaScript Module 3: JavaScript operators and expressions Module 4: Flow control and functions Module 5: Objects and arrays Module 6: Document object model Module 7: Cookies Module 8: Session outline

58

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Flow control

Conditional statements
if statement - use this statement if you want to execute some code only if a specified condition is true. if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false. if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed. switch statement - use this statement if you want to select one of many blocks of code to be executed.

59

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

While statement

60

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Break and continue statements


There are two special statements that can be used inside loops: break. continue. Break The break command will break the loop and continue executing the code that follows after the loop (if any). Continue The continue command will break the current loop and continue with the next value.

61

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example of break statement

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

Result

The number is 0 The number is 1 The number is 2

62

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example of continue statement

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

Result The number is 0 The number is 1 The number is 2 The number is 4 The number is 5

63

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

For loop

64

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Functions

A function is a reusable piece of code that will be executed when called for. A function can be called from anywhere from within the page or even from other pages if the function is stored in an external JavaScript (.js) file. Functions can be embedded in the <head></head> and within the<body> </body> tag.

65

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Predefined functions in JavaScript

DialogBoxes
alert( message) Displays an alert box with a message defined by the string message. Example: alert(An Error Occurred!)

66

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Predefined functions in JavaScript (continued)

confirm(message)
When called, it will display the message and two boxes. One box is "OK" and the other is "Cancel". If OK is selected, a value of true is returned, otherwise a value of false is returned. Example confirm(Do you wish to Continue?)

67

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Predefined functions in JavaScript (continued)


prompt(message)
Displays a box with the message passed to the function displayed. The user can then enter text in the prompt field, and choose OK or Cancel. If the user chooses Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the field is returned.

Example: Prompt (enter your Name)

68

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Predefined functions in JavaScript (continued)


Conversion Functions
eval(string) Converts a string to an integer or a float value. Example: x=20 y=eval(x)+10 y contains the value 30

69

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Predefined functions in JavaScript (continued)

isNaN(value) If the value passed is not a number then a boolean value of true is returned else the boolean value of false is returned. Example x=Samuel y=isNaN(x) The value stored in y is true

70

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Predefined functions in JavaScript (continued)

parseInt(string) Converts a string to an integer returning the first integer encountered which is contained in the string. Example: x=77AB67 y=parseInt(x) y stores the value 77

71

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Predefined functions in JavaScript (continued)

parseFloat(string) Converts a string to an float value . Example x=77.5AB67 y=parseFloat(x) y stores the value 77.5

72

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

User defined functions

73

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

User defined functions (continued)

74

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

User defined functions (continued)

75

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Events

76

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Events (continued)

77

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Event handlers

78

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Common event handlers

79

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Common event handlers (continued)

80

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Common event handlers (continued)

onLoad and onUnload


The onload and onUnload events are triggered when the user enters or leaves the page. The onload event is also triggered when the image is loaded.

The showstatus() function will be called when a user enters a page <body onload=showStatus()>

81

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Common event handlers (continued)

onFocus, onBlur and onChange


The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
The checkEmail() function will be called whenever the user changes the content of the field:

<input type="text" size="30" id="email" onchange="checkEmail()">;

82

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Common event handlers (continued)

onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.

The checkForm() function will be called when the user clicks the submit button in the form. <form method="post" action="xxx.htm" onsubmit="return checkForm()">

83

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Common event handlers (continued)

onMouseOver and onMouseOut


onMouseOver and onMouseOut are often used to create "animated" buttons. An alert box appears when an onMouseOver event is detected: <a href="http://www.ibm.com" onmouseover="alert('An onMouseOver event)> <img src=ibmlogo.gif" width="100" height="30"> </a>

84

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

85

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

86

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example

87

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)

88

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)

89

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)

90

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)

91

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)

92

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)

function Addition(x,y) { var x1=document.form1.text1.value var y1=document.form1.text2.value var Ans=document.form1.text3.value var temp=x1+y1 }

93

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)

function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1

94

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)
function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 }

<INPUT TYPE=button value= +op onClick=Addition(text1.value,text2.value)>

95

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example (continued)
function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 if(Ans==temp) { alert(Your Result agrees with JavaScript!) document.form1.text1.value= document.form1.text2.value= document.form1.text3.value= } else { alert(No, JavaScript evalutes this operation differently) document.form1.text3.value= } }
96 JavaScript Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

97

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

98

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

A complete program
<html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt) } </script> </head> <body> <form> <input type="button" onClick="myfunction('Good Evening!')" value="In the Evening"> </form> <p> When you click on one of the buttons, a function will be called. The function will alert the argument that is passed to it. </p> </body> </html>
99 JavaScript Copyright IBM Corporation 2009

<input type="button" onClick="myfunction('Good Morning!')" value="In the Morning">

IBM Global Business Services

Output

100

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

myfunction (txt) receives Good Morning!

101

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

myfunction (txt) receives Good Evening !

102

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module1 : HTML Forms Module 2: Introduction to JavaScript Module 3: JavaScript operators and expressions Module 4: Flow control and functions Module 5: Objects and arrays Module 6: Document object model Module 7: Cookies Module 8: Session outline

103

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects

JavaScript is not a true Object Oriented language as C++ or Java but rather an Object Based language. Objects in JavaScript are software entities such as the browser window or an HTML document.

104

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

105

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

106

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

107

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

108

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

109

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

110

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

111

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

112

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript objects (continued)

113

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Instances of computer objects (continued)

114

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects

115

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

Boolean 1. 2. 3. 4. 5. 6. Boolean Date Function Math Number String Function Date

Math

Number

String

116

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

1. 2. 3. 4. 5. 6.

Boolean Date Function Math Number String Function Date Boolean

Math

Number

String

117

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

Boolean object
This object is used to convert a non boolean value to a boolean value. The Boolean object is an Object Wrapper for a Boolean value Boolean object is defined with the new keyword var BooleanObj=new Boolean()

118

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript Core Objects (contd.)

All the following lines of code create Boolean objects with an initial value of false :
var myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean("") var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)

119

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

All the following lines of code create Boolean objects with an initial value of true:
var myBoolean=new Boolean(true) var myBoolean=new Boolean("true") var myBoolean=new Boolean("false") var myBoolean=new Boolean("Richard")

120

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

121

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

122

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

1. 2. 3. 4. 5. 6.

Boolean Date Function Math Number String

Boolean

Math Number String

Date

Function

123

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)


Date Object
The Date object is used to work with dates and times. An instance of the Date object with the "new" keyword. An instance of Date object can be created as:
var myDate=new Date() var myDate=new Date("Month dd, yyyy hh:mm:ss") var myDate=new Date("Month dd, yyyy") var myDate=new Date(yy,mm,dd,hh,mm,ss) var myDate=new Date(yy,mm,dd) var myDate= new Date(milliseconds)

124

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

125

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

126

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

127

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

128

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

129

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

130

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

131

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

132

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

133

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)


Commonly used methods of the Date Object

134

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

135

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

1. 2. 3. 4. 5. 6.

Boolean Date Function Math Number String

Boolean

Math

Date

Number

Function

String

136

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

137

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

138

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

139

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

140

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

1. 2. 3. 4. 5. 6.

Boolean Date Function Math Number String

Boolean Date

Math

Number

Function

String

141

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

Math Object
Math object allows to perform common mathematical functions. The Math object includes several Mathematical values and functions. The Math object need not be defined before using it.

142

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

Mathematical values provided by JavaScript

Math.E Math.PI Math.SQRT2 Math.SQRT1_2 Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E

143

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)


Methods of Math object

144

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

145

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

146

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

1. 2. 3. 4. 5. 6.

Boolean Date Function Math Number String Function Date Boolean

Math

Number

String

147

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

148

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

149

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

150

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

1. 2. 3. 4. 5. 6.

Boolean Date Function Math Number String Date Boolean

Math

Number

String Function

151

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

String object
The String object is used to manipulate a stored piece of text. String objects must be created using the new keyword. JavaScript automatically converts the string primitive to a temporary String object A string literal can be embedded within a single or double quotation marks.

152

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)

String primitives and String objects give different results when evaluated as JavaScript. Primitives are treated as source code, but String objects are treated as a character sequence object.
s1 = "2 + 2 // creates a string primitive // creates a String object // returns the number 4 // returns the string "2 + 2 // returns the number 4 s2 = new String("2 + 2") eval(s1) eval(s2) eval(s2.valueOf());

153

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

JavaScript core objects (continued)


Common Methods of String Object

154

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Defining Arrays

An Array object is used to store a set of values in a single variable name. An Array object is created with the new keyword. An array can be created as:
var MyArray=new Array()

An array can also be created by specifying the array size.


var MyArray=new Array(3)

155

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Arrays (continued)

Data can be entered into an array as:


var MyArray=new Array() MyArray[0]=Paul MyArray[1]=Sam MyArray[2]=Niel

Data can also be entered into an array as:


var MyArray=new Array(Paul,Sam, Niel)

156

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Arrays (continued)

Accessing Arrays
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 . var MyArray=new Array() Myarray [0]

The starting index

157

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module1 : HTML Forms Module 2: Introduction to JavaScript Module 3: JavaScript operators and expressions Module 4: Flow control and functions Module 5: Objects and arrays Module 6: Document object model Module 7: Cookies Module 8: Session outline

158

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object model


The DOM is a programming API for documents. It is based on an object structure that closely resembles the structure of the documents it models. For instance, consider this table, taken from an HTML document:
<TABLE> <TBODY> <TR> <TD>Shady Grove</TD> <TD>Aeolian</TD> </TR> <TR> <TD>Over the River, Charlie</TD> <TD>Dorian</TD> </TR> </TBODY> </TABLE>

159

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object model (continued)


Graphical representation of the DOM of the example table

160

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object model (continued)


With JavaScript you can restructure an entire HTML document. You can add, remove, change, or reorder items on a page. To change anything on a page, JavaScript needs access to all elements in the HTML document. This access, along with methods and properties to add, move, change, or remove HTML elements, is given through the Document Object Model (DOM). In 1998, W3C published the Level 1 DOM specification. This specification allowed access to and manipulation of every single element in an HTML page. All browsers have implemented this recommendation, and therefore, incompatibility problems in the DOM have almost disappeared.

161

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object model (continued)


Document Tree

162

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

How to access the nodes in an HTML

You can find the element you want to manipulate in several ways:
By using the getElementById() and getElementsByTagName() methods By using the parentNode, firstChild, and lastChild properties of an element node

163

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Navigator object

Navigator object is the object representation of the client internet browser or web navigator program that is being used. This is a top level object to all others object in DOM hierarchy.

164

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Navigator object properties

appCodeName The name of the browsers code such as Internet Explorer appName The name of the browser. appVersion The version of the browser. plugins An array of plug-ins supported by the browser and installed on the browser. cpuClass The type of CPU which may be x86. cookieEnabled A boolean value of true or false depending on whether Cookies are enabled in the browser.

165

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Navigator object methods

JavaEnabled() Returns a boolean telling if the browser has JavaScript enabled.

166

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Window object and collections

Window object The Window object is the top level object in the JavaScript hierarchy. The Window object represents a browser window. A Window object is created automatically with every instance of a <body> or <frameset> tag. Window object collections Frames[] Returns all named frames in the window.

167

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Window object properties


name sets of return the name of the window. status sets or returns the name of the window. length sets or returns the number of frames in the window. self returns a reference to the current window. Status bar - sets whether or not the browsers status bar should be visible. toolbar - sets whether or not the browsers toolbar should be visible. closed Returns all named frames in the window document history

168

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Window object methods


open() Opens a new browser window. createPopup() Creates a popup window. setInterval(code,millisec[,lang]) Evaluates an expression at specified intervals. clearInterval(id_of_setInterval) cancels a timeout that is set with the setInterval() method. setTimeout(code,millisec[,lang]) Evaluates an expression after a specified number of milliseconds. clearTimeout(id_of_setTimeout) cancels a timeout that is set with the setTimeout() method. focus() sets the focus to the current window. blur() removes focus from the current window. close() closes the current window.

169

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object
Frame object represents an HTML frame. For each instance of a <frame> tag in an HTML document, a Frame object is created.

170

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

In Document Object Model Frames are instances of Window object

171

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

172

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

173

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

174

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

175

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

176

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

177

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

178

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

179

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

180

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

181

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

182

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

183

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

184

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

185

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

186

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Frame object (continued)

187

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

188

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

189

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object

The document object represents the entire HTML document and can be used to access all elements in a page. The document object is part of the window object and is accessed through the window.document property or simply document.

190

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object collections

anchors[] - Returns a reference to all Anchor objects in the document. forms[] - Returns a reference to all Form objects in the document. images[] - Returns a reference to all Image objects in the document. links[] - Returns a reference to all Area and Link objects in the document.

191

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object properties

Body gives direct access to the <body> element. Cookie Sets or returns all Cookies associated with the current document. lastModified Returns the date and time a document was last modified. Title Returns the title of the current document. URL Returns the URL of the current document.

192

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Document object methods


write() - Writes HTML expressions or JavaScript code to a document writeln() Similar to write(), with the addition of writing a new line character after each expression. open() - Opens a stream to collect the output from any document.write() or document.writeln() methods. close() - Closes an output stream opened with the document.open() method, and displays the collected data getElementByID() Returns a reference to the first object with the specified id. getElementsByName() Returns a collection of objects with the specified name. getElementsByTagName() Return a collection of objects with the specified tag name.

193

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object

Location object is an JavaScript object it is not an DOM object. The Location object is automatically created by the JavaScript runtime engine and contains information about the current URL. The Location object is part of the Window object and is accessed through the window.location property.

194

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object (continued)

195

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object (continued)

196

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object (continued)

197

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object (continued)

198

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object (continued)

199

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object (continued)

200

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object methods

Assign (url) It loads a new document. Reload() the current document. Replace() Replaces the current document with a new one.

201

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object example


<html><body><script> switch (window.location.protocol) { case "http:": document.write("From Web<BR>\n") break case "file:": document.write("From Local computer<BR>\n") break default: document.write("Unknown Source<BR>\n") break } </script></body></html>

202

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object example

Output: If Accessed from the Local File System

203

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Location object example

Output: If the page is delivered by a Web Server.

204

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

History object
History object is a JavaScript object. The History object is automatically created by the JavaScript runtime engine and consists of and array of URLs. It is a part of window object and accessed through window.history property.

205

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

History object

206

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

History object

207

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

History object

208

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

History object

209

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

210

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

211

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model

212

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

213

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

214

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

215

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

216

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

217

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

218

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

219

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

220

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

221

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

222

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

223

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

224

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

225

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

226

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

227

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

228

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

229

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

230

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Form object model (continued)

231

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

232

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

233

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

234

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Test your understanding

235

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module1 : HTML Forms Module 2: Introduction to JavaScript Module 3: JavaScript operators and expressions Module 4: Flow control and functions Module 5: Objects and arrays Module 6: Document object model Module 7: Cookies Module 8: Session outline

236

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Cookies
A cookie can store a small amount of information about a user visiting a site. A cookie is a small text file that is stored on the site visitor's computer by their browser . Because the cookie is stored on the users computer, it does not require any server space no matter how many users you have . With JavaScript, you can both create and retrieve cookie values.

237

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Cookies (continued)

You can use Cookies to:


save user preferences. customize data. remember the last visit. Keep track of items in an order while a user browses. Remember the information your sites visitors gave last time.

Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie

238

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Cookies (continued)

What does a cookie contain?


Name value pair: The first element in a cookie is a "name" attribute, followed by the data to be stored in the cookie. The expiry date: Specifies how long the cookie is valid for.

239

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Cookies (continued)

What does a cookie contain?


The path: This states where the cookie may be accessed from on the Web site. Most often, this is set to the server's document root. The domain: The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional.

240

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Questions

The name-value pair is the _____________ element in the Cookie

First

Second

Third

241

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Answer

The name-value pair is the _____________ element in the Cookie

First

Second

Third

242

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Cookies and security

Turn up security level on your browser to disable Cookies or prompt for cookie. Delete the content of a cookie and then write protect it. Use 3rd party software:
Cookie Pal, CookieMaster, CookieCrusher to monitor, browse and edit Cookies.

243

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Format of cookie

First the name value pair. Then a semicolon and a space. Then the expiry date. Expiry date should be in UTC format. Then again a semicolon and a space. Then the path.

244

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Format of cookie (continued)

document.cookie=<name of cookie>=<value of cookie>;<blank space>expires=<date in UTC format>;<blank space>path=<path location>

Example

document.cookie = user=Paul; expires=Thu, 2 Aug 2008 20:47:11 UTC; path=/'

245

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example of setting a cookie


<html> <head> <script language="JavaScript"> function setCookie(name, value) { var exp=new Date("January 31,2008") document.cookie=name+"="+escape (value)+"; expires="+exp.toGMTString() +"; path=/ document.write(Cookie has been set) )
Set an expiry date

</script></head> <body> <form> <input type="button" value="Set a Cookie" onClick="setCookie(user',Paul Smith')"> </form> </body> </html>
What does the escape function do?

246

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Escape () function

There's no escape!
Strictly speaking, we should be escaping our cookie values -- encoding nonalphanumeric characters such as spaces and semicolons. This is to ensure that our browser can interpret the values properly. Fortunately this is easy to do with JavaScript's escape() function. For example document.cookie = "username=" + escape(Paul Smith") + "; expires=15/02/2003 00:00:00";

247

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Example of setting a cookie


<html> <head> <script language="JavaScript"> function setCookie(name, value) { var exp=new Date("January 31,2008") document.cookie=name+"="+escape (value)+"; expires="+exp.toGMTString() +"; path=/ document.write(Cookie has been set) )
The value stored is user=Paul Smith
248 JavaScript

</script> </head> <body> <form> <input type="button" value="Set a Cookie" onClick="setCookie(user',Paul Smith')"> </form> </body> </html>
Setting the cookie

Copyright IBM Corporation 2009

IBM Global Business Services

Reading a cookie
<html> <head> <script language="JavaScript"> function readCookie() { var ca = document.cookie document.write(ca) }
Returns the cookie name value pair

</script> </head> <body> <form><input type="button" value="read" onClick="readCookie()"> </form> </body>


Value retrieved is

</html>

user=Paul Smith

249

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Extracting only the value from the Cookie


<html><head> <script language="JavaScript"> function readCookie(c_name) { if (document.cookie.length>0) {c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length } </script> </head> <body> <form> <input type="button" value="read" onClick="readCookie('user')"> </form> </body></html> document.write( document.cookie.substring(c_start, c_end)) } } Displays the value: Paul Smith

250

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Delete Cookies
<html> <head> <script language="JavaScript"> function deleteCookie ( cookie_name) { var cookie_date = new Date ( ) cookie_date.setTime ( cookie_date.getTime() - 1 ) document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString() } </script> </head>
251 JavaScript Copyright IBM Corporation 2009

<body> <form> <input type="button" value=delete" onClick="deleteCookie(user')"> </form> </body> </html>


The cookie's expiry date is set to one second less then the current date.

IBM Global Business Services

Modifying a Cookie

To modify a cookie simply reset the values and use the same procedure for setting the cookie. Ensure that the cookie name is existing or a new cookie will be created.

252

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Course map
Module 1: Introduction to JavaScript Module 2: JavaScript operators and expressions Module 3: Flow control and functions Module 4: Objects and arrays Module 5: Document object model Module 6: Cookies Module 7: Session outline

253

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Session outline

What is ajax? Advantages and disadvantages Xmlhttprequest A first example

254

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

What is Ajax?

Asynchronous JavaScript and XML. Ajax is group of interrelated development techniques used for creating interactive web applications. It allows web applications to retrieve data from the server asynchronously
Without interfering with the current state of the page

Data is retrieved using the XMLHttpRequest object


or, in browsers that do not support it, through the use of Remote Scripting

255

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

What is Ajax? (Continued)

Two components:
Client Side (e.g. JavaScript)
determine when to contact server contact it display results on page

Server side (e.g. PHP) like normal PHP script but return specifically what is required
maybe just OK or Fail maybe XML or HTML

256

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Technologies used for Ajax

XHTML and CSS for presentation the Document Object Model for dynamic display of and interaction with data XML and XSLT for the interchange and manipulation of data, respectively the XMLHttpRequest object for asynchronous communication JavaScript to bring the above technologies together

257

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

What is Ajax?

258

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Uses of Ajax

AJAX has many potential uses including: updating page information real-time data validation obtaining data for a control responding to server events pushing data to the client real-time interaction real-time monitoring auto completion
Google Suggest helped to initially popularise Ajax in 2005

259

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Advantages of Ajax

Different pages on a website often have much common content with traditional web-techniques, that content has to be reloaded on every request with Ajax a web application can request only the content that needs to be updated sections of pages can be reloaded individually reduces bandwidth usage / load time
260 JavaScript Copyright IBM Corporation 2009

IBM Global Business Services

Advantages of Ajax

The use of asynchronous requests allows a client's browser to be more interactive / respond more quickly to input
_ Application will appear faster / responsive - even if the application has not changed on the server side

Use of Ajax reduces connections to the server, since scripts and style sheets only have to be requested once Ajax allows programmers to make a separation between the methods they use to deliver information via the Internet and formats they use to present it

261

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Disadvantages of Ajax

Dynamically created pages do not register themselves in a browser's history


BACK button does not return the user to an earlier state of an Ajax-enabled page but to the last page visited
Workarounds include changing the anchor portion of the URL (following the #) when AJAX is run and monitoring it for changes

Dynamic web page updates make it difficult for a user to bookmark a particular state of an application
solutions to this problem exist, many of which also use the URL fragment identifier
To keep track of, and allow users to return to, the application in a given state

262

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

XMLHttpRequest (XHR)
XMLHttpRequest (XHR)
An API that can be used by javascript and other web browser scripting languages Used to transfer XML and other text data between a web server and a browser

Though it can do synchronous fetches, it is almost always asynchronous


Due to the greater UI responsiveness

Examples of web apps that make use of XMLHttpRequest include:


Google maps Windows live's virtual earth Mapquests dynamic map interface Facebook
263 JavaScript Copyright IBM Corporation 2009

IBM Global Business Services

XMLHttpRequest (XHR): (Continued)

Different browsers use different methods to create the XMLHttpRequest object

IE uses an ActiveXObject Can use JavaScript try/catch to handle the creation of the XMLHttpRequest object
JavaScript

other browsers uses the built-in JavaScript object XMLHttpRequest

264

Copyright IBM Corporation 2009

IBM Global Business Services

Example of HTML
<body> <script type="text/javascript"> // JavaScript function here ... </script> <form name="myForm"> <h3>Simple Ajax Test</h3> <p>Input string: <input type="text" onkeyup="ajaxFunction(this.value);" name="username" /> </p> <p>Backwards: <em><span id="myElem"></span></em></p> </form></body>
265 JavaScript Copyright IBM Corporation 2009

IBM Global Business Services

The whole JavaScript function


<body> <script type="text/javascript"> function ajaxFunction(myStr) { var xmlHttp; try { ... } // end of try section xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById('myElem').innerHTML = xmlHttp.responseText; } } $path = "http://www.cs.kent.ac.uk/people/staff/amlf/"; xmlHttp.open("GET", $path + "reverse.php?str=" + myStr, true); xmlHttp.send(null); } </script></body>
266 JavaScript Copyright IBM Corporation 2009

IBM Global Business Services

Revision
Cookies are small text files that sit on your hard disk. Cookies are created when you visit websites that use Cookies to store information that they need (or prefer). Websites often use Cookies to personalize the user experience - such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits. Despite the many misconceptions about Cookies being malicious, they are quite harmless. Cookies can't give your personal details to other websites, or transmit a virus or anything like that. A cookie can only be read by the server that created it. Websites normally use Cookies to make its users' lives easier, not harder.

267

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Reading material (AJAX)


Overview
http://en.wikipedia.org/wiki/AJAX http://java.sun.com/developer/technicalArticles/J2EE/AJAX/index.html?cid=59754

Examples
http://www.sitepoint.com/article/remote-scripting-ajax.html http://www.mousewhisperer.co.uk/ajax_page.html http://www.clearnova.com/ajax/ http://www.webpasties.com/xmlHttpRequest/

AJAX based Applications


http://www.ajaxreview.com/ http://ajaxblog.com/

268

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Questions

269

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

Summary

At the completion of this course, we see that you are now able to: Put in your own words an introduction to JavaScript Explain JavaScript operators and expressions Define flow control and functions Identify objects and arrays Describe document object model Describe Cookies Explain session outline

270

JavaScript

Copyright IBM Corporation 2009

IBM Global Business Services

THANK YOU

271

JavaScript

Copyright IBM Corporation 2009

Anda mungkin juga menyukai