Sunteți pe pagina 1din 118

Building Forms in JavaScript

11
and Event Handling
1
Key Points

• Form Object

• Event Handler

• Form Validation

Learning Objectives
The student will be able to

• Describe the Window Object and apply the windows methods and
its properties

• Describe the event Handling and apply the different types of event
handling

• Describe the Form Objects and apply the different types of form
objects with its event, method and properties in real world
application
Building Forms in JavaScript and Event Handling

Concepts at a Glance
1. What is a Form Object?

Form object is a Browser object of JavaScript used to access an HTML form

2. What do you mean by events?

Events are the actions that occur on a Web page, usually as a result of an action performed
by the user

3. What are the types of event handler?

An interactive event handler

A Non-interactive event handler

4. What is form Validation?

Form validation is the process of checking that a form has been filled in correctly before
it is processed

Chapter Content
Form Object
Form Object is a Browser object of JavaScript used to access an HTML form. The Form
object is actually a property of Document object that is uniquely created by the browser for
each form present in a document. The properties and methods associated with Form Object
are used to access the form fields, attributes and controls associated with forms.

Forms allow us to prompt a user for input using elements such as radio buttons, checkboxes
and selection lists. Data gathered in this manner can then be posted to a server for processing.
A form is created by enclosing HTML controls and other elements within <form></form>
tags.

Basic Types for Form buildings


Types

Button Object Radio Object

CheckBox Object Reset Object

File Upload Object Select Object

171 ITFS
JavaScript

Hidden Object Submit Object

Option Object Text Object

Password Object Text Area

Button Object
The JavaScript Button object is a property of the Form object. A Button object is created
with every instance of an HTML <INPUT> tag (with a ‘type’ value set as ‘button’) on a form.
The type may be one of “button”, “submit”, or “reset”. The name is the name we want to
call the button. The onclick and associated function is optional. The clickFunction is run
when the button is clicked and must exist, usually in the header.

Syntax:

<INPUT TYPE=”button” NAME=”myButton” VALUE=”Press This”


onClick=”clickFunction”>

Example:

Program Highlights
Button.html

The program to demonstrate the application of Button object

Key focus: Button

Concepts used: variables and Button object

<html>

<body>

<form name=buttonform>

<INPUT TYPE=”button” VALUE=”Press This” Type=Button>

</form>

<script language=”javascript”>

var buttonobject= document.buttonform.button1;

</script>

ITFS 172
Building Forms in JavaScript and Event Handling

</body>

</html>

Output:

Output Screen

Properties of a Button

• form - The form object that includes the button.

• name - The name of the button.

• type - The type of element which is button, submit, or reset.

• value - The value of the button that appears on the button.

Methods

The following are the list of DOM (Dynamic Object Model) methods that can be used to do
dynamic changes like button click using JavaScript.

DOM Method Description

click() Used to dynamically make a button click

blur() Takes the focus away from the button.

focus() Gives the focus to the Button

Event Handler

The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .

Event Handler Description Example

onMouseOver This is invoked when a <input type=button


mouse is moved over the onMouseOver=”output()”>
button

173 ITFS
JavaScript

onMouseOut This is invoked when a <input type=button


mouse is moved over and onMouseOut=”output()”>
then out of the button

onMouseDown This is invoked when a <input type=button


mouse is pressed down on onMouseDown=”output()”>
the button

onMouseUp This is invoked when a <input type=button


mouse is pressed down on onMouseUp=”output()”>
the button and released

onClick “onClick” function is <input type=button


invoked when a mouse click onClick=”output()”>
is done on the button

onBlur Executes some code when <input type=button


the button loses focus onBlur=”output()”>
using tab

onFocus Executes some code when <input type=button


the button gets focus onFocus=”output()”>
using tab

Checkbox Object
The JavaScript Checkbox object is a property of the form object. A Checkbox object is
created with every instance of an HTML <INPUT> tag (with a ‘type’ value set as ‘checkbox’)
on a Form. These objects are then stored in the Elements array of the parent form and
accessed using either the name defined within the HTML tag or an integer (with ‘0’ being
the first element defined, in source order, in the specified Form).

Syntax:

<INPUT TYPE=”checkbox” NAME=”Item1" VALUE=”1" CHECKED


onClick=”clickFunction”>

ITFS 174
Building Forms in JavaScript and Event Handling

Example:

Program Highlights
checkbox.html

A program to demonstrate application of checkbox object

Key focus: checkbox

Concepts used: variables

<html>

<body>

<form name=testform>

<input name=cb1 value=test type=checkbox>

</form>

<script language=”javascript”>

var cbobject= document.testform.cb1;

</script>

</body>

<html>

Output:

Output Screen

Properties

• checked - The value is true when the button is checked.

• defaultChecked - Is true if the button is checked by default.

• form - The form object that includes the checkbox button.

175 ITFS
JavaScript
• name - The name of the checkbox button.

• type - The type of element which is checkbox.

• value - The value of the button.

Methods

The following are the list of DOM (Dynamic Object Model) methods that can be used to do
dynamic changes like dynamic check box selection, using JavaScript.

DOM Method Description

click() To dynamically make a checkbox checked

blur() To dynamically blur the check box

focus() To dynamically get focus on the check box

Event Handler

The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .

Event Handler Description Example

onMouseOver This is invoked when a mouse is <input type=checkbox


moved over the checkbox onMouseOver=”output()”>

onMouseDown This is invoked when a mouse is <input type=checkbox


pressed down on the checkbox onMouseDown=”output()”>

onMouseUp This is invoked when a mouse is <input type=checkbox


pressed down on the checkbox onMouseUp=”output()”>
and released

onClick onClick is invoked when a mouse <input type=checkbox


click is done on the checkbox onClick=”output()”>

onBlur Executes some code when the <input type=checkbox


check box loses focus using tab onBlur=”output()”>

onFocus Executes some code when the <input type=checkbox


check box gets the focus onFocus=”output()”>
using tab

ITFS 176
Building Forms in JavaScript and Event Handling

Radio Object
The Radio object represents a single radio button, created by an HTML <INPUT> tag of
type “radio”, with a radio button we can give just the one choice to select from a list of
options in web page .

It is for this reason that all radio buttons in a group must have the same value for the NAME
attribute. The Radio object is a form element and as such must be included within a <FORM>
tag. The JavaScript runtime engine creates a Radio object for each individual radio button
on the form. Hence share the same NAME attribute.

Syntax:

<FORM>

<INPUT TYPE=”radio” NAME=”timeofDay” VALUE=”Morning” CHECKED

onClick=”clickFunction”>Morning

<INPUT TYPE=”radio” NAME=”timeofDay” VALUE=”Afternoon”

onClick=”clickFunction”>Afternoon

<INPUT TYPE=”radio” NAME=”timeofDay” VALUE=”Evening”

onClick=”clickFunction”>Evening

</FORM>

Example:

Program Highlights
Radio.html

A program to create Radio button objects

Key focus: Radio button

Concepts used: Varibles, Functions

<html>

<head>

<script type=”text/javascript”>

function check(language)

177 ITFS
JavaScript
{

document.getElementById(“answer”).value=language;

</script>

</head>

<body>

<p>What’s your favorite programming language?</p>

<form>

<input type=”radio” name=”language” onclick=”check(this.value)” value=”VB”>Visual


Basics<br />

<input type=”radio” name=”language” onclick=”check(this.value)”


value=”VB.net”>Dotnet<br />

<input type=”radio” name=”language” onclick=”check(this.value)” value=”Java”>Java<br


/>

<input type=”radio” name=”language” onclick=”check(this.value)” value=”c#”>C sharp <br


/>

<br />

Your favorite language is: <input type=”text” id=”answer” size=”20">

</form>

</body>

</html>

Output:

Output Screen

ITFS 178
Building Forms in JavaScript and Event Handling

Properties

• checked - The value is true when the button is checked.

• defaultChecked - Is true if the button is checked by default.

• form - The form object that includes the radio button.

• name - The name of the radio button.

• type - The type of element which is radio.

• value - The value of the button.

Methods

The following are the list of DOM (Dynamic Object Model) methods that can be used to do
dynamic changes like dynamic Radio Button selection using JavaScript.

DOM Method Description

click() Used to dynamically make a Radio Button checked

blur() Used to dynamically make the Radio Button blur

focus() Used to dynamically get focus on the Radio Button

Event Handler

The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes.

Event Handler Description Example

onMouseOver This is invoked when a mouse <input type=radio


is moved over the Radio onMouseOver=”output()”>
Button

onMouseDown This is invoked when a mouse is <input type=radio


pressed down on the Radio onMouseDown=”output()”>
Button

onMouseUp This is invoked when a mouse <input type=radio


is pressed down on the Radio onMouseUp=”output()”>
Button and released

179 ITFS
JavaScript

onClick This is invoked when a mouse <input type=radio


click is done on the Radio Button onClick=”output()”>

onBlur Executes some code when the <input type=radio


Radio Button loses focus onBlur=”output()”>
using tab

onFocus Executes some code when the <input type=radio


Radio Button gets the focus onFocus=”output()”>
using tab

Text Field Object


The JavaScript Text Object is a property of the form object. A Text object provides a field on
a form in which the user can enter data and is created with every instance of an HTML
<INPUT> tag with the type attribute set to “text”.

Syntax:

<INPUT TYPE=”TEXT” NAME=”firstname”>

Example:

Program Highlights
Textfield.html

A program to demonstrate the application of text field in a webpage

Key focus: text field

Concepts used: variables, Functions

<html>

<head>

<script type=”text/javascript”>

function check()

var myTextField = document.getElementById(‘mycontent’);

if(myTextField.value != “”)

alert(“You entered: “ + myTextField.value)

ITFS 180
Building Forms in JavaScript and Event Handling

else

alert(“Would you please enter some text?”)

</script>

</head>

<body>

<input type=’text’ id=’mycontent’ />

<input type=’button’ onclick=’check()’ value=’sign up’ />

</body>

</html>

Output:

Output Screen

Properties

• defaultValue - The text default value of the text field.

• form - The form that contains the text object.

• name - The name of the text field.

• type - Type is “text”.

• value - The text that is entered and appears in the text field. It is sent to the server when
the form is submitted.

181 ITFS
JavaScript
Methods

The following are the list of DOM (Dynamic Object Model) methods that can be used to do
dynamic changes like dynamic text field selection using JavaScript.

DOM Method Description

select() To dynamically select a TextField

blur() To dynamically make the Text Field blur

focus() This method helps us to get focus on the TextField

Event Handler

The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes.

Event Handler Description Example

onMouseOver onMouseOver is invoked when a <input type=text


mouse is moved over the TextField onMouseOver=”output()”>

onMouseDown onMouseDown is invoked when <input type=radio


a mouse is pressed down inside onMouseDown=”output()”>
the TextField

onMouseUp onMouseUp is invoked when a <input type=text


mouse is pressed down inside the onMouseUp=”output()”>
TextField and released

onClick onClick is invoked when a mouse <input type=text


click is done inside the InputBox onClick=”output()”>

onBlur onBlur Executes some code when <input type=text


the TextField loses focus using tab onBlur=”output()”>

onFocus onFocus Executes some code <input type=text


when the TextField gets the focus onFocus=”output()”>
using tab

ITFS 182
Building Forms in JavaScript and Event Handling

TextArea Object
The JavaScript TextArea Object is a property of the form object. A TextArea object provides
a multi-line field in which the user can enter data and is created with every instance of an
HTML <TEXTAREA> tag on a form.

Syntax:

<TEXTAREA NAME=”” ROWS=”10" COLS=”40" onBlur=”blurHandlerRouting”>

Displayed Text

</TEXTAREA>

Example:

Program Highlights
Textarea.html

A program to demonstrate the application of TextArea in webpage

Key focus: text area


<html>
<body>
<textarea id=”myText” rows=”3" cols=”15">
</textarea>
<br>
<button onclick=”myText.cols=100;”>INCREASE width </button>
<button onclick=”myText.rows=20;”>INCREASE height </button>
</body>
</html>

Output:

Output Screen

183 ITFS
JavaScript
Properties

• defaultValue - The text string value that is initially displayed.

• form - The form object that includes the TextArea object.

• name - The name of the TextArea object. This object should always have a name.

• type - The type of element which is TextArea.

• value - Used to set or get TextArea value

• rows - The number of rows displayed in the TextArea.

• cols - The number of columns displayed in the TextArea.

• Wrap may be set to one of the following values:

• OFF - Default, lines are not wrapped.

• PHYSICAL - Wrap lines and place new line characters where the line wraps.

• VIRTUAL - Wrap lines on the screen, but receive them as one line.

Methods:

The following are the list of DOM (Dynamic Object Model) methods that can be used to do
dynamic changes like dynamic text area selection using JavaScript.

DOM Method Description

select() Used to dynamically select a content in TextArea

blur() Used to dynamically make the TextArea blur

focus() Used to dynamically get focus on the TextArea

Event Handler

The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .

Event Handler Description Example

onMouseOver onMouseOver is invoked when a <textarea name=textn


mouse is moved over the TextArea onMouseOver=”output()”>
testing text area </textarea>

ITFS 184
Building Forms in JavaScript and Event Handling

onMouseDown onMouseDown is invoked when a <textarea name=textn


mouse is pressed down inside the onMouseDown=”output()”>
TextArea testing text area </textarea>

onMouseUp onMouseUp is invoked when a <textarea name=textn


mouse is pressed down inside the onMouseUp=”output()”>
TextArea and released testing text area </textarea>

onClick onClick is invoked when a mouse <textarea name=textn


click is done inside the TextArea onClick=”output()”> testing
text area </textarea>

onFocus onFocus Executes some code <textarea name=textn


when the TextArea gets the focus onFocus=”output()”>
using tab testing text area </textarea>

Select Object
The Select object represents a selection list in a Form object. As such, it must be declared
inside <FORM> tags. The Option object(s) appear inside it as in the following code:

Syntax:

<SELECT NAME=”state” SIZE=0>

<OPTION VALUE=”0">

<OPTION VALUE=”1">AL

<OPTION VALUE=”2">AK

<OPTION VALUE=”3">AR

</SELECT>

Example :

Program Highlights
Selectfield.html

A program to demonstrate the application of select field in webpage

Key focus: select field

185 ITFS
JavaScript
<HTML>

<HEAD>

</HEAD>

<BODY>

<FORM name = “test”>

<SELECT NAME=”mySelect” >

<OPTION SELECTED VALUE=”1">first choice

<OPTION VALUE=”2">second choice

<OPTION VALUE=”3">third choice

<OPTION VALUE=”4">fourth choice

</SELECT>

<P>

</FORM>

</BODY>

</HTML>

Output:

Output Screen

Properties

• form - The form that contains the selection list.

• length - The number of elements contained in the options array.

• name - The name of the selection list.

• options - An array each of which identifies an options that may be selected in the list.

ITFS 186
Building Forms in JavaScript and Event Handling

• selectedIndex - Specifies the current selected Option within the select list

• type - Type is “select”.

Methods:

The following are the list of DOM (Dynamic Object Model) methods that can be used to do
dynamic changes in select option using JavaScript.

DOM Method Description

blur() Used to dynamically make the select object blur

focus() Used to dynamically get focus on the select object

Event Handler

The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .

Event Handler Description

onMouseOver onMouseOver is invoked when a mouse is moved over the Select


Box

onMouseDown onMouseDown is invoked when a mouse is pressed down on the


Select Option

onMouseUp onMouseUp is invoked when a mouse is pressed down on the


select Option and released

onChange onChange is invoked when a new option is selected

onBlur onBlur Executes some code when the SelectBox loses focus using
tab

onFocus onFocus Executes some code when the SelectBox gets the focus
using tab

JavaScript Reset Object


The JavaScript Reset object is a property of the form object.

Syntax:

<INPUT TYPE=”RESET” VALUE=”Clear”>

187 ITFS
JavaScript
Example:

Program Highlights
Reset.html

A program to demonstrate the application of reset object in webpage

Key focus: Reset Object

Concepts used: Text box

<HTML>

<BODY>

<FORM name = “ReaderInfo”>

<INPUT NAME=”Your Name:” VALUE=”type your name here”MAXLENGTH=”50"


SIZE=50>

<P>

<INPUT NAME=”EmailAdd” VALUE=”type email address here”MAXLENGTH=”40"


SIZE=40>

<P>

<INPUT type=”reset” onClick=”alert (‘Returned all fields to default values’)”>

</FORM>

</BODY>

</HTML>

Output:

Output Screen

ITFS 188
Building Forms in JavaScript and Event Handling

Properties

• form - The form that contains the button.

• name - The name of the reset button.

• type - The type is “reset”.

• value - The text that appears on the button.

Methods

DOM Method Description

blur() Removes the input focus from the button.

focus() Gives the input focus to the button.

click() Performs the same as though the user clicked the button.

Events Handler

Event Handler Description

onBlur onBlur Executes some code when the Reset Button loses focus
using tab

onFocus onFocus Executes some code when the Reset Button gets the focus
using tab

onClick onClick is invoked when a mouse click is done on the Reset Button

JavaScript Hidden Objects


A hidden object is a form element and must be defined within a <FORM> tag. It is totally
invisible on the Web page — and visible only in the document source view. We use a hidden
field when we want to pass private information, such as the name of the form, reader’s
responses to form fields.

Syntax:

<INPUT TYPE=”Hidden” VALUE=””>

189 ITFS
JavaScript
Example:

Program Highlights
hidden.html

A program to demonstrate the application of Hidden object in webpage

Key focus: hidden object

Concepts used: variables, functions and Hidden object

<HTML>

<HEAD>

<SCRIPT Language = “JavaScript”>

function stampForm()

rightnow = new Date()

document.myForm.timestamp.value = rightnow

function showSecret()

msg = “hidden field contains”

msg += document.myForm.timestamp.value

alert (msg)

</SCRIPT>

</HEAD>

<BODY onLoad = “stampForm()”>

<FORM name = “myForm”>

<INPUT type = “hidden” name = “timestamp”>

<INPUT type = “button” value = “Try Me” onClick = “showSecret()”>

ITFS 190
Building Forms in JavaScript and Event Handling

</FORM>

</BODY>

</HTML>

Output:

Output Screen

Properties

• form - The form object that includes the hidden object.

• name - The name of the hidden object.

• type - The type of element which is hidden.

• value - The value of the hidden object.

JavaScript Password Object


The JavaScript Password object is a property of the form object.

Syntax:

<INPUT TYPE=”password” NAME=”passwordName” VALUE=”contents”


SIZE=”integer” >

Example:

Program Highlights
Password.html

A program to demonstrate the application of password object in webpage

Key focus: password object

191 ITFS
JavaScript
<html>

<body>

<INPUT TYPE=”password” NAME=”thisPwd” SIZE=10 MAXLENGTH=15 VALUE=””>

</body>

</html>

Output:

Output Screen

Properties

• defaultValue - The default value of the password object.

• form- The form object that includes the password object.

• name - The name of the password object.

• type - The type of element which is password.

• value - The value of the password object.

Methods

DOM Method Description

blur() Takes the focus away from the password object.

focus() Gives the focus to the password object.

Select() The contents of the password object are selected.

Event Handeler

Event Handler Description

onBlur onBlur Executes some code when the password button loses focus
using tab

ITFS 192
Building Forms in JavaScript and Event Handling

onFocus onFocus Executes some code when the password Button gets the
focus using tab

JavaScript Option Object


The JavaScript Option object is a property of the form object. It is one of the several options
in a selection box. It appears inside a select box as follows:

Syntax:

<SELECT NAME=”state” SIZE=0>

<OPTION VALUE=”0">

<OPTION VALUE=”1">AL

<OPTION VALUE=”2">AK

<OPTION VALUE=”3">AR

</SELECT>

Example:

Program Highlights
option object.html

A program to demonstrate the application of option field in webpage

Key focus: Option object

<HTML>

<HEAD>

</HEAD>

<BODY>

<FORM name = “test”>

<SELECT NAME=”mySelect” >

<OPTION SELECTED VALUE=”1">Javascript

<OPTION VALUE=”2">HTML

<OPTION VALUE=”3">VBScript

193 ITFS
JavaScript
</SELECT>

<P>

</FORM>

</BODY>

</HTML>

Output:

Output Screen

Properties

• defaultSelected - Is a Boolean value determining whether the option is selected by


default.

• index - The index of the option in the list of selections.

• selected - Determines if the option is currently selected. This Boolean value is read/
write.

• text - The text used to describe the option.

• value - The value sent to the server if the option was selected.

• prototype - Used to create additional properties.

Methods

DOM Method Description

blur() Takes the focus away from the option.

focus() Gives the focus to the option.

ITFS 194
Building Forms in JavaScript and Event Handling

Event Handler

Event Handler Description

onBlur onBlur Executes some code when the option object loses focus
using tab

onFocus onFocus Executes some code when the option object gets the
focus using tab

onchange onChange is invoked when a new option is selected

JavaScript File Upload Objects


The JavaScript FileUpload Object is a property of the form object which allows users to
provide a local file as part of their form input thereby allowing for indirect file upload. It can
be implement using a form as follows:

Syntax:

<FORM>

<INPUT TYPE=”file” NAME=”elementName”>

</FORM>

Example:

Program Highlights
file upload object.html

A program to demonstrate the application of file upload object in webpage

Key focus: file upload object

<html>

<body>

<FORM>

<INPUT TYPE=”file” NAME=”elementName”>

</FORM>

<body>

195 ITFS
JavaScript
</html>

Output:

Output Screen

Properties

• form - The form object that includes the file upload object.

• name - The name of the file upload element which is not the same as the file name.

• type - The type of element which is file.

• value - Can be used to specify the initial value of the file name to be uploaded.

Methods

DOM Method Description

blur() Takes the focus away from the file upload object.

focus() Gives the focus to the to the file upload object

Event Handler

Event Handler Description

onBlur onBlur Executes some code when the option object loses focus
using tab

onFocus onFocus Executes some code when the option Button gets the
focus using tab

onchange onChange is invoked when a new option is selected

JavaScript Submit Object


The JavaScript Submit Object is a property of the form object.

ITFS 196
Building Forms in JavaScript and Event Handling

Syntax:

<INPUT TYPE=”submit” NAME=”cmdSubmit” VALUE=”Submit”>

Example:

Program Highlights
submit object.html

A program to create submit object in webpage

Key focus: submit object

Concept Used : Button,textarea,textbox

<HTML>

<BODY>

<FONT SIZE=6 COLOR=#0000FF>Ask Alan</FONT><BR>

<FORM METHOD=POST ACTION=”xyz.html”>

<P>

Question:<TEXTAREA NAME=”01Question” ROWS=5 COLS=80></TEXTAREA>

<P>

My e-mail address is: <INPUT NAME=”02ReturnAdd” VALUE=”” MAXLENGTH=”70"


SIZE=70>

<P>

<INPUT TYPE=”SUBMIT” VALUE=”Submit”>

<INPUT TYPE=”RESET”>

<BR>

</FORM>

</BODY></HTML>

197 ITFS
JavaScript
Output:

Output Screen

Properties

• form - The form that contains the submit button.

• name - The name of the submit button.

• type - Type is “submit”.

• value - The text that will appear on the button.

Methods

DOM Method Description

click() Used to dynamically make a button click

blur() Used to dynamically make the button blur

focus() Used to dynamically get focus on the button

Events Handler

Event Handler Description Example

onClick “onClick” function is invoked <input type=button


when a mouse click is done on the onClick=”output()”>
button

onBlur Executes some code when the <input type=button


button loses focus using tab onBlur=”output()”>

onFocus Executes some code when the <input type=button


button gets focus using tab onFocus=”output()”>

ITFS 198
Building Forms in JavaScript and Event Handling

Example:

Program Highlights
test.html

A program to show the use properties of textbox,password,submit button,reset button


webpage

Key focus: textbox,password,submit button,reset button objects

Concepts used: textbox,password,submit button,reset button objects

<html>

<head>

<title>Form Object Test</title>

</head>

<body>

<h2 align=”center”>Test Form</h2>

<form action=”http://www.riiit.com”

method=”post” name=”testform” id=”testform”

onreset=”return confirm(‘Are you sure?’);”

onsubmit=”alert(‘you sending data’); return true;”>

<label>Name:

<input type=”text” id=”field1” name=”field1” size=”20”

value=”” /></label>

<br />

<label>Password:

<input type=”password” id=”field2” name=”field2”

size=”8” maxlength=”8” /></label>

<br />

<input type=”reset” value=”reset”/>

199 ITFS
JavaScript
<input type=”submit” value=”submit” />

</form>

<hr />

</body>

</html>

Output:

Output Screen

Example:

Program Highlights
test2.html

A program to show how to use properties ,methods and events of textbox, password,
submit button, reset button webpage (rephrase)

Key focus: textbox,password,submit button,reset button objects

Concept Used: textbox,password,submit button,reset button objects


<html>
<head>
<title>Textfield Test</title>
</head>
<body>
<h2 align=”center”>Test Form</h2>
<form name=”testform” id=”testform”

ITFS 200
Building Forms in JavaScript and Event Handling

action=”http://www.riiit.com” method=”get”>
<label>Text Field 1: <input type=”text” name=”text1" id=”text1" size=”20"
value=”Original Value” /></label>
<br />
<label>Text Field 2: <input type=”text” name=”text2" id=”text2" size=”20"
maxlength=”20" /></label>
<br />
<input type=”button” value=”Check Value”
onclick=”alert(document.testform.text1.value);” />
<input type=”button” value=”Set Value”
onclick=”document.testform.text1.value=document.testform.text2.value;” />
<input type=”button” value=”Focus”
onclick=”document.testform.text1.focus();” />
<input type=”button” value=”Blur”
onclick=”document.testform.text1.blur();” />
<input type=”button” value=”Select”
onclick=”document.testform.text1.select();” />
</form>
<hr />
</body>
</html>

Output:

Output Screen

201 ITFS
JavaScript

Program Highlights
test3.html

A program to demonstrate properties of checkbox radio button in webpage

Key focus: checkbox, radio button objects

Concept Used: checkbox, radio button objects, and Functions

<html>

<head>

<title>radio/checkbox test</title>

<script type=”text/javascript”>

function showradiovalue(radiogroup)

var numradios = radiogroup.length;

for (var i = 0; i < numradios; i++)

if (radiogroup[i].checked)

alert(‘radio ‘+i+’ with value of ‘+radiogroup[i].value);

</script>

</head>

<body>

<h2 align=”center”>Test Form</h2>

<form name=”testform” id=”testform” action=”#” method=”get”>

<em>Checkbox: </em>

<input type=”checkbox” name=”check1" id=”check1" value=”testvalue” />

<br /><br />

<em>radio buttons: </em>

yes:

ITFS 202
Building Forms in JavaScript and Event Handling

<input type=”radio” name=”radiogroup1" id=”radio1" value=”yes” />

no:

<input type=”radio” name=”radiogroup1" id=”radio2" value=”no” />

maybe:

<input type=”radio” name=”radiogroup1" id=”radio3" value=”maybe” />

<br /><br />

<input type=”button” value=”Click checkbox”

onclick=”document.testform.check1.click();” />

<input type=”button” value=”Click radio”

onclick=”document.testform.radiogroup1[0].click();” />

<input type=”button” value=”Checkbox state”

onclick=”alert(‘checked?’+document.testform.check1.checked);” />

<input type=”button” value=”Radio state”

onclick=”showradiovalue(document.testform.radiogroup1);” />

</form>

<hr />

</body>

</html>

Output:

Output screen

203 ITFS
JavaScript
Event Handler
When users visit our website, they do things like click on things, hover over things etc.
These are examples of what JavaScript calls events. Events are actions that occur on the Web
page, usually as a result of something the user does. Using JavaScript, we can respond to an
event using Event Handlers.

An event handler executes a segment of a code based on certain events occurring within the
application, such as onLoad or onClick. JavaScript event handlers can be divided into two
parts:

• Interactive event handlers

• Non-interactive event handlers.

An interactive event handler is the one that depends on user interaction with the form or
the document. For example, onMouseOver is an interactive event handler because it depends
on the user’s action with the mouse.

A Non-interactive event handler is the one, which doesn’t depend on user. For example of a
non-interactive event handler is onLoad, as it automatically executes JavaScript code without
the need for user interaction. In JavaScript we have many event handlers

List Of Event Handler with event handles


Event handler Applies to: Event Handles

onAbort Image The loading of the image is cancelled.

onBlur Button, Checkbox, The object in question loses focus (e.g. by


FileUpload, Layer, clicking outside it or pressing the TAB key).
Password, Radio,
Reset, Select, Submit,
Text, TextArea,
Window

onChange FileUpload, Select, The data in the form element is changed


Text, TextArea by the user.

onClick Button, Document, The object is clicked on.


Checkbox, Link,
Radio, Reset, Submit

ITFS 204
Building Forms in JavaScript and Event Handling

onDblClick Document, Link The object is double-clicked on.

onError Image, Window A JavaScript error occurs.

onFocus Button, Checkbox, The object in question gains focus (e.g. by


FileUpload, Layer, clicking on it or pressing the TAB key).
Password, Radio,
Reset, Select,
Submit, Text,
TextArea, Window

onKeyDown Document, Image, The user presses a key.


Link, TextArea

onKeyPress Document, Image, The user presses or holds down a key.


Link, TextArea

onKeyUp Document, Image, The user releases a key.


Link, TextArea

onLoad Image, Window The whole page has finished loading.

onMouseDown Button, Document, The user presses a mouse button.


Link

onMouseOut Image, Link The user moves the mouse away from the
object.

onMouseOver Image, Link The user moves the mouse over the object.

onMouseUp Button, Document, The user releases a mouse button.


Link

onReset Form The user clicks the form’s Reset button.

onResize Window The user resizes the browser window or


frame.

onSelect Text, Textarea The user selects text within the field.

onSubmit Form The user clicks the form’s Submit button.

onUnload Window The user closes the page.

205 ITFS
JavaScript
onAbort
The onAbort event handler executes the specified JavaScript code or function on the
occurrence of an abort event. This is used when a user cancels the loading of an image by
either clicking stop in the browser or clicking another link before the image has loaded.

The onAbort event handler uses the following Event object properties.

type - this property indicates the type of event.

target - this property indicates the object to which the event was originally sent.

Syntax:

onAbort = myJavaScriptCode

Example:

Program Highlights
onAbort.html

A program to demonstrate onAbort event

Key focus: onAbort event

Concepts used: functions and onAbort event

<html>

<head>

<script type=”text/javascript”>

function abortImage()

alert(“Error: Loading of the image was aborted”);

</script>

</head>

<body>

<img src=”C:\\Documents and Settings\\Ravi\\My Documents\\Before salary.jpg”

ITFS 206
Building Forms in JavaScript and Event Handling

onabort=”abortImage()”>

</body>

</html>

Output:

Output Screen

onBlur
The onBlur event handler executes the specified JavaScript code or function on the
occurrence of a blur event. This is will happen when a window, frame or form element loses
focus. This can be caused by the user clicking outside of the current window, frame or form
element, by using the TAB key to cycle through the various elements on screen, or clicking
outside windows ,frame or form .

Syntax:

onBlur = myJavaScriptCode

Example:

Program Highlights
onblur.html

The program that is written is demonstrating the onblur event

Key focus: onblur event

Concepts used which is already learnt: functions

207 ITFS
JavaScript
<html>

<head>

<script type=”text/javascript” language=”JavaScript”>

function addCheck() {

alert(“Please check your email details are correct before submitting”)

</script>

</head>

<body>

Enter email address <INPUT TYPE=”text” VALUE=”” NAME=”userEmail”


onBlur=addCheck()>

</body>

<html>

Output:

Output Screen

onChange
onChange is commonly used to validate form fields when a form field’s value has been
altered by the user. The event handler onChange is triggered when the user changes the
field then clicks outside the field or uses the TAB key (i.e. the object loses focus).

ITFS 208
Building Forms in JavaScript and Event Handling

Syntax:

OnChange = myJavaScriptCode

Example:

Program Highlights
onchange.html

A program to demonstrate onchange event

Key focus: onchange event

Concepts used: functions,formobjects

<html>

<head>

<script type=”text/javascript”>

document.getElementById(“test”).onchange()

</script>

<head>

<body>

<input type=”text” onchange=”alert(‘i was clicked’)” id=”test”>

</body>

</html>

Output:

Output Screen

209 ITFS
JavaScript
onClick
The onClick handler is executed when the user clicks with the mouse on the object. Because
we can use it on many types of objects, from buttons through to checkboxes through to
links, it’s a great way to create interactive Web pages based on JavaScript.

Syntax:

onClick = myJavaScriptCode

Example:

Program Highlights
onclick.html

A program to demonstrate onclick event

Key focus: onclick event

Concepts used: functions, form objects

<html>

<body>

<a href=”#” onclick=”alert(‘Thanks!’)”>Click Me!</a>

</body>

</html>

Output:

Output Screen

ITFS 210
Building Forms in JavaScript and Event Handling

onDblClick
The onDblClick event handler executes the specified JavaScript code or function on the
occurance of a double click event.

Syntax:

onDblClick = myJavaScriptCode

Example:

Program Highlights
onDblclick.html

A program to demonstrate dblClick event

Key focus: onDblClick event

Concepts used: functions, form objects

<html>

<body>

<button ondblclick=”document.write(‘Hello World!’)”></button>

</body>

</html>

Output:

Output screen

onError
The onError event handler executes the specified JavaScript code or function on the
occurance of an error event. This is when an image or document causes an error during
loading. The distinction must be made between a browser error, when the user types in a
non-existant URL, for example, and a JavaScript runtime or syntax error. This event handler
will only be triggered by a JavaScript error, not a browser error.

211 ITFS
JavaScript
Syntax:

onError = myJavaScriptCode

Example :

Program Highlights
onerror.html

A program to demonstrate onError event

Key focus: onError event

Concepts used which is already learnt: functions

<html>

<body>

<img src=”image.gif”

onerror=”alert(‘The image could not be loaded.’)”>

<p>In this example we refer to an image that does not exist, therefore we will get the alert
box.</p>

</body>

</html>

Output:

Output Screen

ITFS 212
Building Forms in JavaScript and Event Handling

onFocus
onFocus is executed whenever the specified object gains focus. This usually happens when
the user clicks on the object with the mouse button, or moves to the object using the TAB
key. onFocus can be used on most form elements.

Syntax:

onFocus = myJavaScriptCode

Example:

Program Highlights
onFocus.html

A program to demonstrate onfocus event

Key focus: onfocus event

Concepts used which is already learnt: functions

<html>

<body>

<input type=”text” name=”email_address”

size=”40" value=”Please enter your email address”

onfocus=”this.value=’’”/>

</body>

</html>

Output:

Output Screen

Note: text box contains the prompt “Please enter your email address” that is cleared once the
text box has focus.

213 ITFS
JavaScript
OnKeyPress
The onKeyPress event handler executes the specified JavaScript code or function on the
occurrence of a KeyPress event. A KeyPress event occurs when the user presses or holds
down a key.

Syntax:

onKeyPress = myJavaScriptCode

Example :

Program Highlights
onkeypress.html

A program to demonstrate the onkeypress event

Key focus: onkeypress event

Concepts used: functions, form objects

<html>

<body onkeypress = “show_key(event.which)”>

<form action=”” method=”POST” id=”myForm” >

<input type=”text” name=”myText” onKeyPress=”changeVal()”>

<script type=”text/javascript” language=”JavaScript”>

s1 = new String(myForm.myText.value)

function changeVal()

s1 = “You pressed key”

myForm.myText.value = s1.toUpperCase()

</script>

</form>

</body>

ITFS 214
Building Forms in JavaScript and Event Handling

<html>

Output:

Output Screen

In this program whatever the key we press from the keyboard is converted to upper case
and displayed in text

onKeyDown

The onKeyDown event handler executes the specified JavaScript code or function on the
occurrence of a KeyDown event. A KeyDown event occurs when the user presses a key.

Syntax:

onKeyDown = myJavaScriptCode

Example:

Program Highlights
onKeydown.html

A program to demonstrate the onKeyDown events

Key focus: onKeyDown event

Concepts used: functions,form objects

<html>

<body>

<form action=”” method=”POST” id=”myForm”>

<input type=”text” name=”myText” onKeyDown=”changeVal()”>

<script type=”text/javascript” language=”JavaScript”>

s1 = new String(myForm.myText.value)

function changeVal()

215 ITFS
JavaScript
{

s1 = “You pressed a key”

myForm.myText.value = s1.toUpperCase()

</script>

</form>

</body>

</html>

Output:

Output Screen

onKeyUp
The onKeyUp event handler executes the specified JavaScript code or function on the
occurrence of a KeyUp event. A KeyUp event occurs when the user releases a key from its
depressed position.

Syntax:

onKeyUP = myJavaScriptCode

Example:

Program Highlights
onkeyup.html

A program to demonstrate the onKeyUp event application

Key focus: onKeyUp event

Concepts used: functions

ITFS 216
Building Forms in JavaScript and Event Handling

<html>

<body>

<form action=”” method=”POST” id=”myForm”>

<input type=”text” name=”myText” onKeyUp=”changeVal()”>

<script type=”text/javascript” language=”JavaScript”>

s1 = new String(myForm.myText.value)

function changeVal()

s1 = “You pressed a key”

myForm.myText.value = s1.toUpperCase()

</script>

</form>

</body>

</html>

Output:

Output screen

onload
The onLoad event handler is triggered when the page has finished loading. Common uses
of onLoad include the dreaded pop-up advertisement windows, and to start other actions
such as animations or timers once the whole page has finished loading.

Syntax:

onload = myJavaScriptCode

217 ITFS
JavaScript
Example:

Program Highlights
onload.html

The program to demonstrate onload event

Key focus: onload event

Concepts used which is already learnt: functions

<html>

<body onload = “alert(‘Thanks for visiting my page!’)”>

My Page

</body>

</html>

Output:

Output screen

onMouseOut, onMouseOver
The classic use of these two event handlers is for JavaScript rollover images (images, such as
buttons, that change when you move your mouse over them)

Syntax:

onMouseOut = myJavaScriptCode

onMouseOver= myJavaScriptCode

ITFS 218
Building Forms in JavaScript and Event Handling

Example:

Program Highlights
onMouseOut, onMouseOver.html

A program to demonstrate onMouseOut, onMouseOver events

Key focus: onMouseOut, onMouseOver

Concepts used: functions

<html>

<body>

<form>

<input type=”text” id=”status” value=”Not over the link”/>

<br>

<a href=”” onmouseover=”document.getElementById(‘status’).value=’Over the link’”

onmouseout=”document.getElementById(‘status’).value=’Not over the link’”>Move the


mouse over me!</a>

</form>

</body>

</html>

Output:

Output Screen

onMouseDown
The onMouseDown event handler is used to execute specified Javascript code whenever
the user presses a mouse button.

219 ITFS
JavaScript
Syntax:

onMouseDown = myJavaScriptCode

Example:

Program Highlights
onMousedown .html

The program to demonstrate on MouseDown event

Key focus: onMouseDown

Concepts used: functions

<html>

<body>

<img src=”C:\Documents and Settings\User\Desktop\New Folder\compman.gif”


onMouseDown=”alert(‘You clicked the picture!’)” width=”234" height=”91">

<p>Click the picture</p>

</body>

</html>

Output:

Output Screen

onMouseUp

The onMouseUp event handler is used to execute specified JavaScript code whenever the
user releases the mouse button.

ITFS 220
Building Forms in JavaScript and Event Handling

Syntax:

onMouseUp = myJavaScriptCode

Example:

Program Highlights
onMouseup .html

A program to demonstrate onmouseup event

Key focus: onMouseup

Concepts used: functions

<html>

<body>

<img src=”C:\Documents and Settings\User\Desktop\New Folder\compman.gif”


onMouseUp=”alert(‘You clicked the picture!’)” width=”234" height=”91">

<p>Click the picture</p>

</body>

</html>

Output:

Output Screen

onSubmit
The onSubmit event handler, which works only with the Form object, is commonly used
to validate the form before it’s sent to the server.

221 ITFS
JavaScript
Syntax:

onSubmit=myjavascript code

Example:

Program Highlights
onSubmit .html

A program to demonstrate onSubmit event.

Key focus: onSubmit

Concepts used: functions

<html>

<body>

<form onsubmit=”return confirm(‘Are You Sure?’)” action=””>

<input type=”submit” name=”submit” value=”Submit”/>

</form>

</body>

</html>

Output:

Output Screen

ITFS 222
Building Forms in JavaScript and Event Handling

onReset
The onReset event handler is used to execute specified JavaScript code whenever the user
resets a form by clicking a Reset button

Syntax:

onReset = myJavaScriptCode

Example:

Program Highlights
onreset .html

A program to demonstrate the onreset events works

Key focus: onreset

Concepts used: functions


<html>
<body>
<form onreset=”alert(‘The form will be reset’)”>
Firstname: <input type=”text” name=”fname” />
<br />
Lastname: <input type=”text” name=”lname” />
<br /><br />
<input type=”reset” value=”Reset”>
</form>
</body>
</html>

Output:

Output Screen

223 ITFS
JavaScript
onSelect (HC)

The onSelect event handler is used to execute specified JavaScript code whenever the user
selects some of the text within a text or textarea field.

Syntax:

onSelect = myJavaScriptCode

Example:

Program Highlights
onselect .html

The program to demonstrate the onSelect

Key focus: onselect

Concepts used: functions


<html>
<body>
<form>
Select text: <input type=”text” value=”Hello world!”
onselect=”alert(‘You have selected some of the text.’)”>
<br /><br />
</form>
</body>
</html>

Output:

Output screen

ITFS 224
Building Forms in JavaScript and Event Handling

onUnload
The onUnload event handler is used to run a function or JavaScript code whenever the
user exits a document. The onUnload event handler is used within either the <BODY> or
the <FRAMESET> tag,

Syntax:

onUnload = myJavaScriptCode

Example:

Program Highlights
onUnload .html

The program to demonstrate the onUnload event.

Key focus: onUnload

Concepts used: functions

<html>

<body onunload=”alert(‘The onunload event was triggered’)”>

<p>Close the page to trigger the onunload event.</p>

</body>

</html>

Output:

Output Screen

225 ITFS
JavaScript
Form Validation
One of the most useful things that we can do in JavaScript is to check and make sure that a
form is filled in properly. Checking form contents before submission saves server processor
cycles as well as the user’s time waiting for the network round trip (server to browser) to see
if the proper data has been entered into the form. JavaScript can be used to validate input
data in HTML forms before sending off the content to a server.

Form validation is the process of checking that a form has been filled in correctly before it is
processed

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

Let’s build a simple form with a validation script. The form will include one text field called
“Your Name”, and a Submit button called “Send Details”.

Lets create validation script in such way that it will ensure that the user should enter their
name before the form is sent to the server.

Example:

Program Highlights
form validation .html

The program that is written demonstrating the form validation .

Key focus: form validation

Concepts used: functions, form objects

ITFS 226
Building Forms in JavaScript and Event Handling

<html>

<head>

<title>A Simple Form with JavaScript Validation</title>

<script type=”text/javascript”>

function validate_form ( )

valid = true;

if ( document.contact_form.contact_name.value == “” )

alert ( “Please fill in the ‘Your Name’ box.” );

valid = false;

return valid;

</script>

</head>

<body bgcolor=”#FFFFFF”>

<form name=”contact_form” method=”post”

action=”xyz.html” onSubmit=”return validate_form ( );”>

<h1>Please Type Your Name</h1>

<p>Your Name: <input type=”text” name=”contact_name”></p>

<p><input type=”submit” name=”send” value=”Send Details”></p>

</form>

</body>

</html>

The first part is the form tag:

227 ITFS
JavaScript
<form name=”contact_form” method=”post” action=”xyz.html” onSubmit=”return
validate_form ( );”>

The form is given a name of “contact_form”. So that it is easy to reference the form by
name from our JavaScript validation function.

The form uses the post method to send the data off to xyz.html

Finally, the form tag includes an onsubmit attribute to call our JavaScript validation function,
validate_form(), when the “Send Details” button is pressed. The return allows us to return
the value true or false from our function to the browser, where true means send the value of
the form to the specified page, and false means, don’t send the values “. This means that we
can prevent the form from being sent if the user hasn’t filled it in properly.

The rest of the form prompts the user to enter their name into a form field called
contact_name, and adds a “Send Details” submit button:

<h1>Please Enter Your Name</h1>

<p>Your Name: <input type=”text” name=”contact_name”></p>

<p><input type=”submit” name=”send” value=”Send Details”></p>

</form>

let’s take a look at the JavaScript form validation function that does the actual work of
checking our form.

The form validation function, “validate_form()”, is embedded in the head tag of the page:

<script type=”text/javascript”>

function validate_form ( )

valid = true;

if ( document.contact_form.contact_name.value == “” )

alert ( “Please fill in the ‘Your Name’ box.” );

valid = false;

ITFS 228
Building Forms in JavaScript and Event Handling

return valid;

The first line tells the browser that we are writing JavaScript code,

Next we start our validate_form() function, then set a variable called “ valid “ to the value
true. We use this variable to keep track of whether user has been filled the form correctly or
not. If one of our checks fails, we’ll set valid to false so that the form won’t send the values

The next 5 lines check the value of our contact_name field to make sure it has been filled in:

if ( document.contact_form.contact_name.value == “” )

alert ( “Please fill in the ‘Your Name’ box.” );

valid = false;

If the field is empty, the user is warned with an alert box, and the variable valid is set to false.

Next, we return the value of our valid variable to the onSubmit event handler (described
above). If the value is true then the form will be sent to the specified page, if it’s false then
the form will not be sent:

Finally, we finish our validate_form() function with a closing brace, and end our HTML
comment and script element.

Now lets work with complex form by adding some more component to previous form

229 ITFS
JavaScript
<html>

<head>

<title>A Simpler Form with JavaScript Validation</title>

<script type=”text/javascript”>

function validate_form ( )

valid = true;

if ( document.contact_form.contact_name.value == “” )

alert ( “Please fill in the ‘Your Name’ box.” );

valid = false;

if ( ( document.contact_form.gender[0].checked == false ) && (


document.contact_form.gender[1].checked == false ) )

alert ( “Please choose your Gender: Male or Female” );

valid = false;

if ( document.contact_form.age.selectedIndex == 0 )

alert ( “Please select your Age.” );

valid = false;

if ( document.contact_form.terms.checked == false )

alert ( “Please check the Terms & Conditions box.” );

ITFS 230
Building Forms in JavaScript and Event Handling

valid = false;

return valid;

</script>

</head>

<body bgcolor=”#FFFFFF”>

<form name=”contact_form” method=”post” action=”xyz.html” onSubmit=”return


validate_form ( );”>

<h1>Please Enter Your Details Below</h1>

<p>Your Name: <input type=”text” name=”contact_name”></p>

<p>Your Gender: <input type=”radio” name=”gender” value=”Male”> Male

<input type=”radio” name=”gender” value=”Female”> Female</p>

<p>Your Age:

<select name=”age”>

<option value=””>Please Select an Option:</option>

<option value=”0-18 years”>0-18 years</option>

<option value=”18-30 years”>18-30 years</option>

<option value=”30-45 years”>30-45 years</option>

<option value=”45-60 years”>45-60 years</option>

<option value=”60+ years”>60+ years</option>

</select>

<p>Do you agree to the Terms and Conditions?

<input type=”checkbox” name=”terms” value=”Yes”> Yes

<p><input type=”submit” name=”send” value=”Send Details”></p>

</form>

231 ITFS
JavaScript
</body>

</html>

In our previous example, we have a form called contact_form and a function called
validate_form(). In addition to the previous text field, the form has radio buttons, a drop-
down list and a checkbox.

The validate_form() function now has 3 extra checks, one for each of our new fields.

After the contact_name text box has been checked, the genders radio buttons are validated.

if ( ( document.contact_form.gender[0].checked == false )

&& ( document.contact_form.gender[1].checked == false ) )

alert ( “Please choose your Gender: Male or Female” );

valid = false;

This code checks to see whether either of the radio buttons (“Male” or “Female”) have been
clicked. If neither have been clicked (checked == false), the user is alerted and valid is set to
false.

Next the “Age” drop-down list is checked to see if the user has selected an option.

In the form, we named the first option in the drop-down list “Please Select an Option”.

if ( document.contact_form.age.selectedIndex == 0 )

alert ( “Please select your Age.” );

valid = false;

NOTE: that the values for selectedIndex start at zero (for the first option).

This code will check which option was selected when the user submitted the form. If the
first option is selected, the user is alerted and valid sets to false

Finally, the “Terms and Conditions” checkbox is validated. We want to the user to agree to

ITFS 232
Building Forms in JavaScript and Event Handling

our imaginary Terms and Conditions before they send the form, so we’ll check to make
sure they’ve clicked the checkbox

if ( document.contact_form.terms.checked == false )

alert ( “Please check the Terms & Conditions box.” );

valid = false;

Because we set our valid variable to false in any one of the above cases, if one or more of our
checks fail, the form will not be sent to the specified pages or server. If the user has not
completed more than one field, then they will see an alert box appear for each field that is
missing.

Now we know how to write a form validation script that can handle multiple form fields,
including text boxes, radio buttons, drop-down lists and check boxes.

Summary
• Form object is a Browser object of JavaScript used to access an HTML form

• Events are actions that occur on the Web page, usually as a result of something the user
does

• An interactive event handler is the one that depends on user interaction with the form
or the document

• A Non-interactive event handler is the one, which doesn’t depend on user.

• Form validation is the process of checking that a form has been filled in correctly before
it is processed

233 ITFS
Windows Object 12
1
Key Points

• Introduction

• Window Object

• Window Object Methods

• Properties of windows
Objects

Learning Objectives
The student will be able to

• Describe the Window Object and apply the windows methods and its
properties in real world application
Windows Object

Concepts at a Glance
1. What is the need for window Object?

We need window object because it allows developers to perform tasks such as opening
and closing browser windows, displaying alert and prompt dialogs and specifying an
action to take place in specified period of time.

2. What is the method used to resize the window?

The resizeBy Method is used to resize the window. It moves the bottom right corner
of the window by the specified horizontal and vertical number of pixels while leaving
the top left corner anchored to its original co-ordinates.

3. Which property in Window object is used to get windows name ?

The name property is used to return or set a window’s name.

Chapter Content
Introduction
JavaScript’s Window object represents the browser window or, potentially, the frame that a
document is displayed in. Until now we have focused on the internals and syntax of JavaScript.
Now we will begin to make things happen on the screen (which, after all, is one of the main
purposes of JavaScript).

Window Object
The window object allows developers to perform tasks such as opening and closing browser
windows, displaying alert and prompt dialogs and specifying an action to take place in a
specified period of time.

The window object is the top-level object of the object hierarchy. So whenever an object
method or property is referenced in a script we can call without the object name and dot
prefix for example

Instead of writing like this

window.alert();

we can write in this way (only for window object)

• alert()

235 ITFS
JavaScript
Window Object Methods
Methods Description

alert(msg) Displays an Alert dialog box with the desired message


and OK button.

blur() Removes focus from the window in question,


sending the window to the background on the user’s
desktop.

clearInterval(ID) Clears the timer set using ID=setInterval().

close() Closes a window.

confirm(msg) Displays a Confirm dialog box with the specified


message and OK and Cancel buttons.

focus() Sets focus to the window, bringing it to the forefront


on the desktop.

moveBy(dx, dy) Moves a window by the specified amount in pixels.

moveTo(x, y) Moves a window to the specified coordinate values,


in pixels.

open(URL, [name], [features], Opens a new browser window. “Name” argument


[replace]) specifies a name that we can use in the target
attribute of your <a> tag. “Features” allow us to
show/hide various aspects of the window interface.
“Replace” is a Boolean argument that denotes
whether the URL loaded into the new window
should add to the window’s history list. A value of
true causes URL to not be added.

print() Prints the contents of the window or frame.

prompt(msg, [input]) Displays a Prompt dialog box with a message.


Optional “input” argument allows us to specify the
default input (response) that gets entered into the
dialog box. Set “input” to “” to create a blank input
field.

ITFS 236
Windows Object

resizeBy(dx, dy) Resizes a window by the specified amount in pixels.

resizeTo(x y) Resizes a window to the specified pixel values.

scrollBy(dx, dy) Scrolls a window by the specified amount in pixels.

scrollTo(x, y) Scrolls a window to the specified pixel values.

setInterval(“func”, interval, Calls the specified “func” (or a JavaScript statement)


[args]) repeatedly per the “interval” interval, in milliseconds.
“func” must be surrounded in quotations, as if it
was a string. Use the optional “args” to pass any
number of arguments to the function.

setTimeout(“func”, interval) Calls the specified “func” (or a JavaScript statement)


once after “interval” has elapsed, in milliseconds (ie:
1000=after 1 second). “func” must be surrounded
in quotations, as if it was a string.

Alert Method
The alert() method is used to display an alert box with a specified message and an OK
button.

Syntax:

alert(message)

Example :

Program Highlights
alert.html

A program to demonstrate the application of alert method

Key focus: Alert method

Concepts used: functions, Button Object

<html>

<head>

<script type=”text/javascript”>

237 ITFS
JavaScript
function display_alert()

alert(“I am an javascript alert box!!”)

</script>

</head>

<body>

<input type=”button” onclick=”display_alert()” value=”Display alert box” />

</body>

</html>

Output:

Output Screen

blur Method
The blur() method removes focus from the current window.

Syntax :

window.blur()

ITFS 238
Windows Object

Example:

Program Highlights
Blur.html

A program to demonstrate the application of blur method

Key focus: blur method

Concepts used: function

<html>

<body>

<script type=”text/javascript”>

myWindow=window.open(‘’,’’,’width=500,height=250')

myWindow.blur()

myWindow.document.write(“This is ‘another window’”)

</script>

</body>

</html>

Output:

Output Screen

239 ITFS
JavaScript
ClearInterval Method
The clearInterval() method cancels a timeout that is set with the setInterval() method.The
ID value returned by setInterval() is used as the parameter for the clearInterval() method.

Syntax:

clearInterval(id_of_setinterval)

Example:

Program Highlights
ClearInterval.html

A program to demonstrate the application of clearInterval method

Key focus: ClearInterval method

Concepts used: function

<html>

<body>

<input type=”text” id=”clock” size=”35" />

<script type=”text/javascript”>

var int=self.setInterval(“clock()”,5000);

function clock()

var t=new Date();

document.getElementById(“clock”).value=t;

</script>

<button onclick=”int=window.clearInterval(int)”>Stop interval</button>

</body>

</html>

ITFS 240
Windows Object

Output:

Output Screen

In this program clock will be triggered on every 5 seconds due to setInterval method and to
stop the triggering we should click stop button which calls clearInterval method

close Method
This method is used to close a specified window. If no window reference is supplied, the
close() method will close the current active window. Note that this method will only close
windows created using the open() method.

Syntax: window.close( )

Example:

Program Highlights
close.html

A program to demonstrate the application of Close method

Key focus: Close method

Concepts used: function

<html>

<head>

<title>JavaScript Window Close Example </title>

</head>

<SCRIPT language=”JavaScript”>

function popuponclick()

241 ITFS
JavaScript
my_window = window.open(“”,

“mywindow”,”status=1,width=350,height=150");

my_window.document.write(‘<H1>The Popup Window</H1>’);

function closepopup()

if(false == my_window.closed)

my_window.close ();

else

alert(‘Window already closed!’);

</SCRIPT>

<body>

<P>

<A href=”javascript: popuponclick()”>Open Popup Window</A>

</P>

<P>

<A href=”javascript: closepopup()”>Close the Popup Window</A>

</P>

</body>

</html>

ITFS 242
Windows Object

Output:

Output screen

Confirm
This method brings up a dialog box that prompts the user to select either ‘OK’ or ‘Cancel’,
the first returning true and the latter, false.

Syntax :

Window.confirm()

Example

Program Highlights
confirm.html

A program to demonstrate the application of confirm method

Key focus: confirm method

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

function disp_confirm()

var r=confirm(“Press a button”)

if (r==true)

document.write(“You pressed OK!”)

243 ITFS
JavaScript
}

else

document.write(“You pressed Cancel!”)

</script>

</head>

<body>

<input type=”button” onclick=”disp_confirm()”

value=”Display a confirm box” />

</body>

</html>

Output:

Output Screen

createPopup()
The createPopup() method is used to create a pop-up window.

Syntax:

Window.createPopup()

ITFS 244
Windows Object

Example:

Program Highlights
Createpopup.html

A program to demonstrate the application of createpopup method

Key focus: createpopup method

Concepts used: function


<html>
<body>
<script language=”JavaScript”>
var popup = window.createPopup();// creating variable of popupwindow
popup.document.body.innerHTML = ‘hi popup screen !’;/* When we are using popup
object, it sure that we are creating another window that has its own document collection.
So, simply setting the body’s innerHTML property will allow developers to place almost
anything they’d like into the popup*/
popup.document.body.style.backgroundColor = ‘yellow’;//giving background color
</script>
<input type=”button”
onClick=”location.href=’http://www.riiit.com’;”
onmouseover=”popup.show(100, 100, 200, 100, document.body);”
onmouseout=”popup.hide();”
value=”Navigate to Another Site”>
</body>
</html>

Output:

Output Screen
245 ITFS
JavaScript
Focus Method
This method is used to give focus to the specified window. This is useful for bringing windows
to the top of any others on the screen.

Syntax: window.focus( )

Example:

Program Highlights
Focus.html

A program to demonstrate the application of Focus method

Key focus: Focus method

Concepts used: function

<html>

<body>

<script type=”text/javascript”>

myWindow=window.open(‘’,’’,’width=200,height=100')

myWindow.document.write(“This is ‘myWindow’”)

myWindow.focus()

</script>

</body>

</html>

Output:

Output Screen

ITFS 246
Windows Object

moveBy Method
This method is used to move the window a specified number of pixels in relation to its
current co-ordinates.

Syntax: window.moveBy(horizPixels, vertPixels)

Example:

Program Highlights
moveby.html

A program to demonstrate the application of moveBy method

Key focus: moveBy method

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

function moveWin()

myWindow.moveBy(50,50)

</script>

</head>

<body>

<script type=”text/javascript”>

myWindow=window.open(‘’,’’,’width=200,height=100')

myWindow.document.write(“This is ‘myWindow’”)

</script>

<input type=”button” value=”Move ‘myWindow’”

onclick=”moveWin()” />

247 ITFS
JavaScript
</body>

</html>

Output:

Output Screen

window.moveTo()
The moveTo() method moves the window to the specified location.

Syntax: window.moveTo(numX, numY)

The numX represents the x-coordinate, while the numY represents the y-coordinate.

Example:

Program Highlights
window.moveTo.html

A program to demonstrate the application of moveTo method works.

Key focus: moveTo method

Concepts used: function

<html>

<head>

</head>

<script language=”JavaScript”>

function moveWin(form)

ITFS 248
Windows Object

var myX = form.X.value;

var myY = form.Y.value;

window.moveTo(myX, myY);

</script>

<body>

<form>

<b>X-Coordinate:</b>

<input type=TEXT name=”X”><br>

<b>Y-Coordinate:</b>

<input type=TEXT name=”Y”><br>

<input type=BUTTON value=”Move Window” onClick=”moveWin(this.form)”></td>

</form>

</body>

</html>

Output:

Output Screen

Open Method
This method is used to open a new browser window.

Syntax:

window.open()

249 ITFS
JavaScript
Example:

Program Highlights
open.html

A program to demonstrate the application of open method

Key focus: open method

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

function open_win()

window.open(“http://www.riiit.com”);

</script>

</head>

<body>

<form>

<input type=button value=”Open Window” onclick=”open_win()”>

</form>

</body>

</html>

ITFS 250
Windows Object

Output:

Output Screen

Note that, when using this method with event handlers, we must use the syntax
window.open() as opposed to just open(). Calling just open() will, create a new document
(equivalent to document.open()) not a window.

print Method
This method is used to print the contents of the specified window.

Syntax: window.print( )

Example:

Program Highlights
Print.html

A program to demonstrate the application of Print method

Key focus: Print method

Concepts used: function

251 ITFS
JavaScript
<html>

<head>

<script type=”text/javascript”>

function printpage()

window.print();

</script>

</head>

<body>

<input type=”button” value=”Print this page” onclick=”printpage()” />

</body>

</html>

Output:

Output Screen

ITFS 252
Windows Object

prompt Method
This method displays a dialog box prompting the user for some input. The optional
defaultInput parameter specifies the text that initially appears in the input field.

Syntax: window.prompt(message[, defaultInput])

Example:

Program Highlights
Prompt .html

A program to demonstrate the application of Prompt method

Key focus : Prompt method

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

function greeting() {

y = (prompt(“Please enter your name.”, “Type name here”))

document.write(“Hello “ + y)

</script>

</head>

<body onload=greeting()>

</body>

</html>

253 ITFS
JavaScript
Output:

Output Screen

resizeBy Method
This method is used to resize the window. It moves the bottom right corner of the window
by the specified horizontal and vertical number of pixels while leaving the top left corner
anchored to its original co-ordinates.

Syntax: window.resizeBy(horizPixels, vertPixels)

Example:

Program Highlights
resizeBy .html

A program to demonstrate the application of resizeBy method

Key focus : resizeBy method

Concepts used: function


<html>
<head>
<script type=”text/javascript”>
function resizeWindow()
{
top.resizeBy(-100,-100);
}
</script>

ITFS 254
Windows Object

</head>
<body>
<form>
<input type=”button” onclick=”resizeWindow()” value=”Resize window”>
</form>
<p><b>Note:</b> We have used the <b>top</b> element instead of the <b>window</b>
element, to represent the top frame. If you do not use frames, use the <b>window</b>
element instead.</p>
</body>
</html>
Output:

Output Screen

resizeTo Method
This method is used to resize a window to the dimensions supplied with the Width and
Height (both integers, in pixels) parameters.

Syntax: window.resizeTo(Width, Height)

Example:

Program Highlights
resizeto .html

A program to demonstrate the application of resizeTo method

Key focus : resizeTo method

Concepts used: function

255 ITFS
JavaScript
<html>

<head>

<script type=”text/javascript”>

function resizeWindow()

window.resizeTo(500,300)

</script>

</head>

<body>

<input type=”button” onclick=”resizeWindow()”

value=”Resize window”>

</body>

</html>

Output:

Output Screen

scrollTo Method
This method scrolls the contents of a window, the specified co-ordinate becoming the top
left corner of the viewable area.

Syntax: window.scrollTo(xPosition, yPosition)

ITFS 256
Windows Object

Example:

Program Highlights
scroll to .html

A program to demonstrate the application of scrollTo method

Key focus : scrollTo method

Concepts used: function


<html>
<head>
<script type=”text/javascript”>
function scrollWindow()
{
window.scrollTo(100,500);
}
</script>
</head>
<body>
<input type=”button” onclick=”scrollWindow()” value=”Scroll” />
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<p> first paragraph</p>
<br />
<br />

257 ITFS
JavaScript
<br />
<br />
<br />
<br />
<br />
<br />
<p> second paragraph</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<p> third paragraph</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<p>fouth paragraph</p>
<br />
<br />
<br />
<br />
<br />

ITFS 258
Windows Object

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

Output:

Before

After clicking the button

Output Screen

259 ITFS
JavaScript
setInterval Method
This method is used to call a function or evaluate an expression at specified intervals, in
milliseconds. This will continue until the clearInterval method is called or the window is
closed.

The following example uses the setInterval method to call the clock() function which updates
the time in a text box.

Syntax: window.setInterval(expression/function, milliseconds)

Example:

Program Highlights
setInterval .html

A program to demonstrate the application of setInterval method

Key focus : setInterval method

Concepts used: function

<html>

<body>

<form name=”myForm” action=”” method=”POST”>

<input name=”myClock” type=”Text”>

<script language=javascript>

self.setInterval(‘clock()’, 5000)// clock will be triggerd for every 5 seconds

setInterval(“alert(‘hi!’);”, 5000);//alert box will be displayed for every 5 seconds

function clock() {

time=new Date()

document.myForm.myClock.value=time

</script>

</form>

ITFS 260
Windows Object

</body>

</html>

Output:

Output Screen

setTimeout Method
This method is used to call a function or evaluate an expression after a specified number of
milliseconds.

Syntax: window.setTimeout(expression/function, milliseconds)

Example:

Program Highlights
setTimeout .html

A program to demonstrate the application of setTimeout method

Key focus : setTimeout method

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

function displayAlert()

alert(“The GURU sez hi!”)

261 ITFS
JavaScript
}

</script>

</head>

<body>

<form>

Click on the button.

<br>

After 5 seconds, an alert will appear.

<br>

<input type=”button” onclick=”setTimeout(‘displayAlert()’,5000)” value=”Click Me”>

</form>

</body>

</html>

Output:

Output screen

Properties Of windows Objects

closed Property
This property is used to return a Boolean value that determines if a window has been closed,
the value returned is true.

Syntax: window.closed

ITFS 262
Windows Object

Example:

Program Highlights
closed .html

A program to demonstrate the application of setTimeout property

Key focus : closed property

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

function ifClosed()

document.write(“‘myWindow’ has been closed!”)

function ifNotClosed()

document.write(“‘myWindow’ has not been closed!”)

function checkWin()

if (myWindow.closed)

ifClosed()

else

ifNotClosed()

</script>

263 ITFS
JavaScript
</head>

<body>

<script type=”text/javascript”>

myWindow=window.open(‘’,’’,’width=200,height=100')

myWindow.document.write(“This is ‘myWindow’”)

</script>

<input type=”button” value=”Has ‘myWindow’ been closed?”

onclick=”checkWin()”>

</body>

</html>

Output:

Output Screen

defaultStatus Property
This property is used to define the default message displayed in a window’s status bar.

Syntax: window.defaultStatus(“message”)

Example:

Program Highlights
closed .html

A program to demonstrate the application of closed property

Key focus : closed property

Concepts used which is already learnt: function

ITFS 264
Windows Object

<html>

<body>

<script type=”text/javascript”>

window.defaultStatus=”This is the default text in the status bar!!”

</script>

<p>check out the statusbar.</p>

</body>

</html>

Output:

Output Screen

history Property
This property’s value is the window’s History object, containing details of the URL’s visited
from within that window.

Syntax: window.history

Example:

Program Highlights
history .html

A program to demonstrate the application of history property

Key focus: history property

Concepts used: function

<html>

<body>

265 ITFS
JavaScript
<script type=”text/javascript”>

alert(window.history.length);

</script>

it will display number of pages the User visited

</body>

</html>

Output:

Output Screen

name Property
This property is used to return or set a window’s name.

Syntax: window.name

Example:

Program Highlights
name .html

A program to demonstrate the application of name property

Key focus : name property

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

ITFS 266
Windows Object

function checkWin()

document.write(“The new window’s name is: “ + myWindow.name);

</script>

</head>

<body>

<script type=”text/javascript”>

myWindow=window.open(‘’,’MyName’,’width=200,height=100');

myWindow.document.write(“This is ‘myWindow’”);

</script>

<input type=”button” value=”What’s the name of ‘myWindow’?” onclick=”checkWin()”>

</body>

</html>

Output:

Output Screen

outerheight / outerwidth Property


These properties determine the dimensions, in pixels, of the outside boundary, including all
interface elements, of a window.

267 ITFS
JavaScript
Syntax: window.outerheight

Syntax: window.outerwidth

Example:

Program Highlights
outerheight/outerwidth .html

A program to demonstrate the application of outerheight/outerwidth property

Key focus: outerheight/outerwidth property

Concepts used: function

<html>

<body>

<script type=”text/javascript”>

myWindow=window.open(‘’,’’);

myWindow.outerheight=”100";

myWindow.outerwidth=”100";

myWindow.document.write(“This is ‘myWindow’”);

myWindow.focus();

</script>

</body>

</html>

ITFS 268
Windows Object

Output:

Output Screen

parent Property
This property is a reference to the window or frame that contains the calling child frame.

Syntax: window.parent

personalbar Property
This property relates to the browser’s personal bar (or directories bar). The personalbar
property has its own property, visible, that defaults to true (visible) and can be set to false
(hidden).

Syntax: window.personalbar[.visible = false]

scrollbars Property
This property relates to the browser’s scrollbars (vertical and horizontal). The scrollbars
property has its own property, visible, that defaults to true (visible) and can be set to false
(hidden).

Syntax: window.scrollbars[.visible = false]

269 ITFS
JavaScript
status Property
This property, which can be set at any time, is used to define the transient message displayed
in a window’s status bar such as the text displayed when we onMouseOver a link or anchor.

Syntax: window.status(= “message”)

statusbar Property
This property relates to the browser’s status bar. The statusbar property has its own property,
visible, that defaults to true (visible) and can be set to false (hidden).

Syntax: window.statusbar[.visible = false]

toolbar Property
This property sets or returns a Boolean value that defines whether the browser’s tool bar is
visible or not. The default is true (visible). False means hidden. It can only be set before the
window is opened and you must have UniversalBrowserWrite privilege.

Syntax: window.toolbar[.visible = false]

top Property
This property is a reference (or synonym) for the topmost browser window.

Syntax: top.property or method

Example:

Program Highlights
Top .html

A program to demonstrate the application of Top property

Key focus: Top property

Concepts used: function

<html>

<head>

<script type=”text/javascript”>

function resizeWindow()

ITFS 270
Windows Object

top.resizeBy(-100,-50);

</script>

</head>

<body>

<form>

<input type=”button” onclick=”resizeWindow()” value=”Resize window”>

</form>

<p><b>Note:</b> We have used the <b>top</b> element instead of the <b>window</b>


element, to represent the top frame. If we do not use frames, use the <b>window</b> element
instead.</p>

</body>

</html>

Output:

Output Screen

Summary
• JavaScript’s Window object represents the browser window or, potentially, the frame
that a document is displayed

• The window object allows developers to perform tasks such as opening and closing
browser windows, displaying alert and prompt dialogs.

271 ITFS
Cookies 13
1
Key Points

• Introduction

• Cookies

• Setting Cookies

• Function to set a cookie

• Function to delete a cookie


• Function to retrieve a cookie

Learning Objectives
The student will be able to

• Describe cookies and apply the cookies concept in real world


application
Cookies

Concepts at a Glance
1. What are Cookies?

Cookies are pieces of information that are stored on our computer

2. Why we need Cookies

We need the cookies to retrieve the information of user-visited pages

Chapter Content
Introduction
Cookies were originally invented by Netscape to give ‘memory’ to web servers and browsers.
Since the HTTP (Hypertext Transport Protocol) cannot maintain user information, which
means that once the server has sent a page to a browser requesting it, it doesn’t remember
a thing about it. So if we come to the same web page a second, third, or millionth time, the
server once again considers it as the first time.

The server cannot remember if we identified our self when we want to access protected
pages, it cannot remember user preferences, it cannot remember anything. As soon as
personalization was invented, this became a major problem.

Cookies were invented to solve this problem. There are other ways to solve it, but cookies
are easy to maintain and very versatile.

Cookies
Cookies are pieces of information that are stored on our computer and contain data from
web sites that we have visited, including login information. Cookies allow us to store
particular information about a user and retrieve it every time they visit our pages. Each user
has their own unique set of cookies.

Cookies are typically used by web servers to perform functions such as tracking our visits
to websites, enabling us to log in to sites, and storing our shopping cart informations.

Setting Cookies
To set a cookie, we set the document.cookie property to a string containing the properties of
the cookie that we want to create:

273 ITFS
JavaScript
document.cookie = “name=value; expires=date; path=path;

domain=domain; secure”;

These properties are explained in the table below:

Property Description Example

name=value This sets both the cookie’s name username=matt


and its value.

expires=date This optional value sets the date expires=


that the cookie will expire on. The 18/06/2008 00:00:00
date should be in the format returned
by the toGMTString() method of the
Date object. If the expires value is not
given, the cookie will be destroyed
the moment the browser is closed.

path=path This optional value specifies a path path=/contents/


within the site to which the cookie
applies. Only documents in this path
will be able to retrieve the cookie.

domain=domain This optional value specifies a domain domain=riiit.com


within which the cookie applies.
Only websites in this domain will be
able to retrieve the cookie.

secure This optional flag indicates that the secure


browser should use SSL(Secure
Sockets Layer is the standard security
technology for establishing an
encrypted link between a web server
and a browser) when sending the
cookie to the server.
This flag is rarely used.

ITFS 274
Cookies

document.cookie = “username=Jackson;

expires=15/06/2008 00:00:00";

This code sets a cookie called username, with a value of “ Jackson “, that expires on Feb
15th, 2008 .

var cookie_date = new Date ( 2003, 01, 15 );

document.cookie = “username= Jackson;

expires=” + cookie_date.toGMTString();

This code does exactly the same thing as the previous example, but specifies the date using
the Date.toGMTString() method instead.

NOTE: The months in the Date object start from zero. Please refer Date Object methods

document.cookie = “logged_in=yes”;

This code sets a cookie called logged_in, with a value of “yes”. As the expires attribute has
not been set, the cookie will expire when the browser is closed down.

var cookie_date = new Date ( ); // current date & time

cookie_date.setTime ( cookie_date.getTime() - 1 );

document.cookie = “logged_in=;

expires=” + cookie_date.toGMTString();

This code sets the logged_in cookie to have an expiry date one second before the current
time - this instantly expires the cookie. A handy way to delete cookies!

we should be escaping our cookie values — encoding non-alphanumeric 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(“Jackson “)

+ “; expires=15/02/2003 00:00:00”;

Function to set a cookie


Setting cookies will be a lot easier if we can write a simple function to do stuff like escape
the cookie values and build the document.cookie string. Here’s one we prepared earlier!

275 ITFS
JavaScript
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )

var cookie_string = name + “=” + escape ( value );

if ( exp_y )

var expires = new Date ( exp_y, exp_m, exp_d );

cookie_string += “; expires=” + expires.toGMTString();

if ( path )

cookie_string += “; path=” + escape ( path );

if ( domain )

cookie_string += “; domain=” + escape ( domain );

if ( secure )

cookie_string += “; secure”;

document.cookie = cookie_string;

This function expects the cookie data to be passed to it as arguments; it then builds the
appropriate cookie string and sets the cookie.

For example, to use this function to set a cookie with no expiry date:

set_cookie ( “username”, “John “ );

To set a cookie with an expiry date of 17 Feb 2010:

set_cookie ( “username”, “John “, 2010, 02, 17 );

To set a secure cookie with an expiry date and a domain of user defined website, but with
no path:

set_cookie ( “username”, “John “, 2010, 02, 17, “”,

“riiit.com”, “secure” );

ITFS 276
Cookies

Function to delete a cookie


Now let us learn how to delete the cookies here we have created function to do this task .
This function will “delete” the cookie from the browser by setting the cookie’s expiry date
to one second in the past.

function delete_cookie ( cookie_name )

var cookie_date = new Date ( ); // current date & time

cookie_date.setTime ( cookie_date.getTime() - 1 );

document.cookie = cookie_name += “=; expires=” + cookie_date.toGMTString();

To use this function, just pass in the name of the cookie that we want to delete

Example:

delete_cookie ( “username” );

Function to retrieve a cookie


To retrieve all previously set cookies for the current document, we again use the
document.cookie property:

var x = document.cookie;

This returns a string comprising a list of name/value pairs, separated by semi-colons, for all
the cookies that are valid for the current document. For example:

“username=John “

here’s another useful function that parses the document.cookies string, and returns just the
cookie we’re interested in:

function get_cookie ( cookie_name )

var results = document.cookie.match ( ‘(^|;) ?’ + cookie_name + ‘=([^;]*)(;|$)’ ); //checking


for regular expression

if ( results )

277 ITFS
JavaScript
return ( unescape ( results[2] ) );

else

return null;

The function uses a regular expression to find the cookie name and value we’re interested
in, then returns the value portion of the match, passing it through the unescape() function
to convert any escaped characters back to normal. (If it doesn’t find the cookie, it returns a
null value.)

Using the function is easy. For example, to retrieve the value of the username cookie:

var x = get_cookie ( “username” );

A simple example

In this example, we’ve created a page that prompts us for our name the first time that we
visited, then stores the user name in a cookie and displays the user name in the page on
subsequent visits.

<html>

<head>

<title> Cookies Example</title>

</head>

<body>

<script language=”JavaScript”>

function set_cookie ( name, value, expires_year, expires_month, expires_day, path, domain,


secure )

var cookie_string = name + “=” + escape ( value );

if ( expires_year )

var expires = new Date ( expires_year, expires_month, expires_day );

ITFS 278
Cookies

cookie_string += “; expires=” + expires.toGMTString();

if ( path )

cookie_string += “; path=” + escape ( path );

if ( domain )

cookie_string += “; domain=” + escape ( domain );

if ( secure )

cookie_string += “; secure”;

document.cookie = cookie_string;

function delete_cookie ( cookie_name )

var cookie_date = new Date ( ); // current date & time

cookie_date.setTime ( cookie_date.getTime() - 1 );

document.cookie = cookie_name += “=; expires=” + cookie_date.toGMTString();

function get_cookie ( cookie_name )

var results = document.cookie.match ( ‘(^|;) ?’ + cookie_name + ‘=([^;]*)(;|$)’ );

if ( results )

return ( unescape ( results[2] ) );

else

return null;

if ( ! get_cookie ( “username” ) )

279 ITFS
JavaScript
var username = prompt ( “Please enter your name”, “” );

if ( username )

var current_date = new Date;

var cookie_year = current_date.getFullYear ( ) + 1;

var cookie_month = current_date.getMonth ( );

var cookie_day = current_date.getDate ( );

set_cookie ( “username”, username, cookie_year, cookie_month, cookie_day );

document.location.reload( );

else

var username = get_cookie ( “username” );

document.write ( “Hi “ + username + “, welcome to my website!” );

document.write ( “<br><a href=\”javascript:delete_cookie(‘username’);


document.location.reload( );\”>Forget about me!</a>” );

</script>

</body>

</html>

ITFS 280
Cookies

Output:

Output Screen

After Entering the Cookie Name

Again accessing the same page

Summary
• Cookies were invented by Netscape to give ‘memory’ to web servers and browsers.

• Cookies are pieces of information that are stored in our computer and contain
information of user visited website

281 ITFS
JavaScript

Workbook

Lab Activity : 1
Exercise :1

Concepts Covered : Variables , Operators,Input and Output Statements

Estimated Time : 20 Min

Problem statement: Create a web page to enter the two numbers. It should make a
comparison of the two numbers and display the greater of two numbers.

Exercise :2

Concepts Covered :Input and Output Statements and Control Statement

Estimated Time: 20 Min

Problem statement: Create a web page to enter customer account and credit balance (ATM)
using windows prompt , and evaluate the credit balance of that Customer , if the Customer
credit limit exceed it should display the message “credit limit Exceed”.

Exercise :3

Concepts Covered : Control Statement and Function

Estimated Time: 15 Min

Problem statement: Create an average function that can accept 3 different number, calculate
the average of the 3 numbers and return the computed average value.

Exercise: 4

Concepts Covered: Control Statement

Estimated Time: 20 Min

Problem statement: Generate multiplication table of 10,200,3000 and display in table format

ITFS 282
Workbook

Lab Activity : 2
Exercise :1

Concepts Covered : Arrays,Date,ime

Estimated Time : 20 Min

Problem statement: Create web page which should display System date,time and month
using arrays concept

Hint: Declare two array variables, one for month and another for day then with help date
object try to display

Exercise :2

Concepts Covered :Math

Estimated Time : 15 Min

Problem statement: Create a web page, which should display random Number between 1
to 52

Exercise :3

Concepts Covered :Math

Estimated Time : 15 Min

Problem statement: Create a web page which should display the basic mathematics constant
value of logerithm, Logerithm of 10, Logarithm of 2, base-10 logarithm of E, base-2logarithm
of E, PI, square root of 0.5, square root of 2

Exercise :4

Concepts Covered :Date and Time format

Estimated Time : 20 Min

Problem statement: Display the Time in Digital Format

Exercise: 5

Concepts Covered: Array

Estimated Time: 10 Min

Problem statement: Write a Program to Sort the names in ascending Order

283 ITFS
JavaScript

Exercise:6

Concepts Covered: Date methods and control statements

Estimated Time: 15 Min

Problem statement: Write a Programming script to check the System day is weeks day or
weekend

Lab Activity : 3
Exercise :1

Concepts Covered : Functions

Estimated Time : 20 Min

Problem statement: Create a web page which should display the greeting message if we
click button 1 and if we click button 2 it should display your company name, use function
and invoke functions through event handler

Exercise :2

Concepts Covered : Document Object

Estimated Time : 20 Min

Problem statement: Create a web page as shown below and write a program to change
background color properties through document object and its bgColor attributes.

ITFS 284
Workbook

Exercise: 3

Concepts Covered: Window Object

Estimated Time: 15 Min

Problem statement: create a webpage such that user should get prompt window to enter
their name and entered should be display in alert box with welcome note

Exercise: 4

Concepts Covered: Window Object

Estimated Time: 15 Min

Problem statement: Create a new window for displaying an animated graphics file.

Exercise 5

Concepts Covered: Form Object and Events

Estimated Time: 15 Min

Problem statement: Create the web page as shown below, which uses buttons, function to
call display the message by Onclick events, if the user click first button it should display
the "Hi how are you", if user click second button it should display the message "how is life
treating you" and if the user click third button it should display "see you take care".

Exercise 6

Concepts Covered: Form Validation

Estimated Time: 30 Min

Problem statement: Create the web page as shown below and verify user password

If user clicks submit button without entering the password field values the alert message

285 ITFS
JavaScript

should be displayed, displaying the message "you must enter the password". If the user
enters the wrong password in verify column it should display the message "verify the
password". If the user enters the right password and click the submit button it should go to
user defined page else it should be in same page.

Lab Activity : 4
Exercise :1

Concepts Covered : Functions

Estimated Time : 20 Min

Problem Statements: Create a check box in webpage with proper validation ie's whether
the checked box is checked or not, if it is checked it should display the message that checkbox
is checked else the checkbox is not checked .

Exercise :2

Concepts Covered : Functions

Estimated Time : 20 Min

Problem Statements: Create web page with Button and Demonstrate the event handler
like Onload,Onclickand OnmouseOver

Exercise :3

Concepts Covered : Functions

Estimated Time : 20 Min

Problem Statements: Create web page with Button and shows how to call functions through
the button controls and events.

ITFS 286
Workbook

Exercise :4

Concepts Covered : Functions

Estimated Time : 30 Min

Problem Statements: Create a web page, which helps the user to create cookies and display
his name on every visit to the web page and create the option to user to change the cookie
name

287 ITFS

S-ar putea să vă placă și