L5. Java Script For Validation Form
L5. Java Script For Validation Form
International University
School of Computer Science and Engineering
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
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:
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">
<!--
<SCRIPT TYPE="text/javascript">
<!--
// -->
</SCRIPT>
</BODY>
</HTML>
20
Field iteration, result
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
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 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">
[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>
31
Determining browser size, results
32
Application:
Using JavaScript to make pages dynamic
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]);
}
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:
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>
</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
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;
}
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()">
<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>
</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>
<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;
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);
}
}
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];
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
82
Exercise: Design a form as follows: write a JS
function to require filling the form