Sie sind auf Seite 1von 30

Web-Based Information Publishing On the Web

Systems Writing HTML with a text editor allows to generate


web pages. These pages are said static in the sense that
Fall 2006 they do not change.
CMPUT 410: JavaScript What if we want to personalize pages for particular
visitors or events?
Dr. Osmar R. Zaane What if we want to have actions on the page?
What if the content of the page is from a database?
Etc.
University of Alberta
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 1 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 2

Course Content Objectives

Introduction Perl & Cookies


Internet and WWW SGML / XML
Learn how JavaScript stores data, how a document
Protocols CORBA & SOAP is structured in JavaScript
HTML and beyond Web Services Learn event-based programming with JavaScript.
Animation & WWW Search Engines Learn how JavaScript is event driven and how user
CGI & HTML Forms Recommender Syst. actions are tracked
Javascript Web Mining See and analyze some concrete examples with
Databases & WWW Security Issues JavaScript.
Dynamic Pages Selected Topics

Web-based Applications

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 3 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 4
Content Introduction to Variables
I. JavaScript and the Details
Variable identifiers and their types
The notion of objets A variable in Javascript has a type:
Arrays
number (integer or non integer)
Control structures
Condition and selection String
Iteration Boolean
Procedures and functions Null
II. Event-Based Programming with JavaScript
What is an event? JavaScript is not strongly typed.
What are the recognized events?
Capturing events.
III. Practical Examples
Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 5 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 6

Declaring Variables
Type Conversion on the fly
The first time a variable is used it must be declared with the
keyword var.
Because JavaScript is not strongly typed, it
var identifier = value; is possible to:
The identifier must start with a letter or underscore _ and can Change the type of a variable;
have as many characters as necessary (letters, digits, Do operations on variables of different types.
underscore).
The major type, or default type, is string.
Javascript is sensitive to capital letters.
myvariable is different from MyVariable and x X

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 7 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 8
Variable Examples Variable Examples (cont)
<HTML> <BODY>
<HEAD> <script language="JavaScript">
<TITLE>My First Java Script with variables</TITLE> <!-- hide script
<script language="JavaScript"> document.write("myAddition="+myAddition+"<BR>");
<! hide script document.write("myConcatenation="+myConcatenation+"<BR>");
var myNumber=35; document.write("myError="+myError+"<BR>");
var myString="2004"; document.write("myDream="+myDream+"<BR>");
var myOtherString=CMPUT410"; myError = myNumber * 3;
var myAddition = myNumber+myNumber; document.write("myError="+myError+"<BR>");
var myConcatenation = myStyring + myOtherString; myNumber=Bye!";
var myError = myNumber + myOtherString; document.write("myNumber="+myNumber+"<BR>");
var myCalculation = myNumber + myString; // end of hide --> myAddition=70
var myDream = myOtherString + myString; </script>
myConcatenation=2004CMPUT410
// end of hide --> </BODY>
</script> </HTML> myError=35CMPUT410
</HEAD> myDream= CMPUT4102004
myError=105
myNumber=Bye!
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 9 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 10

Content
I. JavaScript and the Details
Variable identifiers and their types JavaScript & Concept of Objects
The notion of objets
Arrays
Control structures JavaScript is not an object-oriented language.
Condition and selection JavaScript is an object-based language.
Iteration There are many pre-defined objects, but
Procedures and functions programmers can define their own objects.
II. Event-Based Programming with JavaScript
What is an event? An object has attributes (specific properties) as
What are the recognized events? well as methods (behaviour of objects).
Capturing events. An attribute could be a value or recursively
III. Practical Examples another object.
Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 11 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 12
A Book is an Object What are the Objects, What
Title
are their Properties?
Authors
Editors
Number of pages
Price
Set of Chapters
Set of figures and images
etc.
?
Each book has the same
attributes with different
values

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 13 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 14

Access Object Properties Access Object Methods


myObject.oneProperty myObject.oneMethod(parameters)
Object Name . Attributre Name Object Name . Method Name ( parameters )
If the attribute is also an object, to access the property of the If there are no parameters:
attributes attribute:
myObject.oneMethod()
myObject.oneProperty.aPropertyOfProperty
Ex: Book.Editor.Address Ex: document.write(Hello!)

document.MyForm.Name.value
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 15 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 16
Predefined Object Classes Object Date
There are many intrinsic pre-defined objects in The object Date needs to be instantiated
JavaScript: with the keyword new.
var today= new date();
Date Navigator
String History The class Date doesnt have properties but
Math Location the following methods:
Window Form getDate() getYear()
Document etc getDay() setDate()
getHours() setHours()
getMinutes() setMinutes()
etc
These objects have their pre-defined attributes and getMonth() setMonth()
methods. getSeconds() getSeconds()
getTime(); setTime();
getTimezoneOffset() setYear()
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 17 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 18

Example with Date The Object String


<HTML> Where we define a string constant or a string variable,
<HEAD> JavaScript creates an instance of an object String.
<TITLE>My test with dates</TITLE><script language="JavaScript">
var thisIsNow=new Date(); The object String has one property, lenght, and many
var BirthDate = new Date(60,05,18); methods:
</script></HEAD>
<BODY> <script language="JavaScript">
document.write(Today we are the: "+thisIsNow+"<BR>"); anchor() astring.anchor(anchor)<A name=anchor>astring</A>
document.write(Alfreds birthdate is the "+ BirthDate +"<BR>"); big() astring.big()<BIG>astring</BIG>
document.write(The date:"+ BirthDate.getDate()+ "/" +
blink() astring.bink()<BLINK>astring</BLINK>
(BirthDate.getMonth()+1) + "/" +
(BirthDate.getYear()+1900)+"<BR>"); bold() astring.bold()<BOLD>astring</BOLD>
document.write(The time now is:" + thisIsNow.getHours() + ":" + fontcolor() astring.fontcolor(#FF0000)<FONT color=#FF0000>astring</FONT>
thisIsNow.getMinutes() + ":" + fontsize() astring.fontsize(5)<FONT size=5>astring</FONT>
thisIsNow.getSeconds()+"<BR>"); italics(); astring.italics() <I>astring</I>
thisIsNow.setYear(2010); small() astring.small()<SMALL>astring</SMALL>
document.write(The new date in the future is:<br>"+ thisIsNow); sub() astring.sub() <SUB>astring</SUB>
</script></BODY></HTML> sup() astring.sup() <SUP>astring</SUP>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 19 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 20
The Object String (cont) Example with String Object
Other methods for the String object: <HTML>
<HEAD>
link() <TITLE>My test with strings</TITLE>
toUpperCase() astring.toUpperCase() converts into uppercase <script language="JavaScript">
toLowerCase() astring.toLowerCase() converts into lowercase var myString=prompt(Give me a phrase",I am at school");
substring() astring.substring(3,5) substring from 3rd character to 5th. </script>
indexOf() astring.indexOf(anOther) returns the position of anOther in astring. </HEAD><BODY>
charAt() astring.charAt(4) returns the 4th character. <script language="JavaScript">
document.write(myString+"<BR>");
document.write(myString.bold()+"<BR>");
document.write(myString.italics()+"<BR>");
The index in a string starts at 0. document.write(myString.fontcolor("red").blink()+"<BR>");
document.write(myString.link("http://www.cnn.com")+"<BR>");
document.write(myString +"<BR>");
</script>
</BODY></HTML>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 21 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 22

The Object Math The Object Window


JavaScript provides by default an object window
The class Math contains common constants such as:
representing the current window. This object is the root of
Math.PI and Math.E which respectively return the hierarchy describing the JavaScript objects.
3.1415926535897931 and 2.7182818284590451
This object has many properties:
Some useful methods:
defaultStatus default message displayed on the status bar
frames set of frames displayed by the browser
abs() log() length number of frames present in the parent window
acos() max() name name of the window
cos() min() parent parent window
asin() pow() self active window
sin() random() status message displayed on the status bar
atan() round() top top of the object hierarchy defined by the browser
tan(); sqrt(); window active window
exp() floor()
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 23 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 24
Methods of the Window Object
Example with Windows
alert() (modal) window to display a message.
confirm() (modal) window for selection. <HTML>
prompt() (modal) window to enter a value. <HEAD>
<TITLE>My test with windows</TITLE>
clear() clears the window content. </HEAD>
open() opens a new window. <BODY>
<A HREF="#" onMouseOver="window.status=Hi!';return true;">Hello!</A>
close() closes the current window. <BR>
<A HREF="test.html" TARGET=new">Open me</A>
To open a window: <BR>
window.open(URL,NameOfWindow,options); </BODY>
Options are: </HTML>
menubar resizable toolbar
status width location
scrollbars height directories
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 25 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 26

Opening a Window Example with Window Options


<HTML> <HTML>
<HEAD> <HEAD>
<TITLE>My other test with windows</TITLE> <TITLE>Yet another test with windows</TITLE>
</HEAD> </HEAD>
<BODY> <BODY>
<a href="#" onClick="myWindow=window.open( menubar,status,scrollbars,resizable,location,directories,width,height
'test.html',myTest','width=100,height=200,scrollbars,resizable'); <BR>
return true;">Open me</a><br> <a href="#" onClick="option=prompt(What are your options:');
<a href="#" onClick="myWindow.focus();return true;">Show me</a><br> myWindow=window.open('','myTest',option);
<a href="#" onClick="myWindow.blur(); return true;">Hide me </a><br> return true;">Open me</a>
<a href="#" onClick="myWindow.close();return true;">Close me</a><br> <BR>
</BODY> <a href="#" onClick=myWindow.close();
</HTML> return true;">Close me</a>
<BR>
</BODY>
</HTML>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 27 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 28
Object Hierarchy
Document Object Model
window
(DOM) history
frame links
Now that we know what a JavaScript object is location anchors button
and we know how to open a window, it is time to image checkbox
document
applets FileUpload
learn about the document object model. hidden
embeds
JavaScript includes predefined objects such as area password
window. These objects have predefined form reset
submit
properties and methods. Most of the tricks to make a web text
An object property can also be an object. page more dynamic use the document textarea
model and take advantage of the select
hierarchical model. option

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 29 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 30

Other Examples of Predefined The Frames


Objects The important thing about frames, is that each
History contains the list of all visited URL frame inside a window is also considered a
during the current session. window.
<HTML> This implies nested window.
<HEAD><TITLE>My test with history</TITLE></HEAD>
<BODY> Thus, there is a window on top including all the
<SCRIPT LANGUAGE="JavaScript">
document.write(Number of URL="+window.history.length);
others called top, and each window has a parent
</SCRIPT><FORM> called parent. To reference the current window, we
<INPUT TYPE=button VALUE="Back" use self (interchangeable with window).
onClick="window.history.back();return true;">
<INPUT TYPE=button VALUE=Back 3 pages" top
onClick="window.history.go(-3);return true;">
</FORM> parent
</BODY></HTML> self
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 31 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 32
JavaScript and Frames JavaScript and Frames (cont)
<HTML><HEAD><TITLE>My test with Frames</TITLE> <HTML><HEAD><TITLE>Another test with Frames</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<SCRIPT LANGUAGE="JavaScript">
var FrameEmpty = '<html><body bgcolor="#FFFFFF"></body></html>';
var FrameEmpty = '<html><body bgcolor="#FFFFFF"></body></html>';
</SCRIPT>
</HEAD> </SCRIPT>
<FRAMESET rows="25%,*"> </HEAD>
<FRAME SRC="EX16.HTM" name="controle"> <FRAMESET rows="25%,*">
<FRAME SRC="javascript:parent.FrameEmpty" name=target_frame"> <FRAME SRC="EX16b.HTM" name="control">
</FRAMESET> <FRAME SRC="javascript:parent.FrameEmpty" name=target_frame">
</HTML> </FRAMESET>
EX16.HTM
</HTML> EX16b.HTM
<HTML>
<HEAD><TITLE>Control Frame</TITLE></HEAD> <HTML>
<BODY> <HEAD><TITLE>Control Frame</TITLE></HEAD>
<a href="#" onClick="top.target_frame.document.writeln(Good Day!<br>');">Good Day!</a> <BODY>
<BR><a href="#" onClick="top.target_frame.document.writeln(Hi!<br>');">Hi!</a> <a href="#" onClick="top.target_frame. document.bgColor='#00FF00';">Green</a>
</BODY></HTML> <BR><a href="#" onClick="top.target. document.bgColor='yellow';">Yellow</a>
</BODY></HTML>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 33 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 34

Content
The Object Navigator I. JavaScript and the Details
Variable identifiers and their types
There are no methods associated but some attributes: The notion of objets
Arrays
<html> Control structures
<head><title>Version of the Navigator</title></head>
<body>
Condition and selection
<h1> Lets see what browser it is</h1> Iteration
<hr> Procedures and functions
<script language="javascript"> II. Event-Based Programming with JavaScript
document.write(The version of this browser is: " + navigator.appVersion);
document.write ("<br>The Browser is: <B>" + navigator.appName + "</B>"); What is an event?
document.write("<br>Its code name is: " + navigator.appCodeName); What are the recognized events?
document.write ("<br>The OS is: " + navigator.userAgent); Capturing events.
</script>
</body></html> III. Practical Examples
Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 35 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 36
Arrays Simple Example with Arrays
<HTML>
Variables can contain numbers, strings, and object <HEAD>
references. There is also another type of information <TITLE>test with arrays</TITLE>
<SCRIPT LANGUAGE="JavaScript">
that JavaScript can manipulate: Arrays. var colours=new Array("red","blue","green","white");
</SCRIPT>
</HEAD>
var products = new Array(car, truck, bike); <BODY>
product[0] car <a href="#" onClick="document.bgColor=colours[0];return true;">Colour1</a>
<BR>
product[1] truck
<a href="#" onClick="document.bgColor=colours[1];return true;">Colour2</a>
product[2] bike <BR>
product.length 3 <a href="#" onClick="document.bgColor=colours[2];return true;">Colour3</a>
<BR>
<a href="#" onClick="document.bgColor=colours[3];return true;">Colour4</a>
</BODY>
</HTML>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 37 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 38

Another Test with Arrays Random Add


<HTML>
<HEAD> <HTML><HEAD>
<TITLE>Another test with arrays</TITLE> <TITLE>Test with Arrays</TITLE>
<SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">
var processors=new Array("Intel PIII","AMD K7","Cirex"); var pubs=new Array("car01.jpg","car02.jpg","car03.jpg","car04.jpg",
</SCRIPT> "car05.jpg","car06.jpg","car07.jpg");
</HEAD><BODY> var numPub=pubs.length;
<FORM NAME="myCPUform"> var now = new Date();
<INPUT TYPE="text" NAME="cpu" VALUE=""><BR> var x = now.getSeconds() % numPub;
<INPUT TYPE="button" VALUE="Intel" </SCRIPT>
onClick="document.myCPUform. cpu.value=processors[0];return true;"> </HEAD><BODY>
<INPUT TYPE="button" VALUE="AMD" <H1>Todays Car</H1>
onClick="document. myCPUform. cpu.value=processors[1];return true;"> <SCRIPT LANGUAGE="JavaScript">
<INPUT TYPE="button" VALUE="Cirex" document.write(Car Number "+ x+"<br>");
onClick="document. myCPUform. cpu.value=processors[2];return true;"> document.write("<IMG WIDTH=320 HEIGHT=240 SRC="+pubs[x]+">");
</FORM> </SCRIPT></BODY></HTML>
</BODY></HTML>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 39 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 40
DOM Revised Content
I. JavaScript and the Details
Despite the fact that we didnt see all the Variable identifiers and their types
object details in DOM, we have now a rough The notion of objets
idea how it works and how it is used. Arrays
Control structures
After seeing the arrays, we know that a Condition and selection
document is structured as follows: Iteration
Procedures and functions
document II. Event-Based Programming with JavaScript
links[] What is an event?
anchors[]
document.image[2].src=; What are the recognized events?
images[]
Capturing events.
area[]
form[] Change the 3rd document III. Practical Examples
image. Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 41 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 42

Condition and Selection if - then - else


Like many other languages,
JavaScript provides control
structures to execute
There are many variations for this instructions pending some if (condition) instruction;
conditions. else OtherInstruction;

if (condition) {
instruction1;
if (condition) instruction;
instruction2;

if (condition) {
} else {
instruction1;
instructionA;
instruction2;
instructionB;


}
}
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 43 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 44
Nested Selections Logic Operators
We can also have many nested conditions
Conjunction:
And &&
example: (price>=200 && member==true)
if (condition1) {instructions1;} Disjunction
else if (condition2) {instructions2;} Or ||
else if (condition3) {instructions3;}
example: (age>26 || total==1000)
else if (condition4) {instructions4;}
. Negation
else {otherInstructions;} Not !
example: (!finale && !(numbre==50))

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 45 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 46

Example with Condition While Loop


<HTML> Like many other languages,
<HEAD><TITLE>Example with Condition</TITLE></HEAD> JavaScript provides control
<BODY> structures repetitions
<SCRIPT LANGUAGE="JavaScript">
var month=prompt(What is your favorite colour?"); while (condition) instruction;
if (pays.toUpperCase() == BLUE") The execution of the
alert(Great! Me too."); while (condition) { instruction is repeted
else instruction1; while the condition is
alert(That is ugly!"); instruction2; true.
</SCRIPT>
</BODY> }
</HTML>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 47 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 48
Example with Repetition
For Loop
<HTML>
<HEAD><TITLE>quiz</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var now = new Date();
var x = now.getSeconds();
var answer=prompt(guess the seconds"); for (init;condition;increment) instruction;
</SCRIPT></HEAD><BODY>
<SCRIPT LANGUAGE="JavaScript">
while (answer!= x) { for (init;condition;increment) {
document.write(answer +"<br>"); instruction1;
if (x< answer) alert(Too big"); instruction2;
else alert(Too small");
answer =prompt(" guess the seconds ");
}
}
document.write("Bravo!");
</SCRIPT></BODY></HTML> for (i=0;i<20;i++) document.write(*);

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 49 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 50

Example with for Loop Arrays and DOM


<html> As seen before, a document could have a set of
<head><title>Factorials</title></head>
<body>
images. These images could have a name: <IMG
<h1>Factorials from 1 to 9</h1> SRC=image.gif NAME=myName >
<script language = "JavaScript"> The name of an image can be used to manipulate
<! -- hide me
for (i=1, fact=1; i<10;i++, fact=fact *i){ then image: document.myName.src=car.gif;
document.write (i + "! = " + fact); With DOM, a document has an image array:
document.write ("<br>");
} document.images[0], document.images[1],
// end hiding --> When can then manipulate the images by accessing
</script>
</body>
this array: document.images[3].src=car.gif;
</html>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 51 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 52
Content
Example with images[] I. JavaScript and the Details
<html> Variable identifiers and their types
<head><title>Images of the document</title> The notion of objets
</head><BODY> Arrays
<IMG SRC=dblace1.jpg><IMG SRC=dblace2.jpg> Control structures
<IMG SRC=dblace3.jpg><IMG SRC=dblace4.jpg> Condition and selection
<IMG SRC=dblace5.jpg> Iteration
<SCRIPT LANGUAGE="JavaScript"> Procedures and functions
var which=100; II. Event-Based Programming with JavaScript
while(which <0 || which >4) What is an event?
which =prompt(Which image? (0 .. 4)','1');
What are the recognized events?
window.document.images[which].src="car01.jpg";
</SCRIPT> Capturing events.
</BODY> III. Practical Examples
</html> Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 53 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 54

Functions and Procedures Example showing the use of


Functions and procedures, also called subroutines with and without
subroutines, are fundamental in JavaScript
programming. parameters
Suppose we want to measure the reading
A subroutine is a set of instructions semantically
speed of a user. We could put a button
linked.
within the text that would display the time
Grouping instructions in subroutines avoids each time it is pressed.
rewriting the instructions. If there is an update, K asdddfkjashhdf
askdjfhhaskdjfh

it suffices to make the change once in the sub- asddfkjjgasdf


asdkdfjasd kjhggasdf
fkjkfjhjh dsfkjh
asdflkjkj asdkfjhss

routine. asfkfjhhasd asdkjh


asdkjhasd kjhasddf
kjhasd
kjhasdfdkjhasd
fkjhasdkfjha
sdkjjhasdd kjhasdd
kjhkjhkjh kjhkjh kjh

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 55 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 56
There is a Problem
The button could be: The previous code could be put in different places
within the text.
<FORM>
Notice that if the minutes or the secondes are less
<INPUT TYPE="button" VALUE="time" onClick=" than 10, only one digit is displayed (0,1, 2, 3, 9)
var theDate=new Date(); and not two (00, 01, 02,09).
var hour=theDate.getHours();
var minutes=theDate.getMinutes();
Now we have to update the code wherever we
var secondes=theDate.getSeconds(); incerted it.
var theTime=hour + ':' + minutes + ':' + secondes; A better solution would be to write a subroutine
alert(theTime);"> that displays the time and call this same sub-
</FORM>
routine with all the buttons in the text.

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 57 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 58

Sub-routine without
Updating the sub-routine
Parameters
function announceTime() {
<SCRIPT LANGUAGE="JavaScript"> var theDate=new Date();
<! hide me var hour=theDate.getHours();
function announceTime() { var minutes=theDate.getMinutes();
var theDate=new Date(); if (minutes<10) minutes="0"+ minutes;
var hour=theDate.getHours(); var seconds=theDate.getSeconds();
var minutes=theDate.getMinutes(); if (seconds<10) seconds="0"+ seconds;
var seconds=theDate.getSeconds(); var theTime=heure + ':' + minutes + ':' + seconds;
var theTime=hour + ':' + minutes + ':' + seconds; alert(theTime);
alert(theTime); }
} <FORM>
// end hide --> <INPUT TYPE="button" VALUE="Time"
onClick="announceTime();"> The change is done once and all buttons are updated.
</SCRIPT> </FORM>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 59 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 60
Sub-routine with parameters
Sub-routine with parameters
and return value
if (minutes<10) minutes="0"+ minutes;
arguments
if (secondes<10) seconds="0"+ seconds;
function correct(theNumber) {
Similar operations we could create a new function to var myValue;
do this same operation. if (theNumber<10) myValue="0"+theNumber;
else myValue=theNumber;
return myValue;
}

Returned value

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 61 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 62

The updated sub-routine Object Creation


Functions are also used to define and create
function announceTime() {
new objects.
var theDate=new Date(); function house(roomn, year, gar){
var hour=theDate.getHours(); this.rooms = roomn;
var minutes=theDate.getMinutes(); rooms
this.year = year;
var corrMin = correct(minutes);
this.aGarage = gar; year
var seconds=theDate.getSeconds();
var corrSec = correct(seconds); } aGarage
var theTime=hour + ':' + corrMin + ':' + corrSec; var myHouse = new house(8, 1990, true)
alert(theTime);
}

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 63 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 64
Object - Array Index by Property
An array is indexed by an integer (0 to N).
Each object is made of an array of values and
properties. An array representing an object is also
indexed by object attribute.
Thus, we could write:
myHouse[0] = 8; Thus, we could write:
myHouse[1] = 1990; myHouse[rooms] = 8;
myHouse[2] = true; myHouse[year] = 1990;
myHouse[aGarage] = true;

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 65 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 66

Attaching a method to an Object


Dynamic Extension of Objects Like Object Oriented languages, JavaScript
allows you to attach methods to objects that
We can dynamically add attributes to an object. you create.
yourHouse = new house(5, 1974, true); rooms
year
yourHouse.closeOcean = false; aGarage function house(roomn, year, gar){
yourHouse.windows = 18; closeOcean
windows this.rooms = roomn;
yourHouse this.year = year;
The extension concerns only the instance to this.aGarage = gar;
which the attributes were added. The other this.display = displayHouse;
instances stay the same. }

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 67 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 68
Calling the Method Summary Part I
We saw the basics of JavaScript and we learned to
function displayHouse(){ write scripts and perhaps interpret scripts written by
document.write(House has + this.rooms + others.
rooms); We explored the concept of object with JavaScript and covered
if (this.aGarage) some predefined objects such as String, Date, Math, Window, etc., as
well as their properties and methods.
document.write( and a garage.); We discussed the document object model (DOM).
document.write(Built in + this.year); We saw how to create new objects and extend their properties and
} methods.

myHouse=new house(8,1990,true);
myHouse.display(); House has 8 rooms and a garage. Built in 1990
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 69 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 70

Content
I. JavaScript and the Details Interactive Application
Variable identifiers and their types
The notion of objets For an interactive application one needs the
Arrays possiblity to react to users actions.
Control structures We need to provide the user with means to enter
Condition and selection data, click on objects, select options, etc.
Iteration The application needs to capture the users actions
Procedures and functions and react to these actions.
II. Event-Based Programming with JavaScript Identify events and answer them.
What is an event?
What are the recognized events?
Capturing events.
III. Practical Examples
Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 71 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 72
Content
What is an Event? I. JavaScript and the Details
Variable identifiers and their types
The notion of objets
An event is a change in the environment due to some
Arrays
actions usually (but not always) made by the user. Control structures
These actions are pertaining to the mouse and Condition and selection
keyboard. Iteration
A change in the document or the objects in the Procedures and functions
document constitute events. II. Event-Based Programming with JavaScript
What is an event?
Example: moving or clicking the mouse, updating a What are the recognized events?
value in an entry field, etc. Capturing events.
III. Practical Examples
Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 73 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 74

What are the events recognised Events in JavaScript


by JavaScript? We already saw a sample of JavaScript events in the code
examples used to illustrate previous concepts.
JavaScript captures and manages 9 event types:
Mouse click (left button).
Mouse cursor passing over an object. onClick The left button of the mouse is clicked when over a target.
The selection or de-selection of an entry field. onMouseOver The mouse cursor passes over a target.
onBlur The focus on a target is lost.
The update of the entry field value. onFocus The target is activated.
onSelect The target is selected.
The submission of an entry form. onChange The target content changed.
The loading of a new document. onSubmit The form is submitted (or being submitted).
onLoad The page is being loaded.
The exit of the browser or document. onUnload The page is being replaced or closed.

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 75 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 76
The Event Targets
Other Events
The targets actually capture the events; these are objects from the
document object model (DOM). Objects dont capture the same
events. onError
onClick A HREF, BUTTON, CHECKBOX, RADIO,
RESET, SUBMIT
onAbort
onMouseOver A HREF These events are used with window and
onBlur PASSWORD, SELECT, TEXT, TEXTAREA
onFocus PASSWORD, SELECT, TEXT, TEXTAREA image and come from page or image loading
onSelect PASSWORD, TEXT, TEXTAREA interruptions (manual interruption, abort,
onChange PASSWORD, SELECT, TEXT, TEXTAREA
onSubmit FORM etc.).
onLoad BODY (window), IMAGE
onUnload BODY (window)

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 77 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 78

How does it work? Another Event: Timeout


The browser intercepts the events (also called The window object has 2 specific methods to
interruptions) and acts upon them. manage a countdown
Action Event Capture Action setTimeout() specifies a millisecond counter
that is associated to an instruction. After a
The actions are associated to the targets by specified time interval, an interruption is
means of the HTML tags. produced and the instruction is evaluated.
<TAG onEvent=Action> clearTimeout() cancels the countdown.
Example: <A href=# onClick=alert(Hello!);>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 79 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 80
A living Clock Example of a Timer
<html><head><title>Timer</title>
We saw how to display the current time in a <SCRIPT LANGUAGE="JavaScript">
function myClock () {
previous example. var now = new Date();
var hour = now.getHours();
To have a clock, it suffices to contineously var minutes = now.getMinutes();
display the time at the same place. var seconds = now.getSeconds();
var timeResult = "" + hour+ ((minutes < 10)?":0":":")
We have to call the function to display the + minutes + ((seconds < 10)?":0":":") + seconds;
return timeResult;
time at regular intervals. }
<BODY onLoad="WhatTime()">
function WhatTime() {
Defining a timeout within the time display var theTime=myClock();
<FORM>
<INPUT TYPE=TEXT SIZE=8
function would do the trick. document.forms[0].clicking.value=theTime;
NAME=clicking">
setTimeout(WhatTime()',1000);
</FORM>
}
</BODY></html>
</SCRIPT></head>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 81 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 82

Slides with setTimeout() Slidess (cont)


Continuously superposing images by calling the subroutine that function forward() {
displays an image at regular intervals. stop();
num = (num+1) %number;
window.document.images[0].src=slides[num] + ".jpg";
<html> window.document.forms[0].image.value=num+1;
<head><title>Countdown images</title> }
<SCRIPT LANGUAGE="JavaScript">
var slides=new Array("jump1","jump2","jump3","jump4", function backward() {
"jump5","jump6","jump7","jump8"); stop();
var number=slides.length; if (num==0) num=number-1; else num--;
var num=0; document.images[0].src=slides[num] + ".jpg";
var timer=0; window.document.forms[0].image.value=num+1;
}
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 83 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 84
Slidess (cont) Slides (cont)
</SCRIPT>
</head>
function next() { <BODY>
forward(); <CENTER>
timer=setTimeout("next()",500); <IMG SRC="jump1.jpg">
} <FORM>
<INPUT TYPE=BUTTON value="&lt;&lt;" onClick=backward();'>
function stop() { <INPUT TYPE=BUTTON value="Stop" onClick='stop();'>
clearTimeout(timer); <INPUT TYPE=BUTTON value="&gt;&gt;" onClick=forward();'>
} <INPUT TYPE=BUTTON value="Show" onClick='restart();'>
Image:<INPUT TYPE="TEXT" SIZE=1 NAME="image">
function restart() { </FORM>
timer=setTimeout("next()",500); </CENTER>
} </BODY>
</html>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 85 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 86

Content
I. JavaScript and the Details Order of Execution
Variable identifiers and their types
The notion of objets In traditional programming, the order of execution is
Arrays
dictated by the order of instrctions in the code. The
Control structures
execution is instruction by instruction.
Condition and selection
Iteration With event-based programming, the order of execution
Procedures and functions depends upon the events.
II. Event-Based Programming with JavaScript When an event is intercepted, the corresponding
What is an event? instructions are executed.
What are the recognized events?
Capturing events.
III. Practical Examples
Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 87 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 88
Order of Execution (cont) Associating Functions with
Functions should be defined before they are Events
invoked. After defining a function, one must
Warning: An event could happen before the associate this function to the events we want
whole document is loaded. The user can indeed to capture.
use the mouse while only part of the page is
loaded and displayed. We use the keywords for these events
(event handlers) that we saw previously.
Before invoking a function we must make sure it
is defined.
<BODY onLoad=JavaScript instructions>
This is one reason why it is better to put the <FRAMESET onLoad=JavaScript instructions>
function definitions in <HEAD> window.onLoad=FonctionReference;

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 89 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 90

Example of Association Events for JavaScript Objects


A form <FORM METHOD=></FORM> allows data entry.
The browser submits these data to the server when the We saw the list of events intercepted by
submit button is pressed. JavaScript.
Adding onSubmit=return verifyForm(this) to the tab Lets see, object by object, the most common
<FORM> would call and execute the function verifyForm
events and the HTML syntax.
when the browser attempts to submit the data, and thus
allows to intercept the data and validate it before it is We will emphasise the events associated with
actually sent. form objects.

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 91 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 92
Common Events and window Common Events and link
onLoad invoked when the page is loaded. onClick invoked when a hyperlink is clicked.
onUnload invoked when the page is left. onMouseOver invoked when the mouse is over the
link.
HTML Syntax HTML Syntax
<BODY
<A
[BACKGROUND= imageURL] [BGCOLOR = color]
HREF = URL
[TEXT = color] [LINK = color] [ALINK = color] [VLINK = color]
[TARGET = target_window]
[onLoad = handler] [onUnload = handler] > [onClick = handler]
<FRAMESET [onMouseOver = handler] >
[ROWS=lines] [COLS=columns]
[onLoad=handler] [onUnload=handler]>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 93 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 94

Common Events and form Common Events and button


onReset invoked before resetting. onClick invoked when the button is pressed.
onSubmit invoked before submitting.

HTML Syntax HTML Syntax


<FORM <INPUT Attributes
[NAME = name] TYPE = button name
[TARGET = target_window] VALUE= string
form
[ACTION = URL] [NAME = name]
type
[METHOD = GET/POST] [onClick = handler] >
[ENCTYPE = encryption]
value
[onReset = handler]
[onSubmit = handler] >

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 95 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 96
Common Events and checkbox Common Events and radio button
onClick invoked when the checkbox is clicked. onClick invoked when the radio button is
clicked.

HTML Syntax HTML Syntax


<INPUT Attributes <INPUT Attributes
TYPE = checkbox name TYPE = radio name
[VALUE= string] [VALUE= string]
form form
[NAME = name] [NAME = name]
checked checked
[CHECKED] [CHECKED]
defaultChecked defaultChecked
[onClick = handler] > [onClick = handler] >
type type
value value

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 97 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 98

Common Events and select Common Events and text


onChange invoked when a change occurs. onChange invoked when there is a change
onBlur invoked when the select looses focus. onBlur invoked when the text looses focus
onFocus invoked when the select is activated. onFocus invoked when the text field is activated.

HTML Syntax Attributes HTML Syntax Attributes


<SELECT name <INPUT name
NAME = name form TYPE=text form
[SIZE= size] length [NAME = name] value
[MULTIPLE] [VALUE= default]
options defaultValue
[onChange = handler] [SIZE=size] [MAXLENGTH=maxsize]
selectedIndex type
[onBlur = handler] [onChange = handler]
type [onBlur = handler]
[onFocus = handler] >
[onFocus = handler] >
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 99 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 100
Common Events and textarea Common Events and submit
onChange invoked when there is a change. onClick invoked the button is clicked.
onBlur invoked when the area looses focus.
onFocus invoked when the area is activated
HTML Syntax
HTML Syntax Attributes <INPUT Attributes
<TEXTAREA name TYPE = submit name
[NAME = name] [VALUE= string]
form form
[ROWS= lines] [COLUMNS=columns] [NAME = name]
value type
[WRAP=OFF/VIRTUAL/PHYSICAL] [onClick = handler] >
defaultValue value
[onChange = handler]
type
[onBlur = handler]
[onFocus = handler] >

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 101 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 102

Common Events and reset Common Events and image


onClick invoked the button is clicked. onClick invoked when the image is clicked.

HTML Syntax HTML Syntax


<INPUT Attributes <INPUT Attributes
TYPE = reset name TYPE = image name
[VALUE= string] SRC= URL
form form
[NAME = name] [NAME = name]
type type
[onClick = handler] > [onClick = handler] >
value src

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 103 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 104
Summary Part II Content
I. JavaScript and the Details
Variable identifiers and their types
The notion of objets
Arrays
We saw what is an event in JavaScript. Control structures
We saw how events are intercepted. Condition and selection
We enumerated the known events. Iteration
We saw the form elements and the associated events. Procedures and functions
We saw how to program with events and how the II. Event-Based Programming with JavaScript
execution is done. What is an event?
We illustrated the concepts with simple examples. What are the recognized events?
Capturing events.
III. Practical Examples
Data entry validation within a form;
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 105 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 106

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">


function checkform()
{
if(document.myform.variable1.value=="") {
alert("Please enter the full path for your file! ");
document.myform.variable1.focus();
return(false);
}
if(document.myform.variable2.selectedIndex==0) {
alert("Please choose a content! ");
document.myform.variable2.focus();
return(false);
}
if(document.myform.variable3.value>5){
alert("Please enter a correct number! ");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
document.myform.variable3.focus();
return(false);
<HTML>
}
<HEAD>
}
<title>Example of Forms with JavaScript</title>
</SCRIPT>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 107 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 108
</HEAD> <tr>
<BODY bgcolor="#ffffff"> <td><font face="arial,helvetica"> File Content</font></td>
<center> <td>: <select name="variable2">
<h1><font face="arial,helvetica"> Form Example</font></h1> <option value="">-----> Please choose a content!
</center> <option value="1"> Resume
<FORM name=myform" <option value="2"> Application
action="/cgi-bin/mycgi.pl" <option value="3"> Complaint
method="post" <option value="4"> Other
enctype="multipart/form-data" </select></td>
onSubmit="return checkform()> </tr>
<table border="0"> <tr>
<tr> <td><font face="arial,helvetica"> Number [0..5]</font></td>
<td><font face="arial,helvetica"> Upload a file</font></td> <td>: <input type=text" name= "variable3" size=2 > </td>
<td>: <input type="file" name= "variable1" size=20 > </td> </tr>
</tr> </table>
<input type=submit value=Upload>
</FORM>
</BODY>
</HTML>
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 109 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 110

Entering an e-mail Address function checkEmail(){


e-mail Validation
var theAddress=document.myAddress.email.value;
<html>
var newAddress = "";
<head><title>Validate my e-mail</title>
for (k = 0; k < theAddress.length; k++){
<SCRIPT LANGUAGE="JavaScript">
ch = theAddress.substring(k, k+1);
if ((ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z") || (ch == "@") ||
(ch == "[") || (ch == "]") || (ch == ".") || (ch == "_") || (ch == "-") ||
</script> (ch >= "0" && ch <= "9"))
<BODY onLoad=emailReset();"> newAddress += ch;
<FORM name="myAddress" onsubmit="return verifyEmail();"> }
E-Mail: <input type="text" name="email" size="25" if (theAddress!= newAddress) {
onchange="this.value=checkEmail();"><br> if (confirm(You entered spaces or invalid characters.\n\n
<input type="submit" value="Submit" name="B1"> Click OK to fix this.\n\nClick CANCEL to keep unchanged."))
<input type="reset" value="Init" name="B2" onclick=emailReset();"> return newAddress;
</FORM> return theAddress;
</BODY> }
</html> return theAddress;
}
Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 111 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 112
e-mail Validation (cont) e-mail Validation (cont)
function verifyEmail(){ if ((theAddress.indexOf("@") == -1) || (theAddress.indexOf(".") == -1)) {
var theAddress = document.myAddress.email.value alert(Check your e-mail. An address must include the characters '@' and '.'\n\n
if (document.myAddress.email.value == "") { Example: jha@somewhere.com");
alert(Please enter your e-mail.") document.myAddress.email.select();
document.myAddress.email.focus(); document.myAddress.email.focus();
return false; return false;
} }
theAddress =document.myAddress.email.value; c = theAddress.indexOf("@")
b = theAddress.substring(0,1) d = theAddress.indexOf(".");
if (b == '@') { e = theAddress.substring(c,d);
alert(Check your e-mail. You should have a prefix before '@'\n\n if (e.length < 2) {
Example: jha@somewhere.com") alert(Some domain has to exist between the characters \"@\" and \".\"")
document.myAddress.email.select(); document.myAddress.email.select();
document.myAddress.email.focus(); document.myAddress.email.focus();
return false; return false;
} }

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 113 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 114

e-mail Validation (cont) Another e-mail example


b = theAddress.indexOf(".") <HEAD>
theAddress = theAddress.substring(b, theAddress.length); <SCRIPT LANGUAGE="JavaScript">
if (theAddress.length <2) { <!-- Begin
alert(You have to have a suffix of at least 2 characters after the '.'") function checkEmail(myForm) {
document.myAddress.email.select(); if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value)){
document.myAddress.email.focus(); return (true)
return false; }
} alert("Invalid E-mail Address! Please re-enter.")
alert(Thank you"); return (false)
<BODY>
return false; }
<form onSubmit="return checkEmail(this)">
} // End --> E-mail Address:<br>
</script> <input type="text" name="emailAddr">
function emailReset(){ </HEAD> <p>
document.myAddress.email.value = ""; <input type="submit" value="Submit">
<input type="reset" value="Reset">
document.myAddress.email.focus();
</form>
} </BODY></HTML>

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 115 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 116
Return True
Some useful References
What is "return true", "return false"?
This is what is used to actually allow, or stop the form from JavaScript with Netscape
submitting, respectively. This is how JavaScript controls the http://developer.netscape.com/docs/manuals/index.html?content=javascript.html
submitting of a form. By default, a form will return true. (Submit Jscript (Microsoft) http://msdn.microsoft.com/scripting/default.htm
the form).
Builder.com http://www.builder.com
This is a important point. For example, you can stop a link from
completing upon clicking. Designing with JavaScript http://www.webcoder.com/
<a href="normal.htm" onclick="return Ask the JavaScript Pro http://www.inquiry.com/techtips/js_pro/
false">Click here, it won't work!</a> WebMonkey http://hotwired.lycos.com/webmonkey/programming/javascript/
Yahoo
By returning false, we prohibit the action from completing! http://dir.yahoo.com/Computers_and_Internet/Programming_Languages/JavaScript/

Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 117 Dr. Osmar R. Zaane, 2001-2006 Web-based Information Systems University of Alberta 118

Das könnte Ihnen auch gefallen