Documente Academic
Documente Profesional
Documente Cultură
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?
Events are the actions that occur on a Web page, usually as a result of an action performed
by the user
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.
171 ITFS
JavaScript
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:
Example:
Program Highlights
Button.html
<html>
<body>
<form name=buttonform>
</form>
<script language=”javascript”>
</script>
ITFS 172
Building Forms in JavaScript and Event Handling
</body>
</html>
Output:
Output Screen
Properties of a 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.
Event Handler
The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .
173 ITFS
JavaScript
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:
ITFS 174
Building Forms in JavaScript and Event Handling
Example:
Program Highlights
checkbox.html
<html>
<body>
<form name=testform>
</form>
<script language=”javascript”>
</script>
</body>
<html>
Output:
Output Screen
Properties
175 ITFS
JavaScript
• name - The name of the checkbox 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.
Event Handler
The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .
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>
onClick=”clickFunction”>Morning
onClick=”clickFunction”>Afternoon
onClick=”clickFunction”>Evening
</FORM>
Example:
Program Highlights
Radio.html
<html>
<head>
<script type=”text/javascript”>
function check(language)
177 ITFS
JavaScript
{
document.getElementById(“answer”).value=language;
</script>
</head>
<body>
<form>
<br />
</form>
</body>
</html>
Output:
Output Screen
ITFS 178
Building Forms in JavaScript and Event Handling
Properties
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.
Event Handler
The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes.
179 ITFS
JavaScript
Syntax:
Example:
Program Highlights
Textfield.html
<html>
<head>
<script type=”text/javascript”>
function check()
if(myTextField.value != “”)
ITFS 180
Building Forms in JavaScript and Event Handling
else
</script>
</head>
<body>
</body>
</html>
Output:
Output Screen
Properties
• 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.
Event Handler
The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes.
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:
Displayed Text
</TEXTAREA>
Example:
Program Highlights
Textarea.html
Output:
Output Screen
183 ITFS
JavaScript
Properties
• name - The name of the TextArea object. This object should always have a name.
• 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.
Event Handler
The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .
ITFS 184
Building Forms in JavaScript and Event Handling
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:
<OPTION VALUE=”0">
<OPTION VALUE=”1">AL
<OPTION VALUE=”2">AK
<OPTION VALUE=”3">AR
</SELECT>
Example :
Program Highlights
Selectfield.html
185 ITFS
JavaScript
<HTML>
<HEAD>
</HEAD>
<BODY>
</SELECT>
<P>
</FORM>
</BODY>
</HTML>
Output:
Output Screen
Properties
• 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
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.
Event Handler
The following are the list of DOM (Dynamic Object Model) events that can be used to do
dynamic changes .
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
Syntax:
187 ITFS
JavaScript
Example:
Program Highlights
Reset.html
<HTML>
<BODY>
<P>
<P>
</FORM>
</BODY>
</HTML>
Output:
Output Screen
ITFS 188
Building Forms in JavaScript and Event Handling
Properties
Methods
click() Performs the same as though the user clicked the button.
Events Handler
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
Syntax:
189 ITFS
JavaScript
Example:
Program Highlights
hidden.html
<HTML>
<HEAD>
function stampForm()
document.myForm.timestamp.value = rightnow
function showSecret()
msg += document.myForm.timestamp.value
alert (msg)
</SCRIPT>
</HEAD>
ITFS 190
Building Forms in JavaScript and Event Handling
</FORM>
</BODY>
</HTML>
Output:
Output Screen
Properties
Syntax:
Example:
Program Highlights
Password.html
191 ITFS
JavaScript
<html>
<body>
</body>
</html>
Output:
Output Screen
Properties
Methods
Event Handeler
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
Syntax:
<OPTION VALUE=”0">
<OPTION VALUE=”1">AL
<OPTION VALUE=”2">AK
<OPTION VALUE=”3">AR
</SELECT>
Example:
Program Highlights
option object.html
<HTML>
<HEAD>
</HEAD>
<BODY>
<OPTION VALUE=”2">HTML
<OPTION VALUE=”3">VBScript
193 ITFS
JavaScript
</SELECT>
<P>
</FORM>
</BODY>
</HTML>
Output:
Output Screen
Properties
• selected - Determines if the option is currently selected. This Boolean value is read/
write.
• value - The value sent to the server if the option was selected.
Methods
ITFS 194
Building Forms in JavaScript and Event Handling
Event Handler
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
Syntax:
<FORM>
</FORM>
Example:
Program Highlights
file upload object.html
<html>
<body>
<FORM>
</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.
• value - Can be used to specify the initial value of the file name to be uploaded.
Methods
blur() Takes the focus away from the file upload object.
Event Handler
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
ITFS 196
Building Forms in JavaScript and Event Handling
Syntax:
Example:
Program Highlights
submit object.html
<HTML>
<BODY>
<P>
<P>
<P>
<INPUT TYPE=”RESET”>
<BR>
</FORM>
</BODY></HTML>
197 ITFS
JavaScript
Output:
Output Screen
Properties
Methods
Events Handler
ITFS 198
Building Forms in JavaScript and Event Handling
Example:
Program Highlights
test.html
<html>
<head>
</head>
<body>
<form action=”http://www.riiit.com”
<label>Name:
value=”” /></label>
<br />
<label>Password:
<br />
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)
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
<html>
<head>
<title>radio/checkbox test</title>
<script type=”text/javascript”>
function showradiovalue(radiogroup)
if (radiogroup[i].checked)
</script>
</head>
<body>
<em>Checkbox: </em>
yes:
ITFS 202
Building Forms in JavaScript and Event Handling
no:
maybe:
onclick=”document.testform.check1.click();” />
onclick=”document.testform.radiogroup1[0].click();” />
onclick=”alert(‘checked?’+document.testform.check1.checked);” />
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:
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
ITFS 204
Building Forms in JavaScript and Event Handling
onMouseOut Image, Link The user moves the mouse away from the
object.
onMouseOver Image, Link The user moves the mouse over the object.
onSelect Text, Textarea The user selects text within the field.
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.
target - this property indicates the object to which the event was originally sent.
Syntax:
onAbort = myJavaScriptCode
Example:
Program Highlights
onAbort.html
<html>
<head>
<script type=”text/javascript”>
function abortImage()
</script>
</head>
<body>
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
207 ITFS
JavaScript
<html>
<head>
function addCheck() {
</script>
</head>
<body>
</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
<html>
<head>
<script type=”text/javascript”>
document.getElementById(“test”).onchange()
</script>
<head>
<body>
</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
<html>
<body>
</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
<html>
<body>
</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
<html>
<body>
<img src=”image.gif”
<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
<html>
<body>
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
<html>
s1 = new String(myForm.myText.value)
function changeVal()
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
<html>
<body>
s1 = new String(myForm.myText.value)
function changeVal()
215 ITFS
JavaScript
{
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
ITFS 216
Building Forms in JavaScript and Event Handling
<html>
<body>
s1 = new String(myForm.myText.value)
function changeVal()
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
<html>
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
<html>
<body>
<form>
<br>
</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
<html>
<body>
</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
<html>
<body>
</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
<html>
<body>
</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
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
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
<html>
</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
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
ITFS 226
Building Forms in JavaScript and Event Handling
<html>
<head>
<script type=”text/javascript”>
function validate_form ( )
valid = true;
if ( document.contact_form.contact_name.value == “” )
valid = false;
return valid;
</script>
</head>
<body bgcolor=”#FFFFFF”>
</form>
</body>
</html>
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:
</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 == “” )
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 == “” )
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>
<script type=”text/javascript”>
function validate_form ( )
valid = true;
if ( document.contact_form.contact_name.value == “” )
valid = false;
valid = false;
if ( document.contact_form.age.selectedIndex == 0 )
valid = false;
if ( document.contact_form.terms.checked == false )
ITFS 230
Building Forms in JavaScript and Event Handling
valid = false;
return valid;
</script>
</head>
<body bgcolor=”#FFFFFF”>
<p>Your Age:
<select name=”age”>
</select>
</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 )
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 )
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 )
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
• 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
• 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.
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.
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
window.alert();
• alert()
235 ITFS
JavaScript
Window Object Methods
Methods Description
ITFS 236
Windows Object
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
<html>
<head>
<script type=”text/javascript”>
237 ITFS
JavaScript
function display_alert()
</script>
</head>
<body>
</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
<html>
<body>
<script type=”text/javascript”>
myWindow=window.open(‘’,’’,’width=500,height=250')
myWindow.blur()
</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
<html>
<body>
<script type=”text/javascript”>
var int=self.setInterval(“clock()”,5000);
function clock()
document.getElementById(“clock”).value=t;
</script>
</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
<html>
<head>
</head>
<SCRIPT language=”JavaScript”>
function popuponclick()
241 ITFS
JavaScript
my_window = window.open(“”,
“mywindow”,”status=1,width=350,height=150");
function closepopup()
if(false == my_window.closed)
my_window.close ();
else
</SCRIPT>
<body>
<P>
</P>
<P>
</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
<html>
<head>
<script type=”text/javascript”>
function disp_confirm()
if (r==true)
243 ITFS
JavaScript
}
else
</script>
</head>
<body>
</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
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
<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.
Example:
Program Highlights
moveby.html
<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>
onclick=”moveWin()” />
247 ITFS
JavaScript
</body>
</html>
Output:
Output Screen
window.moveTo()
The moveTo() method moves the window to the specified location.
The numX represents the x-coordinate, while the numY represents the y-coordinate.
Example:
Program Highlights
window.moveTo.html
<html>
<head>
</head>
<script language=”JavaScript”>
function moveWin(form)
ITFS 248
Windows Object
window.moveTo(myX, myY);
</script>
<body>
<form>
<b>X-Coordinate:</b>
<b>Y-Coordinate:</b>
</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
<html>
<head>
<script type=”text/javascript”>
function open_win()
window.open(“http://www.riiit.com”);
</script>
</head>
<body>
<form>
</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
251 ITFS
JavaScript
<html>
<head>
<script type=”text/javascript”>
function printpage()
window.print();
</script>
</head>
<body>
</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.
Example:
Program Highlights
Prompt .html
<html>
<head>
<script type=”text/javascript”>
function greeting() {
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.
Example:
Program Highlights
resizeBy .html
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.
Example:
Program Highlights
resizeto .html
255 ITFS
JavaScript
<html>
<head>
<script type=”text/javascript”>
function resizeWindow()
window.resizeTo(500,300)
</script>
</head>
<body>
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.
ITFS 256
Windows Object
Example:
Program Highlights
scroll to .html
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
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.
Example:
Program Highlights
setInterval .html
<html>
<body>
<script language=javascript>
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.
Example:
Program Highlights
setTimeout .html
<html>
<head>
<script type=”text/javascript”>
function displayAlert()
261 ITFS
JavaScript
}
</script>
</head>
<body>
<form>
<br>
<br>
</form>
</body>
</html>
Output:
Output screen
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
<html>
<head>
<script type=”text/javascript”>
function ifClosed()
function ifNotClosed()
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>
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
ITFS 264
Windows Object
<html>
<body>
<script type=”text/javascript”>
</script>
</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
<html>
<body>
265 ITFS
JavaScript
<script type=”text/javascript”>
alert(window.history.length);
</script>
</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
<html>
<head>
<script type=”text/javascript”>
ITFS 266
Windows Object
function checkWin()
</script>
</head>
<body>
<script type=”text/javascript”>
myWindow=window.open(‘’,’MyName’,’width=200,height=100');
myWindow.document.write(“This is ‘myWindow’”);
</script>
</body>
</html>
Output:
Output Screen
267 ITFS
JavaScript
Syntax: window.outerheight
Syntax: window.outerwidth
Example:
Program Highlights
outerheight/outerwidth .html
<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).
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).
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.
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).
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.
top Property
This property is a reference (or synonym) for the topmost browser window.
Example:
Program Highlights
Top .html
<html>
<head>
<script type=”text/javascript”>
function resizeWindow()
ITFS 270
Windows Object
top.resizeBy(-100,-50);
</script>
</head>
<body>
<form>
</form>
</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
Learning Objectives
The student will be able to
Concepts at a Glance
1. What are Cookies?
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”;
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 .
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.
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!
+ “; expires=15/02/2003 00:00:00”;
275 ITFS
JavaScript
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
if ( exp_y )
if ( path )
if ( 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:
To set a secure cookie with an expiry date and a domain of user defined website, but with
no path:
“riiit.com”, “secure” );
ITFS 276
Cookies
cookie_date.setTime ( cookie_date.getTime() - 1 );
To use this function, just pass in the name of the cookie that we want to delete
Example:
delete_cookie ( “username” );
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:
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:
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>
</head>
<body>
<script language=”JavaScript”>
if ( expires_year )
ITFS 278
Cookies
if ( path )
if ( domain )
if ( secure )
cookie_string += “; secure”;
document.cookie = cookie_string;
cookie_date.setTime ( cookie_date.getTime() - 1 );
if ( results )
else
return null;
if ( ! get_cookie ( “username” ) )
279 ITFS
JavaScript
var username = prompt ( “Please enter your name”, “” );
if ( username )
document.location.reload( );
else
</script>
</body>
</html>
ITFS 280
Cookies
Output:
Output Screen
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
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
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
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
Problem statement: Generate multiplication table of 10,200,3000 and display in table format
ITFS 282
Workbook
Lab Activity : 2
Exercise :1
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
Problem statement: Create a web page, which should display random Number between 1
to 52
Exercise :3
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
Exercise: 5
283 ITFS
JavaScript
Exercise:6
Problem statement: Write a Programming script to check the System day is weeks day or
weekend
Lab Activity : 3
Exercise :1
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
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
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
Problem statement: Create a new window for displaying an animated graphics file.
Exercise 5
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
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
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
Problem Statements: Create web page with Button and Demonstrate the event handler
like Onload,Onclickand OnmouseOver
Exercise :3
Problem Statements: Create web page with Button and shows how to call functions through
the button controls and events.
ITFS 286
Workbook
Exercise :4
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