Tutorial 10: Programming with JavaScript - CS Division - Home
Welcome to Javascript Tutorial
Transcript of Welcome to Javascript Tutorial
-
8/3/2019 Welcome to Javascript Tutorial
1/30
So far we have learned to create web pages that are static -- you could only display texts
and images. JavaScript is a scripting language engineered byNetscape, and later reverse-
engineered by Microsoft. It lets you create buttons, text fields, text boxes, etc, thusmaking your web pages more interesting and useful.
Client-Side vs. Server-Side JavaScript
Web browsers have built-in JavaScript interpreter -- this means that the browser can
interpret a chunk of JavaScript code and execute the command. This is known as 'client-
side' JavaScript. The 'client' is the user of a website. For example, if you're shopping on
Amazon.com, you are the client, and Amazon is the server. What you will learn in this
tutorial is the client-side JavaScript.
In many cases, client-side JavaScript is not enough. Many online shopping sites, such as
Amazon, will greet you with your name if you are revisiting. This can be done with'server-side' JavaScript, which can access the server's database to look up your name,
address, shopping history, etc. When you request a web page that contains server-sideJavaScript, the server executes the script and sends back the resulting document to theclient.
Here is a simple HTML document with client-side JavaScipt:
1
2
34
567
8
910
11
12
JavaScript Example
-
8/3/2019 Welcome to Javascript Tutorial
2/30
Example 1: You can write any text in the HTML document using JavaScript.
Line 1-5, 11, 12: These are just the HTML codes for heading and body.
Line 6 & 10: JavaScript code must be surrounded by the tag. This lets thebrowser know that whatever is inside the tag must be interpreted by the JavaScript
interpreter. Language="JavaScript" is needed since there are other types of scriptinglanguages that can be embedded in HTML documents. For example, IE has imbedded
VBScript interpreter.
Line 7 & 9: Old browsers do not have a JavaScript interpreter built in. Thus it is a good
idea to surround the JavaScript code with the comment tags ( ) in order toavoid errors in loading these documents. Old browsers will see the code as a comment
and ignore it; new browsers will properly interpret the code.
Line 8: This is the JavaScript code that writes "Hello, World!" in your HTML document.In programming, each command line is called astatement. Statements must be separatedby semicolon, unless you have a line break. So the semicolon in our example could have
been omitted.
Object-Oriented Language
JavaScript is an object-oriented language. This means that a chunk of code is created as
an 'object' with certain behaviors that are specified by the coder. In our Hello,World!
example, 'document' is an object, 'write' is a methodof the object that writes the text inthe parenthesis on the document. Methods arefunctions that are defined in an object.
If this sounds confusing to you, think of an object as a car. Say the car's name is 'Rock'.
Rock has a method called 'forward' that turns the wheel to let you drive forward. If you
want to tell Rock to turn left, you would say, Rock.forward("left");. If you want to gobackward, you would say Rock.backward("straight");.
-
8/3/2019 Welcome to Javascript Tutorial
3/30
Objects also have 'properties'. If you want a red car, you would specify the color by
Rock.bodyColor = "red";. If you want leather seats, you can specify it by
Rock.interior = "leather";. Thus 'bodyColor' and 'interior' would be Rock's properties.
Exercise 1: One of the properties of the Document object is 'bgColor', which is forbackground colors. Modify the code in example 1 so that the background of thedocument is yellow. You may change the text if you wish.
Back to the TopTo the Table of Contents
Chapter 1: Basics
Button Events and Functions
When you click on a button, move the mouse over an image, etc, you are generatingevents. You can capture these events and produce useful results with JavaScript.
1
23
4
5
67
8910
11
12
1314
15
1617
Button Event Example
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_intro.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.htmlhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_intro.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.html -
8/3/2019 Welcome to Javascript Tutorial
4/30
Example 1.1: When you click on the button, a dialog box appears with the message.
To create a button, type
. This
line needs to be surrounded by a FORM tag, which is used in when you want to process
more complicated codes. For now, just include it and don't worry about it.
Button text shows up on the button (e.g. "Click on me"). In the example, we want some
action to occur when the user clicks on the button. Thus the command 'onClick' is
required. This is one of the manyEvent Handlers that come with JavaScript. EventHandlers look for any event that the user produces and carries out necessary operations.
In this case, we use 'onClick' event handler to call up a function named 'writeMessage'.
Line 6-8 is a very simple function -- it has only one statement. A function is a chunk of
code that can be called up however many times you want. Notice that it is in the HEADsection of the HTML document. Usually the functions are written in the head section,
and they are called up in the BODY section when you want to use it. Here is the formatto create a function:
function functionName( optional_argument1, optional_argument2, etc ) {
...content of the function...
}
Here, 'function' is a keywordreserved for JavaScript. It lets the interpreter know that
what is coming up is a function definition. Note that JavaScript is case-sensitive. So you
cannot type 'Function' -- you will be given an error message and the code will not work!Then you specify the name of the function, which needs to be all one word, i.e., no space
is allowed. Following the function name is the parentheses containing optional argument
list. In our example, we had empty parenthesis, meaning the function takes in noargument. Arguments are variables that are passed into the function by the caller. You
will learn about them more in the next example.
-
8/3/2019 Welcome to Javascript Tutorial
5/30
Function definition needs to be enclosed in curly brackets, just as in the example. 'alert'
is a built-in JavaScript method that displays the text that you put in the parentheses. The
text should be surrounded by quotation marks. Finally, be sure to end each statementwith a semicolon. Although JavaScript lets you get away with not having one, it is a bad
habit.
Now that you learned how to define a function, here is how you call up a function. In our
example, 'writeMessage' function takes in no argument. Thus
onClick="writeMessage()" calls up the function whenever the button is pressed.
Variables; If & If-else statements
Suppose you want to build a stupid calculator. It adds two numbers passed into it, then
adds 3 to the result. If the answer is greater than 10, it is displayed the result in the alert
box. Otherwise, nothing happens. Here is how:
123
4
56
7
89
10
11
12
13
14
1516
17
18
19
Button Event Example 2
-
8/3/2019 Welcome to Javascript Tutorial
6/30
Example 1.2: When the first button is pressed, nothing happens. When the second one is pressed, a dialog
box with the answer (18) pops up.
Here we introduce variables. You've probably used this name in a math class, and theywork in similar ways. Variables let you store literals, which are numbers, strings, etc.
You cannot use the keywords as your variables. In the 'add' function, we have three
variables: x,y, and answer. X and y are arguments. Notice that we called the functions
with the following lines: "add(2,3)" and "add(5,10)". Here we are pasing in twoarguments, since we defined the function to take in two arguments. They are used in any
way we want in the function. The third variable, answer, holds the final value of x+y+3.If you simply write x+y+3; you lose your result. Since we want to use the result to test if
it is greater than 10, we assign the result to the variable answer.
So, in line 7, we have declared the variable answerand store the result of the addition.
To see if our answer is greater than 10, we use the 'if' statement. The syntax is:
if (something is true)this command line is carried out;
// ...otherwise it is skipped.
In JavaScript (as well as in Java and C++), the double slash sign (//) is used as
comments. Other comparisons you can perform include:
< (less than)
== (equals. note that this is double '=' sign)
!= (not equal)
-
8/3/2019 Welcome to Javascript Tutorial
7/30
= (greater than or equal to).
A statement similar to ifis the if-else statement. The syntax is:
...if (condition)
this command line is carried out when condition is true;
elsethis command line is carried out when condition is false;
For the above example, we could have written:
function add(x, y){
var answer = x + y + 3;
if (answer > 10)
alert(answer);else
alert("Answer less than or equal to ten.");}
Exercise 2: Random Number Generator
Make two buttons, one that says "Your Lucky Number" and theother "Your Unlucky Number". When the user presses the"lucky" button, a dialog box should pop out saying "Here is
your lucky number: #", where # should be some randomnumber. If the other button is clicked, the dialog boxshould say, "Oops, don't use this number today: #". Bothnumbers should be randomly generated and have a valuebetween 1 and 99. Both buttons have to be handled by ONLYONE function.
Generating random integers:
-Math.random() generates a random number between 0.0 and1.0.-Math.round(x) rounds the number x to the nearest integer.
Combining strings:
- if you typevar strOne = "hello"; then strOne now holds thestring "hello".- if you type alert(strOne + ", everyone!"); then the resultingmessage is "hello, everyone!"
-
8/3/2019 Welcome to Javascript Tutorial
8/30
The page should look like this:
For-Loops
If you want to repeat a task several times, you can either write out all the commands, oryou can be smart and use a for-loop. For-loop has the following format:
for ( varany = start_int; ending condition;steps ){
for-loop body
}
Here is a concrete example:
for( var num=0; num
-
8/3/2019 Welcome to Javascript Tutorial
9/30
Link Events are almost the same as button events, except that the event is generated when
the user does something to a link, not a button. You simply create a link and insert an
event handler, similar to the button examples.
1
23
4
5
6
7
8
9
10
11
1213
14
15
16
17
18
1920
Link Event Example
TouchHere
Example 1.3: To see the working page of the code above, click here.
In the example above, we have created a link in line 18. When HREF value is set to "#",the link destination is set to the top of the same page. You've seen this kind of syntax inthe HTML tutorial, in the anchoring section. Instead of looking for mouse clicks, we
would like to generate an event when the mouse pointer is simply placed over the link.
So 'onMouseOver' event handler is used. The third handler is called 'onMouseOut()',
which generates an event when the mouse is over a link/button/image and exits the area.
Let's analyze line 6 - 13, the JavaScript code. The 'greet' function is defined in line 11-
13. It takes in no argument, and it simply calls up the 'alert' method to pop up a dialog
box whenever the mouse is on the link. The message displayed in the dialog box is moreinteresting this time. First notice the plus signs to concatenate three differentstrings.
Strings are characters surrounded by quotation marks. JavaScript provides many ways ofmanipulating strings. When you write, alert("Hello"+", World!");, you are
concatenating two strings. The result is exactly the same as alert("Hello, World!");.
Also notice that we are calling the 'getCount' function while concatenating strings. When
getCount() is called in line 12, line 7-10 is executed. This function adds one to variable
'counts' each time it is called, then it returns that variable to the caller. Thus when youfirst touch the link, you call greet(), which in turn calls getCount(). Then getCount() sets
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex4.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex4.htm -
8/3/2019 Welcome to Javascript Tutorial
10/30
'counts' to 1 (because count is 0 in the beginning) and returns the value of 'counts'. Next
time getCount() is called, 'counts' becomes 2, and the function returns 2. This is your
first counter!
You can make a function return anything you want. You can return literals, strings,
arrays, and any other object. Remember, however, that when 'return' line is reached in afunction, the function returns the appropriate item and immediately terminates. Suppose
you write 'return;' between line 7 and 8. Then the function starts, sees the return line, andterminates without ever reaching the rest of the code. You can return nothing if what you
wish is just to terminate the function.
Notice that when you hit the Refresh button in the browser, the counter starts back from
0. It is important to realize thescope of variables. In this case, 'counts' is aglobal
variable. What this means is that the variable is initialized when the page is loaded, and
its lifespan continues as long as the page is kept loaded. So when you refresh the page,
'counts' is re-initialized to 0. You can also have localvariables, as opposed to global
ones. Suppose you tweak example 4 so that line 6-10 looks liks this:
function getCount(){
var counts=0;
counts = counts + 1;
return counts;
}
The only thing changed is that 'counts' is initialized inside 'getCount' function definition.
But this changes the entire functionality. Now variable 'counts' is initialized to 0 every
time the function is called. So every time you touch the link, all you will see is "Hello.You've touched me 1 times.". So local variables are alive as long as the function is alive.
Exercise 3: Factorials and For-Loops
Make 5 links, each saying "Factorial of x", where x is 5,10, 15, 20, and 25. When you click on each link, a diaologbox pops up with the correct answer. You should write afunction that takes in an integer, calculates factorials,and returns an answer. Since we want the function to begeneral, you should test that the integer is less than orequal to 50 (we don't want to overload the system) and
greater than or equal to 0. If the numbers are not inrange, the dialog box should say "Invalid number". You cancreate another link that passes in 60 to test that yourfunction works properly.
Factorials: Written as N!, where N is a whole number, N! =N * (N-1) * (N-2) * ... * 2 * 1. Thus 3! = 6. Note that 0!is mathematically defined to be 1.
-
8/3/2019 Welcome to Javascript Tutorial
11/30
Summary
Button & Link Handlers: onClick(), onMouseOver(), onMouseOut().Programming concepts: Functions, Variables, Return values, Variable scope.
Programming techniques: If, If-else, For-loop.
Back to the TopTo the Table of Contents
Last Updated September 9, 2000 by Grace Pok
Last Updated September 9, 2000 by Grace Pok
Chapter 2: Window Events
If you are reading this tutorial from a monitor, you are looking at a Window. Your webbrowser window probably has menu bars, navigation bars, status bar, and of course, the
tutorial content. So Window is where you display your HTML document and JavaScript
elements. JavaScript provides you with many tools for manipulating windows andcapturing window events.
The Client-Side Object Hierarchy
Now that you've learned the gist of JavaScript, it's time to learn how the Object modelworks in JavaScript. In the introduction we've introduced the Document object. There
are many more objects that are pre-defined in the client-side JavaScript. The list below
shows the hierarchy.
Current Window (this is the global object)
self, window, parent, top (various Window objects) navigator (Navigator object)
o plugins[] (array of Plugin objects)o mimeTypes[] (array of MimeType objects)
frames[] (array of Window objects) location (Location object)
history (History object) document (Document object)
o forms[] (array of Form objects)
elements[] -->array of HTML Form element objects, which are: Button Checkbox FileUpload Hidden
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_tutorial1.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.htmlhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_tutorial1.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.html -
8/3/2019 Welcome to Javascript Tutorial
12/30
Password Radio Reset Select
options[] (array of Option objects)
Submit Text TextArea
o anchors[] (array of Anchor objects)
o links[] (array of Link objects)o images[] (array of Image objects
o applets[] (array of applets)
o embeds[] (array of embedded objects)
As you can see, Document object is only one of the six objects that belong to the current
Window object. The Window object acts as your global variable. So when you use thedocument.write("Hello, World!"); method, it is automatically assumed that you are
referring to the current window that is opened. So far you have seen Document and
Button objects. We will cover more of the objects mentioned above, but not all of them.If you'd like to explore JavaScript in detail, you are encouraged to buy a reference book
(recommended:JavaScript: The Definitive Guide from O'Reilly) or consult an online
reference.
Changing the Window's Location
Here is the simplest example of manipulating a window with JavaScript. We simply
open a different page in the current window.
You are simply resetting the location property of the Window. You can also use
self.location. Here is how to change the location with a button in HTML form:
1
2
-
8/3/2019 Welcome to Javascript Tutorial
13/30
3
4
Page"
onClick = "window.location ='page.html';">
Note that in line 3, we have page.html in single quotation marks. Since the value of
onClickneeds to be in quotation, and the window.location's value also needs to be in
quotation, we alternate between single and double quotes. If you write,
"window.location = "page.html";">, it will be seen as two strings ("window.location=
"and ";") and you will receive an error.
To change the location through a link, type
Type Link Label Here
By specifying javascript: in the HREF value, you can carry out any JavaScript.
Opening New Windows
In Chapter 4 of the HTML tutorial (Link), you've learned out to open a link in a newwindow. Not only does JavaScript let you do the same, you also have more control over
how the new window will look. Take a look at the example below.
12
3
45
6
7
89
10
11
1213
Window Opening Example
-
8/3/2019 Welcome to Javascript Tutorial
14/30
14
15
Click to Open
a New Window
Example 2.1: When the link is clicked, a window 480x400 pixels pops up. Take a look at the example
here.
The link calls up the function 'openWindow()'. The function is defined in line 6-8. Line
7 creates a new Window object (by window.open). The general format is:
window.open("page.html", "target_name", "properties");. It is crucial that you do not
include any return carriages (return key or enter key) here. Line 7 is actually all in one
line. The three strings that are passed in the window.open method are the arguments that
are needed to control the new window:
page.html --> Address of the web page that will be displayed in the new window.
target_name --> The window's target name. This is mainly used for frames, etc. If youare not familiar with TARGET tags, refer to HTML Tutorial Chapter 4.
properties --> You can manipulate the properties of the new window with the following
7 fields:
width, height --> window pixel sizestoolbar, menubar, status, scrollbars, resizable --> values are either 'yes' or 'no'.
Exercise 4: Window Clock
Create a HTML page with a button that says "TIME". Whenclicked, a new window should pop up that is 300 x200, withno toolbars, no menubars, no statusbar, and no scrollbars.Through the "Date" object, you can check for the user'stime. The window should display the time of the user'scomputer. If the hour is between 8am to 6pm, the backgroundof the new window should be "cyan" and the text in black.Otherwise, the window should be "black" background with
white letters.
Date Object: "new Date()" returns the current date object ofthe user's computer. The "getHours()" function, when operatedon an date object, returns the values between 0 (midnight)and 23 (11p.m.).
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex5.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex5.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/html_tutorial4.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex5.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex5.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/html_tutorial4.htm -
8/3/2019 Welcome to Javascript Tutorial
15/30
History
With JavaScript, you can make your own 'Back' and 'Forward' navigation buttons. They
work through the history object, which stores the URL history of the browser and lets you
go back and forth. Three methods ofhistory object are mentionable.
history.back()and history.forward()--these work in the same manner as
the 'back' and 'forward' buttons on your browser
history.go(x)-- this method takes in an integer, which indicates the relative
position in the History list of the URL to be visited. For example, history.go(-2) has thesame effect as pressing the 'back' button twice, and history.go(1) same as the 'forward'
button.
The example below shows you how to implement these methods:
1
2
34
5
6
7
8
910
11
12
1314
15
16
17
1819
2021
22
23
History Example
Click to go
-
8/3/2019 Welcome to Javascript Tutorial
16/30
back
Click to goforward
Example 2.2: Playing with history object. Click here to see the example in a browser.
Notice in the example above that line 14&15 serve the same functionality as line 20 and21. The 'move' function that we have defined is more versatile, because we can pass in
any number to go forward or backward however many steps we desire. Although this
function has no extra purpose than to call the history.go() method, one can easily imagineadding other statements in the function to execute more interesting stuff (such as
displaying a dialog box, etc).
Window Loading and Unloading
To call up a JavaScript function as a document is loaded/unloaded onto a window, you
can use onLoad and onUnload event handlers. This section applies both to windows andto frames, since they are virtually the same.
There are many cases when you want to call up a JavaScript function when the page is
loaded. For example, you might want to check which browser the viewer is using. Since
Netscape and Internet Explorer have different HTML/JavaScript interpretor, you mightwant to test the browser, then load appropriate documents accordingly.
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex7.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex7.htm -
8/3/2019 Welcome to Javascript Tutorial
17/30
The onLoad/onUnload handlers are inserted in the BODY tag or the FRAMESET tag:
For window without frames,
For window with frames,
Here is an example of testing browsers.
1
23
4
5
6
7
8
9
1011
12
13
1415
16
1718
19
Browser Testing
Testing Browsers
You can modify this script and use it to direct your JavaScript
visitors in one direction, and other visitors elsewhere.
Example 2.3: Testing browsers.Click here to see the example in a browser.
In line 7 and 8, we obtain the name and version of the browser through the navigator
object. The properties are stored in thisapp and thisversion, which are displayed through
the alert method.
Example: This demonstrates further onLoad and onUnload events.
Remote Control Example
You can create a small window with various links that will let you navigate on a big
window. Take a look at this example:
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex8.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex8.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex8.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_onUnload.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex8.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_onUnload.htm -
8/3/2019 Welcome to Javascript Tutorial
18/30
1
2
34
5
6
78
9
1011
12
1314
........
.......
1b2b
3b
4b5b
6b
7b8b
9b10b
11b12b
13b
14b15b
.......
Remote Control
Navigate through JavaScript Tutorials
Tutorial 1
Tutorial 2
Tutorial 3
........
Example 2.4: Here we show some parts of the code for Remote Control. The first row (line 1-15) is for the
page that calls the remote window. The second row (line 1b-15b) is for the remote control. Click here to see
the example in a browser.
Let's focus on line 1-14. This is the HTML file that opens up the remote control page. Inline 14, we call up remoteStart function on loading the page. The remoteStart
function creates a new window and opens it (line 5), assigning the window as 'remote'. In
line 6, we assign the URL address of the remote window. This is supposed to be the
FULL address, not relative one, due to a bug in Netscape 2. In JavaScript, if a browser
window creates a new window, the original window is referred to as the new window's
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex9.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex9.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex9.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex9.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS1-2/js_ex9.htm -
8/3/2019 Welcome to Javascript Tutorial
19/30
opener. Some versions of Netscape don't do this automatically, so we do it automatically,
as shown in line 7. Line 8 simply assigns the opener.name as "opener_window".
Line 1b through 15b show how the remote control works. It has several links that lets younavigate through our JavaScript tutorial, chapter 1-4. The links call up the go functioin in
line 3b. This function takes in a string called url and sets the value ofopener.location.href as the url. Here we use relative addresses.
Exercise 5: Your Own Remote Control
Here you will modify exercise 9 of the HTML tutorial (whereyou made frames with links). Modify your myJava.htm page sothat when you click on the "My JavaScript Page" link, aremote control pops up. Hint: use "onLoad" handler. Theremote control should have links to all the exercises
you've done (1-4) for this JavaScript tutorial (hope youdidn't delete them!). When the links are clicked, thedestination pages should show up in the main frame of theoriginal window. Also note that the rest of the links onthe left frame of should still work as in the originalversion --> Pay attention to line 10 in example 2.4!
The results should be something like this:
-
8/3/2019 Welcome to Javascript Tutorial
20/30
'myJava' page and the remote control pops up when My JavaScript Page link is clicked.
Exercise 2 pops up when "Ex 2"
link of the remote control is
clicked.
Summary
Object Hierarchy
Location
Opening New WindowsHistory
onLoad/onUnload
-
8/3/2019 Welcome to Javascript Tutorial
21/30
Back to the Top
To the Table of Contents
Last Updated September 9, 2000 by Grace Pok
Chapter 3: Forms
When you build a web page that requires JavaScript, in many cases you'll be using a form
and its elements: text inputs, radio buttons, select menus, etc. Here you will learn how tocreate forms, retrieve data from them, and how to create functions using the data.
Creating Forms
In chapter 1 you've already encountered the FORM tag, which surrounded Button
objects. So far we had no use for it.
1
2
3
45
6
78
9
Creating Forms
Example 3.1: A form containing a text field and a button.
The example above creates a form named "simple_form" with a text field and a button.Whenever you refer to anything in JavaScript, you do so by name. Thus the NAME tag
(line 4 & 5) is important.
Do you recall our analogy of objects with a car? In there we talked about how to access
various properties of the car "Rock". To get to the interior property, we simply had towrite Rock.interior. Thus to retrieve the user's input from the text field, you simply
write document.simple_form.t_box1.value. Likewise, you refer to the form
by document.simple_form.
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_tutorial2.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.htmlhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_tutorial2.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.html -
8/3/2019 Welcome to Javascript Tutorial
22/30
Form Inputs
Form inputs are the information that the user provides, such as text in text area, button
clicks, etc. Next example demonstrates how to handle inputs.
1
23
4
5
67
8
910
11
1213
14
1516
17
18
1920
21
22
......
Please enter your name below and click SUBMIT.
......
Example 3.2: A form with a text field and a button. When the button is clicked, a new window pops up.
Click here to see the example in a browser.
The extra feature added in this example is the onClick handler in line 21 and the
handleButton function in line 3-12.
When you refer to the form using its full name, you would write document.box. But ifyou are working inside the form, i.e. if you are inside the "box" form tags, then you can
refer to it as this. It's like calling yourself as "I", not by your name. The use ofthis
may seem confusing in the beginning, but if you want to learn JavaScript further, you'd
probably want to familiarize yourself with it.
In line 21, you will notice that this.form is passed in as the argument. Here, this
refers to the button (not the form, since we are inside the button INPUT tag), and form
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS3-4/js_ex11.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS3-4/js_ex11.htm -
8/3/2019 Welcome to Javascript Tutorial
23/30
refers to the form in which the button is contained. Thus this.form is equivalent to
document.box, the form's name.
In line 3, we declare a function handleButton. The argument it accepts is named
input, which we expect to be a form. In line 5, we want to extract the text inside the
text field. We refer to the text by input.name_field.value and assign it to avariable name. Then we open a new window and call it disp. This is almost the same as
the remote control example we've seen in chapter 2.
In line 9, we concatenate several strings to write a short message in a new windowthrough the document.write function. So if the user types in "Jones", the new window
displays "Hello, Jones. Welcome to the show.".
Exercise 6: Login Page
Create a form with three text fields, one labeled "FirstName", another "Last Name", and the third as "Password".Create a login button and a reset button. For example, ifthe user types in "John", "Doe", and "111" in thetextfields respectively, a new window should pop up saying,"Hello, John Doe. Thank you for loggin in." If the usertypes in anything other than 111 as the password, the newwindow should say somthing like, "Incorrect password.Please try again.". When the user presses the reset button,all the textfields should become empty.
Password Field: By setting "TYPE = password" for thepassword textfield, you can have the asterisk (*)characters echo the actual characters.
Validating Form Inputs
Let's go back to the previous example. Suppose this is a very simple guest book, and you
want the user to enter the first and last name. Since the name is going into your database,you don't want to accept blank entries and incomplete entries. You can write a JavaScript
function that will validate entries before you accept them.
Take a look at Example 3.3. Here, the user is asked to give the name and the phonenumber. The phone number is checked for the xxx-xxx-xxxx format.
Here is a portion of the BODY section:
Name:
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS3-4/js_ex12.htmhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/Figures%20JS3-4/js_ex12.htm -
8/3/2019 Welcome to Javascript Tutorial
24/30
Phone:
When the button is clicked, we call checkForm(this.form), where 'this.form' is
equivalent to 'document.box'. Here is the code forcheckForm function:
1
23
4
5
67891011
function checkForm(input){
var n = input.name_field.value;var p = input.phone.value;
if( check(n,p) ){
disp =window.open("","window1","width=300,height=200,resizeable=yes");if(disp.opener == null) disp.opener = window;disp.opener.name = "disp_opener";disp.document.write("Hello, "+n+". Welcome to our store.");disp.document.write("
Here is your phone number: "+p+".");disp.document.write("
Thank you for your business.");disp.document.close();}
}
In line 1, we have the usual function declaration. In line 2-3, we obtain the user's input in
the name_field and phone textfields and assign them to variable n and p, respectively. Inline 4, we have an if-statement, where we call function check(n,p). As we will see soon,
check takes in two strings. It checks to see that the first one is not empty, and that the
second one is in the form of phone number by calling another function. Only when both
strings are in the correct format, does it return true. So if check(n,p) returns true, line 5-11are executed -- this is almost the same as example 3.2.
Here is the code for the check function:
-
8/3/2019 Welcome to Javascript Tutorial
25/30
1
2
3
45
6
7
89
10
function check(name, pn){
if (name=="" || name==" "){
alert("Plase enter your name.");
document.box.name_field.focus();return false;
}if(!phoneNumCheck(pn)){
alert("The phone number must be in the following format: 222-222-2222");document.box.phone.focus();return false;
}
return true;
}
In line 2, we check for two condition: if name is equal to "" (thus blank entry) OR if
name is equal to " "(thus a space), then line 3-5 is executed. Here, '||' is the OR operator.
The OR operator (||) returns true if one of the conditions are true. The opposite is the
AND operator (&&). Another logical operator is the NOT operator (!).
In line 3, we alert the user to enter the name. In line 4, focus() brings the cursor to the
specified HTML element, i.e., document.box.name_field. Then we return false, andthe function terminates by returning to the caller (checkForm function).
Suppose the user enters something in the name_field textfield. Next we check for the
phone number's syntax in line 6. Here we see the NOT operator. As we will see shortly
again, phoneNumCheck returns true if the argument is in the form of a phone number. So
we want to check ifphoneNumCheck(pn) returns false. So ifphoneNumCheck is NOT
true, i.e. false, then line 7-9 is executed.
Finally, let's analyze the phoneNumCheck function.
-
8/3/2019 Welcome to Javascript Tutorial
26/30
1
23
45
6789
101112
13
1415
16
function phoneNumCheck(number){
//check for blank entryif (number=="" || number==" ") return false;
//check for the xxx-xxx-xxxx formatif ( number.indexOf("-")!=3 || number.indexOf("-",4)!=7 ||number.length!=12)return false;
//we extract all the numbers from the entry, excluding the hyphensvar num = number.substr(0,3);num = num.concat(number.substr(4,3));num = num.concat(number.substr(8,4));
//now we check that only digits are enteredvar c;for( i=0; i
-
8/3/2019 Welcome to Javascript Tutorial
27/30
var charThree =strTest.indexOf("m");
So, if the index of first hyphen is not equal to 3 (!=3), or if that of second hyphen is not 7,
we return false. Also if the length of number is not 12, then we also return false (You can
access the length property of any string by StringName.length).
In line 7-9, we extract only the digits of the phone number.
String.substr(start_index, how_many) is a built-in JavaScript function. It extracts
"how_many" characters from the String, starting from the "start_index". Say that the user
entered 234-443-1423 as the phone number. After line 7, num is assigned "234". In line 8,
number.substr(4,3) returns "443", which is concatenated to the previous "234" by
String.concat function. Suppose we simply wrote num = number.substr(4,3) in
line 8. Then num would become "443", not "234443" as we intend to do. Finally we
extract the last four digits of the phone number in line 9 (num would be "2344431423").
Now we want to check that the phone number has only digits. Line 11-15 accomplishes
this. Line 11 declares variable c, which will be used in the for-loop. The method
num.charCodeAt(i) in line 14 returns the ascii value of the i-th character ofnum. In
ascii, character 0-9 has the value of 48-57. So we know that ifc is not between 48 and 57,
the phone number has characters other than digits. If so, we return false in line 15. For asimple table of ascii codes, take a look at:
http://members.tripod.com/~plangford/index.html.
When all these tests are satisfied, the function returns true and terminates (line 16).
Other HTML Form Elements
Check Boxes
Syntax:
Usage: If you want the box to be checked when the form is loaded, type in the optionalCHECKED. You can also pass in a value if desired. To test if the check box is checked, test
Checkbox.checked property. It returns true if the checkbox is checked.
Checkbox.value property returns the value that was passed in from the input.
Radio Buttons
Syntax:
Usage: Radio buttons are used when you want an exclusive selection. Usually you have
several buttons in a group, and when one is checked, the other becomes unchecked. So all
http://members.tripod.com/~plangford/index.htmlhttp://members.tripod.com/~plangford/index.html -
8/3/2019 Welcome to Javascript Tutorial
28/30
the buttons in the group are given the same NAME and differs in their VALUE. The
syntax for retrieving checked state and value is the same as check boxes.
Lists/Menus
Syntax:
Option 1Option 2
Usage: You can have as many options you want in the list. If you want the user to be able
to choose more than one option, type MULTIPLE in the SELECT tag.
Exercise 7: Subscription Form
Make a web page that looks like this:
-
8/3/2019 Welcome to Javascript Tutorial
29/30
The important requirements of the design:
all the text fields
at least three radio buttons in the second column
a sign up button. reset button optional
use a table to organize your form
Of the functionality:
If any text field is not filled out, an alert boxshould pop up notifying the user.
Check for the five-digit format of the zip code andalert the user appropriately.
Check for the email address format, i.e., it shouldcontain '@' character somewhere in the input.
The cursor should be returned to the first text field
where the error occured. Only when the form is filled out completely and
correctly (well, almost) should it be accepted.
After the user clicks on "Sign Me Up" button, a new windowshould pop up confirming the sign-up. For example, if theuser's information was
John Doe, CPU BOX 273333, Rochester, NY 14627,[email protected], Weekly subscription,
The new window should say:
Thank you, John Doe.
Our newsletter will be mailed to you WEEKLY to this address:
CPU BOX 273433Rochester, NY 14627
Have a nice day!
Back to the Top
To the Table of Contents
Conclusion
This tutorial should have given you a good feel about what JavaScript is all about.
However, we've only scratched the surface. It would take a lot more than three chapters
http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_tutorial3.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.htmlhttp://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/HTML/js_tutorial3.htm#%23http://www.cs.rochester.edu/u/www/u/pawlicki/ECOMM/tem/index.html -
8/3/2019 Welcome to Javascript Tutorial
30/30
to cover all the topics. Just in case you would like to learn more about this fun language,
here is a short list of books/resources.
Designing with JavaScript, by Nick Heinle, published by O'Reilly-- this is a good place start for non-progammers who want to pick up JavaScript quickly
JavaScript, the Definitive Guide, by David Flanagan, published by O'Reilly
-- this book covers JavaScript very thoroughly, from the core JavaScript to client-side
JavaScript. It may be hard for beginners to pick up, but it is a good reference book.
JavaScript Guide by Netscape(http://developer.netscape.com/docs/manuals/communicator/jsguide4/index.htm)
-- this online guide gives you good overview of JavaScript as well as references.
Last Updated September 9, 2000 by Grace Pok
http://developer.netscape.com/docs/manuals/communicator/jsguide4/index.htmhttp://developer.netscape.com/docs/manuals/communicator/jsguide4/index.htm