0% found this document useful (0 votes)
1 views83 pages

L5. Java Script For Validation Form

Uploaded by

hrgaming1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views83 pages

L5. Java Script For Validation Form

Uploaded by

hrgaming1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Web Application Development (IT093IU)


Assoc. Prof. Nguyen Van Sinh
Email: nvsinh@[Link]
(Semester 1, 2025-2026)
JavaScript
⚫ Generating HTML Dynamically
⚫ Monitoring User Events
⚫ Basic JavaScript Syntax
⚫ Applications - using JavaScript to:
⚫ Customize web pages
⚫ Make pages more dynamic
⚫ Validate data forms
⚫ Manipulate HTTP cookies
⚫ Interact with and control frames
⚫ Control applets and call Java from JavaScript
⚫ Access JavaScript from Java
Generating HTML dynamically
⚫ Idea
⚫ Script is interpreted as page is loaded and used
[Link] or [Link] to insert
HTML at the location the script occurs
⚫ Template
...
<BODY>
Regular HTML
<SCRIPT TYPE="text/javascript">
[Link](‘Hello Sinh’);
</SCRIPT>
More Regular HTML
</BODY>

3
A simple script
<HTML>
<HEAD>
<TITLE>First JavaScript Page</TITLE>
</HEAD>

<BODY>
<H1>First JavaScript Page</H1>

<SCRIPT TYPE="text/javascript">
<!--
[Link]("<HR>");
[Link]("Hello World Wide Web");
[Link]("<HR>");
// -->
</SCRIPT>

</BODY>
</HTML>

4
Simple script, result

5
Extracting information with JavaScript
<HTML>
<HEAD>
<TITLE>Extracting Document Info with
JavaScript</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<H1>Extracting Document Info with JavaScript</H1>
<HR>

<SCRIPT TYPE="text/javascript">
<!--

function referringPage() {
if ([Link] == 0) {
return("<I>none</I>");
} else {
return([Link]);
}
}

6
Extracting document infor with JavaScript
...
[Link]
("Document Info:\n" +
"<UL>\n" +
" <LI><B>URL:</B> " + [Link] + "\n" +
" <LI><B>Modification Date:</B> " + "\n" +
[Link] + "\n" +
" <LI><B>Title:</B> " + [Link] + "\n" +
" <LI><B>Referring page:</B> " + referringPage() +
"\n" +
"</UL>");
[Link]
("Browser Info:" + "\n" +
"<UL>" + "\n" +
" <LI><B>Name:</B> " + [Link] + "\n" +
" <LI><B>Version:</B> " + [Link] + "\n"
+
"</UL>");
// -->
</SCRIPT>
<HR>
</BODY>
</HTML>

7
Extracting document infor with JavaScript,
Result

8
Multi-Browser compatibility
⚫ Use Language Attribute
<SCRIPT LANGUAGE="JavaScript">
<!-- languageVersion = "1.0"; // -->
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.1">
<!-- languageVersion = "1.1"; // -->
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.5">
<!-- languageVersion = "1.5"; // -->
</SCRIPT>
Note: Don’t include that attribute TYPE="text/javascript”
⚫ Use Vendor/Version Info
⚫ [Link]
⚫ [Link]
Monitoring user events

⚫ Use Various “onFunction” Attributes


⚫ onClick
⚫ onLoad
⚫ onMouseOver
⚫ onFocus
⚫ etc.

10
User events, example
<HTML>
<HEAD>
<TITLE>Simple JavaScript Button</TITLE>
<SCRIPT TYPE="text/javascript">

function dontClick() {
alert("I told you not to click");
}

</SCRIPT>
</HEAD>

<BODY BGCOLOR="WHITE">
<H1>Simple JavaScript Button</H1>

<FORM>
<INPUT TYPE="BUTTON"
VALUE="Don't Click Me"
onClick="dontClick()">
</FORM>
</BODY>
</HTML>

11
User events, result

12
JavaScript syntax: dynamic typing

⚫ Idea
⚫ Like Lisp, values are typed, not variables
⚫ A value is only checked for proper type
when it is operated upon
⚫ Example

var x = 5; // int
x = 5.5; // float
x = "five point five"; // String

13
JavaScript syntax: function declarations
⚫ Declaration Syntax
⚫ Functions are declared using the function
reserved word
⚫ The return value is not declared, nor are the
types of the arguments

⚫ Examples:
function square(x) {
return(x * x);
}

function factorial(n) {
if (n <= 0) {
return(1);
} else {
return(n * factorial(n - 1));
}
}
14
JavaScript syntax: function declarations
⚫ First Class Functions
• Functions can be passed and assigned to
variables
• Example
var fun = [Link];
alert("sin(pi/2)=" + fun([Link]/2));

15
JavaScript syntax: Objects and Classes
⚫ Fields Can Be Added On-the-Fly
⚫ Adding a new property (field) is a simple matter
of assigning a value to one
⚫ If the field doesn’t already exist when you try to
assign to it, JavaScript will create it
automatically.
⚫ For instance:

var test = new Object();


test.field1 = "Value 1"; // Create field1
property
test.field2 = 7; // Create field2 property

16
JavaScript syntax: Objects and Classes
⚫ You Can Use Literal Notation
⚫ You can create objects using a shorthand
“literal” notation of the form
{ field1:val1, field2:val2, ..., fieldN:valN }
⚫ For example, the following gives equivalent
values to object1 and object2
var object1 = new Object();
object1.x = 3;
object1.y = 4;
object1.z = 5;
object2 = { x:3, y:4, z:5 };

17
JavaScript syntax: Objects and Classes
⚫ The "for/in" Statement Iterates Over
Properties
⚫ JavaScript, unlike Java or C++, has a construct
that lets you easily retrieve all of the fields of an
object
⚫ The basic format is as follows:
for(fieldName in object) {
doSomethingWith(fieldName);
}
• Also, given a field name, you can access the field
via object["field"] as well as via [Link]

18
Field iteration, example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>For/In Loops</TITLE>

<SCRIPT TYPE="text/javascript">
<!--

function makeObjectTable(name, object) {


[Link]("<H2>" + name + "</H2>");
[Link]("<TABLE BORDER=1>\n" +
" <TR><TH>Field<TH>Value");
for(field in object) {
[Link] (" <TR><TD>" + field +
"<TD>" + object[field]);
}
[Link]("</TABLE>");
}
// -->
</SCRIPT>
19
Field iteration, example
...
</HEAD>
<BODY BGCOLOR="WHITE">
<H1>For/In Loops</H1>

<SCRIPT TYPE="text/javascript">
<!--

var test = new Object();


test.field1 = "Field One";
test.field2 = "Field Two";
test.field3 = "Field Three";
makeObjectTable("test", test);

// -->
</SCRIPT>

</BODY>
</HTML>

20
Field iteration, result

The for/in statement iterates over object properties

21
JavaScript syntax: Objects and Classes
⚫ A “Constructor” is Just a Function that Assigns to “this”
• JavaScript does not have an exact equivalent to Java’s
class definition
• The closest you get is when you define a function that
assigns values to properties in the this reference
• Calling this function using new binds this to a new
Object
• For example, following is a simple constructor for a Ship
class
function Ship(x, y, speed, direction){
this.x = x;
this.y = y;
[Link] = speed;
[Link] = direction;
}
22
Constructor, example
var ship1 = new Ship(0, 0, 1, 90);
makeObjectTable("ship1", ship1);

23
JavaScript syntax: Objects and Classes

⚫ Methods Are Function-Valued


Properties
⚫ No special syntax for defining methods
of objects
⚫ Instead, you simply assign a function to
a property

24
Class methods, example
⚫ Consider a version of the Ship class that includes
a move method
function degreesToRadians(degrees) {
return(degrees * [Link] / 180.0);
}
function move() {
var angle = degreesToRadians([Link]);
this.x = this.x + [Link] *
[Link](angle);
this.y = this.y + [Link] *
[Link](angle);
}
function Ship(x, y, speed, direction) {
this.x = x;
this.y = y;
[Link] = speed;
[Link] = direction;
[Link] = move;
}

25
Class methods, result
var ship1 = new Ship(0, 0, 1, 90);
makeObjectTable("ship1 (originally)", ship1);
[Link]();
makeObjectTable("ship1 (after move)", ship1);

26
JavaScript syntax: Objects and Classes
⚫ Arrays: for the most part, you can use arrays in JavaScript a lot
like Java arrays.
⚫ Here are a few examples:
var squares = new Array(5);
for(var i=0; i<[Link]; i++) {
vals[i] = i * i;}
// Or, in one fell swoop:
var squares = new Array(0, 1, 4, 9, 16);
var array1 = new Array("fee", "fie", "fo", "fum");
// Literal Array notation for creating an
array.
var array2 = [ "fee", "fie", "fo", "fum" ];
⚫ Behind the scenes, however, JavaScript simply represents
arrays as objects with numbered fields
⚫ You can access named fields using either [Link]
or object["field"], but numbered fields only via
object[fieldNumber]

27
Array, example
var arrayObj = new Object();
arrayObj[0] = "Index zero";
arrayObj[10] = "Index ten";
arrayObj.field1 = "Field One";
arrayObj["field2"] = "Field Two";

makeObjectTable("arrayObj", arrayObj);

28
Application:
Adjusting to the browser window size
⚫ Browser introduced the [Link]
and [Link] properties
⚫ Lets you determine the usable size of the current browser
window
⚫ Refer:
[Link]

29
Determining browser size, example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>Strawberries</TITLE>
<SCRIPT TYPE="text/javascript">

function image(url, width, height) {


return('<IMG SRC="' + url + '”’ + ' WIDTH=' + width +
' HEIGHT=' + height + '>');
}

function strawberry1(width) {
return(image("[Link]", width,
[Link](width*1.323)));
}

function strawberry2(width) {
return(image("[Link]", width,
[Link](width*1.155)));
}

</SCRIPT>
</HEAD>

30
Determining browser size, example
...

<SCRIPT TYPE="text/javascript">

var imageWidth = [Link]/4;


var fontSize = [Link](7,[Link]([Link]/100));

[Link]
('<TABLE>\n' +
' <TR><TD>' + strawberry1(imageWidth) + '\n' +
' <TH><FONT SIZE=' + fontSize + '>\n' +
' "Doubtless God <I>could</I> have made\n' +
' a better berry, but doubtless He\n' +
' never did."</FONT>\n' +
' <TD>' + strawberry2(imageWidth) + '\n' +
'</TABLE>');
</SCRIPT>
<HR>

Strawberries are my favorite garden crop; a fresh ...


</BODY>
</HTML>

31
Determining browser size, results

32
Application:
Using JavaScript to make pages dynamic

⚫ Modifying Images Dynamically


⚫ The [Link] property
contains an array of Image objects
corresponding to each IMG element in
the current document
⚫ To display a new image, simply set the
SRC property of an existing image to a
string representing a different image
file

33
Modifying images, example
⚫ The following function changes the first
image in a document
function changeImage() {
[Link][0].src = "images/new-
[Link]";
}
⚫ Referring to images by name is easier:
<IMG SRC="[Link]" NAME="cool"
WIDTH=75 HEIGHT=25>
function improveImage() {
[Link]["cool"].src = "way-
[Link]";
}

34
Modifying images:
A clickable image button, example
<SCRIPT TYPE="text/javascript">
<!--
imageFiles = new Array("images/[Link]",
"images/[Link]",
"images/[Link]",
"images/[Link]");
imageObjects = new Array([Link]);
for(var i=0; i<[Link]; i++) {
imageObjects[i] = new Image(150, 25);
imageObjects[i].src = imageFiles[i];
}
function setImage(name, image) {
[Link][name].src = image;
}

35
Modifying images:
A clickable image button, example
function clickButton(name, grayImage) {
var origImage = [Link][name].src;
setImage(name, grayImage);
var resetString =
"setImage('" + name + "', '" + origImage + "')";
setTimeout(resetString, 100);
}
// -->
</SCRIPT>

</HEAD>
...
<A HREF="[Link]"
onClick="clickButton('Button1', 'images/Button1-
[Link]')">
<IMG SRC="images/[Link]" NAME="Button1"
WIDTH=150 HEIGHT=25></A>

<A HREF="[Link]"
onClick="clickButton('Button2', 'images/Button2-
[Link]')">
<IMG SRC="images/[Link]" NAME="Button2"
WIDTH=150 HEIGHT=25></A>
...
36
Highlighting images under the mouse,
Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>High Peaks Navigation Bar</TITLE>
<SCRIPT TYPE="text/javascript">
<!—
// Given "Foo", returns "images/[Link]".
function regularImageFile(imageName) {
return("images/" + imageName + ".gif");
}
// Given "Bar", returns "images/[Link]".
function negativeImageFile(imageName) {
return("images/" + imageName + "-[Link]");
}
37
Highlighting images under the mouse,
Example
// Cache image at specified index. E.g., given index 0,
// take imageNames[0] to get "Home". Then preload
// images/[Link] and images/[Link].

function cacheImages(index) {
regularImageObjects[index] = new Image(150, 25);
regularImageObjects[index].src =
regularImageFile(imageNames[index]);
negativeImageObjects[index] = new Image(150, 25);
negativeImageObjects[index].src =
negativeImageFile(imageNames[index]);
}

imageNames = new Array("Home", "Tibet", "Nepal",


"Austria", "Switzerland");
regularImageObjects = new Array([Link]);
negativeImageObjects = new Array([Link]);

// Put images in cache for fast highlighting.


for(var i=0; i<[Link]; i++) {
cacheImages(i);
}

38
Highlighting images under the mouse,
Example
...
function highlight(imageName) {
[Link][imageName].src =
negativeImageFile(imageName);
}
function unHighlight(imageName) {
[Link][imageName].src =
regularImageFile(imageName);
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<TABLE BORDER=0 WIDTH=150 BGCOLOR="WHITE"
CELLPADDING=0 CELLSPACING=0>
<TR><TD><A HREF="[Link]"
TARGET="Main"
onMouseOver="highlight('Tibet')"
onMouseOut="unHighlight('Tibet')">
<IMG SRC="images/[Link]"
NAME="Tibet"
WIDTH=150 HEIGHT=25 BORDER=0>
</A>
...

39
Highlighting images under the mouse, Result

40
Making pages dynamic: moving layers
⚫ Netscape 4 introduced “layers” – regions
that can overlap and be positioned
arbitrarily
⚫ JavaScript 1.2 lets you access layers via
the [Link] array, each element
of which is a Layer object with properties
corresponding to the attributes of the
LAYER element
⚫ A named layer can be accessed via
[Link]["layer name"] rather
than by using an index, or simply by using
[Link]

41
Moving layers, example
⚫ Descriptive overlays slowly “drift” to final
spot when button clicked
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>Camps on K-3</TITLE>
<SCRIPT TYPE="text/javascript">
function hideCamps() {
// Netscape 4 document model.
[Link]["baseCamp"].visibility = "hidden";
[Link]["highCamp"].visibility = "hidden";
// Or [Link] = "hidden";
}
function moveBaseCamp() {
[Link](1, 3);
if ([Link] < 130) {
setTimeout("moveBaseCamp()", 10);
}
}

42
Moving layers, example
function showBaseCamp() {
hideCamps();
baseCamp = [Link]["baseCamp"];
[Link](0, 20);
[Link] = "show";
moveBaseCamp();
}

function moveHighCamp() {
[Link](2, 1);
if ([Link] < 110) {
setTimeout("moveHighCamp()", 10);
}
}

function showHighCamp() {
hideCamps();
highCamp = [Link]["highCamp"];
[Link](0, 65);
[Link] = "show";
moveHighCamp();
}
</SCRIPT>

43
Moving layers, example.
<LAYER ID="highCamp" PAGEX=50 PAGEY=100
VISIBILITY="hidden">
<TABLE>
<TR><TH BGCOLOR="WHITE" WIDTH=50>
<FONT SIZE="+2">High Camp</FONT>
<TD><IMG SRC="images/[Link]">
</TABLE>
</LAYER>
<LAYER ID="baseCamp" PAGEX=50 PAGEY=100
VISIBILITY="hidden">
<TABLE>
<TR><TH BGCOLOR="WHITE" WIDTH=50>
<FONT SIZE="+2">Base Camp</FONT>
<TD><IMG SRC="images/[Link]">
</TABLE>
</LAYER>

<FORM>
<INPUT TYPE="Button" VALUE="Show Base Camp"
onClick="showBaseCamp()">
<INPUT TYPE="Button" VALUE="Show High Camp"
onClick="showHighCamp()">
<INPUT TYPE="Button" VALUE="Hide Camps"
onClick="hideCamps()">
</FORM>
44
Moving layers, result

45
Moving layers, result

46
Application:
Using JavaScript to validate data forms
⚫ Accessing Forms
⚫ The [Link] property contains an array of
Form entries contained in the document
⚫ As usual in JavaScript, named entries can be
accessed via name instead of by number, plus
named forms are automatically inserted as properties
in the document object, so any of the following
formats would be legal to access forms
var firstForm = [Link][0];
// Assumes <FORM NAME="orders" ...>
var orderForm = [Link]["orders"];
// Assumes <FORM NAME="register" ...>
var registrationForm = [Link];

47
Application:
Using JavaScript to validate CGI forms
⚫ Accessing Elements within Forms
⚫ The Form object contains an elements property
that holds an array of Element objects
⚫ You can retrieve form elements by number, by
name from the array, or via the property name:

var firstElement = [Link][0];


// Assumes <INPUT ... NAME="quantity">
var quantityField =
[Link]["quantity"];
// Assumes <INPUT ... NAME="submitSchedule">
var submitButton = [Link];

48
Checking form values individually, example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>On-Line Training</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
...
// When the user changes and leaves textfield, check
// that a valid choice was entered. If not, alert
// user, clear field, and set focus back there.

function checkLanguage() {
// or [Link]["langForm"].elements["langField"]
var field = [Link];
var lang = [Link];
var prefix = [Link](0, 4).toUpperCase();
if (prefix != "JAVA") {
alert("Sorry, '" + lang + "' is not valid.\n" +
"Please try again.");
[Link] = ""; // Erase old value
[Link](); // Give keyboard focus
}
}
49
Checking form values individually, example.
// -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<H1>On-Line Training</H1>

<FORM ACTION="cgi-bin/registerLanguage" NAME="langForm">


To see an introduction to any of our on-line training
courses, please enter the name of an important Web
programming language below.
<P>
<B>Language:</B>
<INPUT TYPE="TEXT" NAME="langField"
onFocus="describeLanguage()"
onBlur="clearStatus()"
onChange="checkLanguage()">
<P>
<INPUT TYPE="SUBMIT" VALUE="Show It To Me">
</FORM>

</BODY>
</HTML>

50
Checking form values individually, results

51
Checking values when form is submitted,
example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>Camp Registration</TITLE>
<SCRIPT TYPE="text/javascript">

function isInt(string) {
var val = parseInt(string);
return(val > 0);
}

function checkRegistration() {
var ageField = [Link];
if (!isInt([Link])) {
alert("Age must be an integer.");
return(false);
}
...
// Format looks OK. Submit form.
return(true);
}
</SCRIPT>

52
Checking values when form is submitted,
example.
<BODY BGCOLOR="WHITE">
<H1>Camp Registration</H1>

<FORM ACTION="cgi-bin/register"
NAME="registerForm"
onSubmit="return(checkRegistration())">
Age: <INPUT TYPE="TEXT" NAME="ageField"
onFocus="promptAge()"
onBlur="clearStatus()">
<BR>
Rank: <INPUT TYPE="TEXT" NAME="rankField"
onFocus="promptRank()"
onBlur="clearStatus()">
<BR>
Serial Number: <INPUT TYPE="TEXT" NAME="serialField"
onFocus="promptSerial()"
onBlur="clearStatus()">
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit Registration">
</FORM>

</BODY>
</HTML>

53
Checking values when form is submitted,
results

54
Application: using JavaScript to store and
examine cookies

⚫ Using [Link]
⚫ Set it (one cookie at a time) to store values

[Link] = "name1 = val1";


[Link] = "name2 = val2; expires = ”
someDate;
[Link] = "name3=val3; path=/;
domain = [Link]";

⚫ Read it (all cookies in a single string) to access


values

55
Application:
using JavaScript to store and examine cookies

⚫ Parsing Cookies
function cookieVal(cookieName, cookieString) {
var startLoc = [Link](cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = [Link]("=", startLoc);
var endLoc = [Link](";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = [Link];
}
return([Link](sepLoc+1, endLoc));
}
56
Exercise
⚫ Using JavaScript to:
⚫ Write a webpage to solve equation
(ex: quadratic equation)
⚫ Allow to input a, b, c from user,
⚫ Check input validation (e.g. they are integer)
⚫ Display results when user click on button “Compute”
on the web UI (e.g. they are float) as follows:

57
Cookie, example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>Widgets "R" Us</TITLE>
<SCRIPT TYPE="text/javascript">

function storeCookies() {
var expires = "; expires=Monday, 01-Dec-01 23:59:59
GMT";
var first = [Link];
var last = [Link];
var account = [Link];
[Link] = "first=" + first + expires;
[Link] = "last=" + last + expires;
[Link] = "account=" + account + expires;
}

// Store cookies and give user confirmation.


function registerAccount() {
storeCookies();
alert("Registration Successful.");
}

58
Cookie, example.
function cookieVal(cookieName, cookieString) {
var startLoc = [Link](cookieName);
if (startLoc == -1) {
return(""); // No such cookie
}
var sepLoc = [Link]("=", startLoc);
var endLoc = [Link](";", startLoc);
if (endLoc == -1) { // Last one has no ";"
endLoc = [Link];
}
return([Link](sepLoc+1, endLoc));
}
function presetValues() {
var firstField = [Link];
var lastField = [Link];
var accountField = [Link];
var cookies = [Link];
[Link] = cookieVal("first", cookies);
[Link] = cookieVal("last", cookies);
[Link] = cookieVal("account", cookies);
}
</SCRIPT>

59
Cookie, example.
</HEAD>
<BODY BGCOLOR="WHITE" onLoad="presetValues()">

<H1>Widgets "R" Us</H1>

<FORM ACTION="servlet/[Link]"
NAME="widgetForm"
onSubmit="storeCookies()">
First Name: <INPUT TYPE="TEXT" NAME="firstField">
<BR>
Last Name: <INPUT TYPE="TEXT" NAME="lastField">
<BR>
Account Number: <INPUT TYPE="TEXT" NAME="accountField">
<BR>
Widget Name: <INPUT TYPE="TEXT" NAME="widgetField">
<BR>
<INPUT TYPE="BUTTON" VALUE="Register Account"
onClick="registerAccount()">
<INPUT TYPE="SUBMIT" VALUE="Submit Order">

</FORM>
</BODY>
</HTML>

60
Cookie, example.

61
Email validation: an example
Application:
Using JavaScript to interact with frames
⚫ Idea
⚫ The default Window object contains a
frames property holding an array of
frames (other Window objects) contained
by the current window or frame.
⚫ It also has parent and top properties
referring to the directly enclosing frame or
window and the top-level window,
respectively.
⚫ All of the properties of Window can be applied
to any of these entries.

63
Displaying a URL in a particular frame. Ex
⚫ [Link]

<HTML>
<HEAD>
<TITLE>Show a URL</TITLE>
</HEAD>

<FRAMESET ROWS="150, *">


<FRAME SRC="[Link]" NAME="inputFrame">
<FRAME SRC="[Link]" NAME="displayFrame">
</FRAMESET>

</HTML>

64
Displaying a URL in a particular frame, ex:
⚫ [Link]
<HTML>
<HEAD>
<TITLE>Choose a URL</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function showURL() {
var url = [Link];
// or [Link]["displayFrame"].location = url;
[Link] = url;
}

function preloadUrl() {
if ([Link] == "Netscape") {
[Link] =
"[Link]
} else {
[Link] =
"[Link]
}
}
...

65
Displaying a URL in a particular frame, ex:
⚫ [Link], cont.
<BODY BGCOLOR="WHITE" onLoad="preloadUrl()">
<H1 ALIGN="CENTER">Choose a URL</H1>

<CENTER>
<FORM NAME="urlForm">
URL: <INPUT TYPE="TEXT" NAME="urlField" SIZE=35>
<INPUT TYPE="BUTTON" VALUE="Show URL"
onClick="showURL()">
</FORM>
</CENTER>
</BODY>
</HTML>

66
Displaying a URL in a particular frame,
Result.

67
Displaying a URL in a particular frame,
Result.

Java Script
68
Giving a frame the input focus, example.
⚫ If JavaScript is manipulating the frames, the fix is
easy: just add a call to focus in showUrl:
function showURL() {
var url = [Link];
[Link] = url;
// Give frame the input focus
[Link]();
}
⚫ Fixing the problem in regular HTML documents is a
bit more tedious
⚫ Requires adding onClick handlers that call focus to
each and every occurrence of A and AREA that includes
a TARGET, and a similar onSubmit handler to each FORM
that uses TARGET

69
Application: accessing Java from JavaScript
⚫ Idea
⚫ Netscape 3.0 introduced a package called
LiveConnect that allows JavaScript to talk to Java
and vice versa
⚫ Applications:
⚫ Calling Java methods directly.
⚫ In particular, this section shows how to print debugging
messages to the Java console
⚫ Using applets to perform operations for JavaScript
⚫ In particular, this section shows how a hidden applet
can be used to obtain the client hostname, information
not otherwise available to JavaScript
⚫ Controlling applets from JavaScript
⚫ In particular, this section shows how LiveConnect
allows user actions in the HTML part of the page to
trigger actions in the applet
70
Application: accessing Java from JavaScript
⚫ Calling Java Methods Directly
⚫ JavaScript can access Java variables and
methods simply by using the fully qualified name.
For instance:

[Link]("Hello Console");

⚫ Limitations:
⚫ Can’t perform operations forbidden to applets
⚫ No try/catch, so can’t call methods that throw
exceptions
⚫ Cannot write methods or create subclasses

71
Controlling applets from javaScript, example
⚫ [Link], cont.
<BODY BGCOLOR="#C0C0C0">
<H1>Mold Propagation Simulation</H1>

<APPLET CODE="[Link]" WIDTH=100 HEIGHT=75>


</APPLET>
<P>
<APPLET CODE="[Link]" WIDTH=300 HEIGHT=75>
</APPLET>
<P>
<APPLET CODE="[Link]" WIDTH=500 HEIGHT=75>
</APPLET>

<FORM>
<INPUT TYPE="BUTTON" VALUE="Start Simulations"
onClick="startCircles()">
<INPUT TYPE="BUTTON" VALUE="Stop Simulations"
onClick="stopCircles()">
</FORM>

</BODY>
</HTML>

72
Controlling applets from javaScript, example
⚫ [Link]
<HTML>
<HEAD>
<TITLE>Mold Propagation Simulation</TITLE>
<SCRIPT TYPE="text/javascript">

function startCircles() {
for(var i=0; i<[Link]; i++) {
[Link][i].startCircles();
}
}

function stopCircles() {
for(var i=0; i<[Link]; i++) {
[Link][i].stopCircles();
}
}
</SCRIPT>
</HEAD>

73
Controlling applets from javaScript, example
⚫ [Link]
public class RandomCircles extends Applet
implements Runnable {
private boolean drawCircles = false;

public void startCircles() {


Thread t = new Thread(this);
[Link]();
}

public void run() {


Color[] colors = { [Link], [Link],
[Link], [Link] };
int colorIndex = 0;
int x, y;
int width = getSize().width;
int height = getSize().height;

Graphics g = getGraphics();
drawCircles = true;
...

74
Controlling applets from javaScript, example
⚫ [Link]
while(drawCircles) {
x = (int)[Link](width * [Link]());
y = (int)[Link](height * [Link]());
[Link](colors[colorIndex]);
colorIndex = (colorIndex + 1) % [Link];
[Link](x, y, 10, 10);
pause(0.1);
}
}

public void stopCircles() {


drawCircles = false;
}

private void pause(double seconds) {


try {
[Link]((int)([Link](seconds * 1000.0)));
} catch(InterruptedException ie) {}
}
}

75
Controlling applets from JavaScript, results

76
Accessing JavaScript from Java
⚫ Steps
1. Obtain and install the JSObject class
2. Import it in your applet
import [Link]
3. From the applet, obtain a JavaScript reference
to the current window
JSObject window = [Link](this);

77
Accessing JavaScript from Java.
4. Read the JavaScript properties of interest
– Use getMember to access properties of the
JSObject
JSObject someForm =
(JSObject)[Link]("someFormName
");
5. Set the JavaScript properties of interest
– Use setMember to set properties of the JSObject
[Link]("bgColor", "red");
6. Call the JavaScript methods of interest
String[] message = { "An alert message" };
[Link]("alert", message);
[Link]("alert(’An alert message’)");
7. Give the applet permission to access its Web
page
<APPLET CODE=... WIDTH=... HEIGHT=...
MAYSCRIPT>
...
</APPLET>

78
Matching applet background
with web-page, example
⚫ [Link]
import [Link];
import [Link].*;
import [Link];

public class MatchColor extends Applet {


public void init() {
JSObject window = [Link](this);
JSObject document =
(JSObject)[Link]("document");
// E.g., "#ff0000" for red
String pageColor =
(String)[Link]("bgColor");
// E.g., parseInt("ff0000", 16) --> 16711680
int bgColor =
[Link]([Link](1,
7), 16);
setBackground(new Color(bgColor));
}
}

79
Matching applet background
with web-page, example

⚫ [Link]

<HTML>
<HEAD>
<TITLE>MatchColor</TITLE>
</HEAD>
<BODY BGCOLOR="RED">
<H1>MatchColor</H1>
<APPLET CODE="[Link]"
WIDTH=300 HEIGHT=300 MAYSCRIPT>
</APPLET>
</BODY>
</HTML>

80
Applet that controls HTML form values,
example
⚫ See on-line
example for
[Link]

81
Summary

⚫ JavaScript permits you to:


⚫ Customize Web pages based on the situation
⚫ Make pages more dynamic
⚫ Validate HTML form input
⚫ Manipulate cookies
⚫ Control frames
⚫ Integrate Java and JavaScript
⚫ Refer from the textbooks and internet
⚫ Exercises: page 57, review many exercises
in JavaScript (check validation form)
[Link]

82
Exercise: Design a form as follows: write a JS
function to require filling the form

You might also like