JS Tutorial
JS Tutorial
Programmers Tutorial
This tutorial contains only a portion of the material covered in
WestLake’s hands-on JavaScript class.
Form Validation.....................................................................................................
Validating Numeric Data ....................................................................................................................................
The String Object and Form Validation...............................................................................................................
The onSubmit Event Handler and Form Validation..............................................................................................
With JavaScript, a Web page can react to what the user is doing. Images can swap when the mouse moves over
them, form elements can influence each other on the fly, and calculations can be made without having to resort to a
CGI script. In fact, a great deal can be accomplished with very little programming. There is no need for a fancy
computer, complex software, or access to a Web server; all the work can be done and tested right on the local
computer.
http request
http response
Browser/Client Server
When a client makes a http: request (requests an HTML page) to the server, the server checks
the url to verify that the file exists. If so, an http: response (an HTML page) is provided to the
browser and the page displays in the client window. Otherwise, an error message saying the
file could not be found results. Any JavaScript on the page downloads with the HTML.
http: response
and once again returned to the browser.
Debugging JavaScript
Learning any language naturally entails making errors. Fortunately, there are tools available to help debug, locate
and fix problems. At the simplest level, browsers have error messages that will help identify and alert you to your
errors.
In Netscape 4.x, an error console is available by typing javascript: into the address bar of the browser.
Although these debugging tools are useful to pinpoint the problem, they may not always lead to the needle in the
haystack. Further exploration and troubleshooting may be required.
Every JavaScript object has associated properties and methods. A property is a characteristic that can be
manipulated or changed about the object. For example, the document object has a background color. The
background color (bgColor) is considered to be a property of the document object.
A method, on the other hand, is an action that an object can perform. The document object can write content into
the document via the write() method. So, JavaScript can change the characteristics of an object (via its properties)
as well as ask an object to perform specific tasks (via its methods).
In addition to properties and methods, JavaScript objects have event handlers that trigger the changes to occur.
Different event handlers exist for different objects, and are treated as an attribute of the specific object. For
example, some event handlers for a link include onClick, onMouseOver, and onMouseOut.
As the course progresses, many of JavaScript objects (as well as their associated properties, methods, and event
handlers) will be discussed in detail.
As an example, consider the following button. Remember, the form’s button has no innate actions:
<form>
This is my form:
<input type="button" value="Click Here!">
</form>
Adding an event handler (followed by an action or set of actions) to the button can create a dynamic change of the
page when that button is triggered:
Notice that the button’s onClick event handler triggers the action, but that the action can then alter any of
JavaScript’s objects.
document.bgColor='red';
• Invoke a function
JavaScript Syntax
Before looking at JavaScript objects in more detail, it is important to become familiar with the rules of syntax.
JavaScript’s syntax is modeled after programming languages such as Java and C++. Some basic syntax guidelines
follow:
• JavaScript is case-sensitive.
• Whitespace is ignored, so spaces, tabs, and new-lines can be used to indent the code
to your liking. It is important, however, to ensure there are no spaces between a
method and its parentheses. Also, do not break a statement across two lines if the
first line is long enough to hold the entire statement, as this will result in JavaScript
errors.
• Any literal value (such as a text string) must be put in a set of quotes. In addition,
multiple sets of quotes must be nested appropriately.
• Certain keywords have been reserved in JavaScript for specific purposes. Keep this
in mind as your knowledge of JavaScript increases. The following keywords have
been reserved, and may not be used for anything other than their intended purpose.
Reserved keywords include the following:
window
Accessing the appropriate object entails stepping down the object hierarchy by use of dot notation. Simply work
your way through the hierarchy, placing a dot (a period) before each new child object that you reference. Notice
that some of the objects are followed by brackets, indicating that there may be more than one of that type of object
on the page. For example, the code to access an image follows:
window.document.images[1];
More specifically, the above code references the second image in a page. The brackets at the end of the image
object indicate the object is part of an array (a list). In this case, the array is a list of images in the document. The
number in the brackets refers to the image’s placement (index) in the code. Because JavaScript starts counting with
zero, the code for the first image listed in the html page would be as follows:
window.document.images[0];
window.document.images[1];
It is important to know that each browser and each browser version may have different Document Object Model
hierarchies. Throughout most of this class, the hierarchy used is cross-browser compatible; however, as you further
explore the JavaScript language, you will find that these different DOMs must be accounted for.
Naming Objects
Although accessing an object can be done by the item's placement in the JavaScript array, doing so can be
cumbersome. Instead, naming the object (by using the name attribute) provides a more intuitive means for
referencing an object.
Any html tag can be named via the name attribute. For example, the following code names an image chicken:
window.document.images[0];
the object can be referenced by its name, as provided by the name attribute.
window.document.chicken;
Providing names for objects makes accessing those objects through the DOM much more intuitive.
window.document.bgColor='red';
window.document.write('Hello World');
Notice both properties and methods are simply appended to the end of the object’s name and separated from its
parent by a period. However, notice the syntax differences between changing a property and invoking a method.
To change a property, start by accessing the object, its property, and then set the property equal to a new value. All
properties are set in this manner:
window.document.bgColor='red';
A method, on the other hand can do something, and is always followed by a set of parentheses. If additional
information for that method is needed, that additional information is contained in the parentheses. For example the
code that writes “Hello World” into the document follows:
window.document.write('Hello World');
Methods are always followed by a set of parentheses, regardless of whether those parentheses contain further
parameters. Inside of the parentheses, any argument that is not a variable name or numerical value should be placed
in quotes to indicate that it is a text string or string literal.
Object Description
navigator The navigator object provides properties that expose information about the
current browser to JavaScript scripts.
Object Description
String The String object enables programs to work with and manipulate strings
of text, including extracting substrings and converting text to uppercase or
lowercase characters.
Date The Date object allows programs to work with and manipulate the current
date. The object includes methods for calculating the difference between
two dates and working with times.
Math The Math object allows programs to work with and manipulate numerical
values generated by the Math object. For example, the Math object's
properties and methods enable programmers to round numbers as well as
generate random numbers.
Both the String and Date objects will be discussed in detail.
<html>
<head>
<title>Background Color Change</title>
</head>
<body>
<center>
<form>
<input type="button" value="Clic k Me!"
onClick="window.document.bgColor='Red';">
</form>
</center>
</body>
</html>
JavaScript has been added to a button. When invoked by a click of the button, the code changes the background
color. Notice that the event handler (onClick) is treated as if it is an attribute of the <input> tag. The event
handler is followed by an equal sign and a JavaScript statement nested in a set of quotes.
The background color (document.bgColor) can be assigned any valid color name, or a hexadecimal RGB triplet.
For a listing of valid colors and corresponding triplets, consult http://www.lynda.com/hexh.html.
Clicking on each button changes the background of the page to the specified color.
To complete this exercise:
1. From the JStutorial .zip file you downloaded, drag the icon for exercise1-temp.html to the
Notepad icon on the Desktop. This will open the file in Notepad.
2. The exercise file appears as follows. Please complete the missing sections, as indicated by
bold <!--comments-->.
<html>
<head>
<title>Color Picker</title>
</head>
<body>
<center>
<form>
<p><input type="button" value="Red"
onClick="window.document.bgColor='red'"></p>
<p><!--ADD A BUTTON THAT (WHEN CLICKED) CHANGES THE BACKGROUND COLOR TO
GREEN--></p>
<p><!--ADD A BUTTON THAT (WHEN CLICKED) CHANGES THE BACKGROUND COLOR TO
BLUE--></p>
<p><!--ADD A BUTTON THAT (WHEN CLICKED) CHANGES THE BACKGROUND COLOR TO
WHITE--></p>
</form>
</center>
</body>
4. Open the file in the browser and test each button. If there are errors, bring Notepad back to
the foreground, edit the code, and save it. Then, bring the browser back to the foreground
and reload the page. Repeat this step until all errors have been resolved.
<html>
<head>
<title>Color Picker</title>
</head>
<body>
<center>
<form>
<p><input type="button" value="Red"
onClick="window.document.bgColor='Red'"></p>
<p><input type="button" value="Green"
onClick="window.document.bgColor='Green'" ></p>
<p><input type="button" value="Blue"
onClick="window.document.bgColor='Blue'"> </p>
<p><input type="button" value="White"
onClick="window.document.bgColor='White'"> </p>
</form>
</center>
</body>
</html>
Clicking each of the buttons invokes the alert(), prompt(), and confirm() methods, respectively. The code for this
page is as follows, and will be detailed further.
<html>
<head>
<title>Modal dialogs</title>
</head>
<body>
<center>
<form>
</form>
</center>
</body>
</html>
alert()
window.alert() displays a dialog with warning text and an OK button. The user must click OK before proceeding
further with the page. The alert() method takes one parameter: the message to display. For an example, take a look
at the JavaScript code for the alert() button's onClick event handler in dialogs.html:
window.alert('Ouch');
The above code invokes the following alert box when the button is clicked:
prompt()
window.prompt() displays a dialog that asks a question and provides a blank field for the user to fill in her answer.
OK and Cancel buttons are provided, and one must be clicked before the user may continue.
The window.prompt() method requires two parameters: the text for the message to display in the dialog and a default
entry (if any) for the field to display. For demonstration, examine the following code:
When invoked, the above code displays the following prompt dialog box:
Notice that the words WestLake Internet Training automatically appear in the field for the user. This can also be left
blank by leaving the set of quotes containing the second parameter empty:
confirm()
window.confirm() displays a message in a dialog box with both an OK and Cancel button. For example, the
following code:
The confirm() method requires only one parameter (the message that the dialog should display).
window.document.bgColor='red';
window.alert('Hello World');
you may opt to write:
document.bgColor='red';
alert('Hello World');
Nesting Quotes
The above examples of the window’s alert(), prompt(), and confirm() methods used single quotes inside the
parentheses. However, in some cases double-quotes may have worked just as well. The key lies in how the code
occurs in the page. For now, you only know how to invoke the code inline triggered by an object’s event handler
(such as onClick):
invokes two statements. The first statement changes the background color to red and the second displays an alert
dialog. It is a good idea to end all JavaScript statements with a semi-colon in the event that you later want to add
another statement.
Take note that the order of the actions will execute based on the order they are placed in the script. Although most
statements occur instantaneously, putting an alert() method first requires the user to click OK before any of the other
statements are executed.
<html>
<head>
<title>Mouse Movements</title>
</head>
<body>
Notice that the same object can have more than one event handler, and that each event handler
is treated as a separate attribute of the object's tag.
1. Open exercise2-temp.html in Notepad. This code has the same functionality of the code
completed in the last exercise:
<html>
<head>
<title>Color Picker</title>
</head>
<body>
<center>
<form>
<!--ADD AN ALERT TO EACH OF THE BUTTONS onClick EVENT HANDLERS BELOW. THE
ALERT SHOULD TELL THE USER THAT THE BACKGROUND HAS CHANGED TO THE
SPECIFIC COLOR-->
<p><input type="button" value="Red" onClick="document.bgColor='red'"></p>
<p><input type="button" value="Green"
onClick="document.bgColor='green'"></p>
</form>
</center>
</body>
</html>
2. Add a JavaScript statement that invokes an alert message to each of the buttons. Remember
to use the semi-colon to separate JavaScript statements.
3. Save the page and test each button in a browser . If one of your buttons does not work
properly, fix the code as needed. Be sure to save and refresh the page to test the latest
version.
• Add a link with both onMouseOver and onMouseOut events. This link should be
responsible for changing the background color when the mouse rolls over it, and
changing the background color to white when the mouse rolls off.
<html>
<head>
<title>Color Picker</title>
</head>
<body>
<center>
<form>
<p><input type="button" value="Red" onClick="document.bgColor='red' ;
alert('The background color has changed to red.'); "></p>
<p><input type="button" value="Green" onC lick="document.bgColor='green' ;
alert('The background color has changed to green.'); "></p>
<p><input type="button" value="Blue" onClick="document.bgColor='blue' ;
alert('The background color has changed to blue.'); "></p>
<p><input type="button" value="White " onClick="document.bgColor='white' ;
alert('The background color has changed to white.'); "></p>
</form>
</center>
</body>
</html>
<html>
<head>
<title>Functions</title>
<script language="JavaScript">
<!--
function ouchalert() {
alert('Ouch, that hurt!');
}
//-->
</script>
</head>
<body>
<center>
<p>Without a function:</p>
<hr>
<form>
<p>With a function:</p>
<p><input type="button" value="Eenie" onClick="ouchalert();"></p>
<p><input type="button" value="Meenie" onClick="ouchalert();" ></p>
<p><input type="button" value="Miney" onClick="ouchalert();" ></p>
</form>
</center>
</body>
</html>
All of the buttons have the same functionality, as they all result in the same alert:
However, whereas the first set of buttons' actions are coded inline with each HTML tag, the second set all call upon
the same function that then executes the alert:
<script language="JavaScript">
</script>
<script language="JavaScript">
<!--
statements to execute
//-->
</script>
This ensures browsers that do not support the language will ignore the code, and browsers that do support JavaScript
can still execute the code. The two slashes (//) prior to the closing html comment are single-line JavaScript comment
symbols. These are needed to tell JavaScript to ignore the closing piece of the html comment (- - >), as the - - code
is actually used to decrement a variable and will be intepreted as such without the single-line comments.
function function_name() {
statements to execute when function is called;
}
where function is a reserved term responsible for declaring a function, and function_name is the name given to the
function being declared. Although a function is named as the coder desires, all syntax rules (such as using
underscores instead of spaces and not using reserved terms) apply.
Notice that a set of parentheses immediately follows the function name. These parentheses are required and are used
to enclose additional information, just as a method’s set of parentheses encloses any required parameters. This will
be discussed in more detail later. For now, be sure to know that the parentheses are required syntax for both
declaring the function as well as calling the function.
The statements to be executed by the function are nested within the { and } characters. Although spaces are ignored,
writing functions in a standard format will quicken the debugging process. Standard notation is shown above.
<html>
</head>
<form>
<input type="button" value="Red"
onClick="flipcolor('red')" ><p>
</form>
</center>
</body>
</html>
Notice that the code is essentially the same as in the previous exercise, with the exception of the code in bold. The
code in bold adds two components:
• The function then passes that argument to the statements it executes. The function
receives the argument passed to it (in this case, a string of either 'red', 'green', 'blue',
or 'white') and assigns that argument to a local variable that can be used throughout
the function. In this example the variable mynewcolor stores the sent argument and
passes that argument throughout the function as needed:
function flipcolor(mynewcolor) {
document.bgColor = mynewcolor;
}
So, when the red button is clicked, 'red' is assigned the value of mynewcolor. When
the 'green' button is clicked, green is assigned to the value of mynewcolor, and so
forth. The new value of mynewcolor is then used throughout the function to change
the background of the page.
Passing arguments to a function makes the the function much more flexible.
function flipcolor(mynewcolor) {
alert("You just pressed the " + mynewcolor + " button!");
}
Notice that any text enclosed in pairs of quotes displays literally; the local variable that you want interpreted is not.
In addition, the text and the local variable are joined by the + operator, which concatenates the strings and the
variables into one seamless message. Anytime you want the value of a variable displayed in conjunction with a
string of text, it is necessary to join the pieces of the string with the variable using the concatenation (+) operator.
1. Open exercise3-temp.html in Notepad. You will be modifying the color picker to use
functions. The code is currently as follows and matches that of the code in the completed
version of the last exercise, with commented instructions for completing this exercise:
<html>
<head>
<title>Color Picker</title>
<!--
/*WRITE A FUNCTION CALLED flipandalert(). THIS FUNCTION SHOULD:
* ACCEPT ONE ARGUMENT AND STORE IT IN A VARIABLE CALLED color_value
* CHANGE THE BACKGROUND COLOR BASED UPON THE INFORMATION PASSED TO
color_value
* ALERT THE USER TO THE BACKGROUND CHANGE
<body>
<center>
<form>
<!--MODIFY THE FOUR BUTTONS BELOW SO THAT THEY CALL UP ON THE
flipandalert() FUNCTION AND PASS THE APPROPRIATE COLOR AS A STRING
LITERAL-->
<p><input type="button" value="Red" onClick="document.bgColor='red';
alert('The background color has changed to red.');"></p>
<p><input type="button" value="Green" onClick ="document.bgColor='green';
alert('The background color has changed to green.');"></p>
<p><input type="button" value="Blue" onClick="document.bgColor='blue';
alert('The background color has changed to blue.')"></p>
<p><input type="button" value="White" onC lick="document.bgColor='white';
alert('The background color has changed to white.')"></p>
</form>
</center>
</body>
</html>
2. Edit the script to declare a function named flipandalert(). Don’t forget to place the function
in <script>… </script> tags and html comment tags. Also, be sure to place the function in
the <head> of the document.
3. Create a local variable in the parentheses of the function. Name this variable color_value.
4. The function, flipandalert(), should execute two statements when called upon:
• The second action alerts the user to the page's change in background color.
5. Modify the buttons so that each onClick event handler calls the flipandalert() function and
sends the appropriate argument to that function.
6. Save the page and test it in a browser. If it is not working correctly, go back and fix the code
as needed.
• Modify the alert statement so that it displays “Red is a great background color”.
<html>
<head>
<title>Color Picker</title>
<script language="JavaScript">
<!--
function flipandalert(color_value) {
document.bgColor = color_value;
alert("The background color has ch anged to " + color_value +
".");
}
//-->
</script>
</head>
<body>
<center>
<form>
<p><input type="button" value="Red"
onClick="flipandalert('red');"></p>
</form>
</center>
</body>
</html>
• initiates a variable called first_name through the use of the reserved term var.
Variables in JavaScript should be declared the first time they are used by using the
reserved word var.
• stores the entered information in the variable named first_name. Names of variables
(also known as identifiers) can use numbers, letters, and underscores. The first
character of the name, however, cannot be a number.
JavaScript Data
Scalar variables can hold one of four types of data: a string, number, Boolean value (i.e., true or
false), or null.
The four types of data which a scalar variable can hold are described below:
var age;
age=25;
var firstname;
firstname = "Mickey";
var mouse;
mouse = true;
firstname = null;
Notice that the assignment (=) operator does not mean equal to in JavaScript. Instead, it is responsible for setting
the value of a variable. The first statement assigns the number 25 to the variable age. Notice that the number 25 is
not surrounded by quotes, therefore it is interpreted as a numerical value rather than a string.
The second statement assigns the string "Mickey" to the variable firstname. As the second statement illustrates,
anytime a string is assigned to a variable, it must be placed in quotation marks.
The third statement assigns the Boolean value true to the variable mouse. Again, true is not treated as a string
because it is not nested in quotation marks.
The fourth and final statement assigns null to firstname. null is a special value that deallocates the variable (which
previously held the value "Mickey") and frees the memory it occupied for later use.
Once variables are assigned a value, they can be used in other JavaScript statements in the page. For example, once
the first three statements above are executed, an alert() method could display a customized message dependent on
the values of those variables:
alert("Hello, " + firstname + ", you are " + age + " years old.");
Notice that quotes do not surround the variable names so that they are not treated as strings.
var age;
var firstname;
var mouse;
age = 25;
firstname = "Mickey";
mouse = true;
code could be condensed to:
age = 25;
firstname = "Mickey";
mouse = true;
The first statement declares all three variables at once, and the latter statements assign values to each variable.
Alternatively, the above code could be condensed by assigning the value in the declaration:
var age=25
To do anything with the entered information, however, the information must be stored in a variable. For example:
var first_name;
first_name = prompt("Please enter your first name:", "");
This statement prompts the user for his first name. When OK is pressed, the user’s entry is assigned to the
first_name variable. If the user clicks the Cancel button instead, the value null is assigned to the variable.
The above code can be condensed further into a statement that initiates the variable, prompts the user, and assigns
her entry to the initiated variable all within one line:
After entering the information and clicking OK, the page displays as follows:
In short, the user is prompted to enter her name upon loading the page. Her entered information is stored in a
variable and later used to display a custom alert message when the howdyalert() function is called. The JavaScript
code responsible for this follows:
<html>
<head><title>Assigning Prompt Data to a Variable</title>
<script language="JavaScript">
<!--
function howdyalert() {
alert("Hello, " + firstname + ", welcome to WestLake!");
}
//-->
</script>
</head>
<body>
<center>
<form>
<input type="button" value="Click me!" onClick=" howdyalert()">
</form>
</center>
</body>
</html>
This code brings up a very important fact about the placement of the <script></script> tags, and how that
placement controls when the JavaScript is executed. All code between the <script> and </script> tags, except for
code within functions, is executed immediately as it is loaded in the browser. Since the <script></script>
block is within the head, the statement:
1. Open exercise4-temp.html in Notepad. The code for this exercise is the same as the code in
the completed version of the last exercise:
<html>
<head>
<title>Color Picker</title>
<script language="JavaScript">
<!--
//PROMPT THE USER FOR HIS/HER FIRST NAME AND STORE IT IN A SCALAR
VARIABLE, firstname
function flipandalert(color_value) {
document.bgColor = color_value;
//MODIFY THE ALERT BELOW TO USE THE DATA STORED IN firstn ame TO
DISPLAY A CUSTOMIZED MESSAGE
alert("The background color has changed to " + color_value +
".");
}
//-->
</script>
</head>
<body>
<center>
<form>
<p><input type="button" value="Red" onClick="flipandalert('red');"></p>
<p><input type="button " value="Green"
onClick="flipandalert('green');"></p>
<p><input type="button" value="Blue" onClick="flipandalert('blue');"></p>
<p><input type="button" value="White"
onClick="flipandalert('white');"></p>
</form>
</center>
</body>
</html>
2. Create a variable called firstname that uses a prompt() method to request the user’s
information as soon as the page is requested. This variable should be placed in the <script>
4. Save the page and test it in a browser. If the page does not work, go back into the code and
make changes as necessary.
<html>
<head>
<title>Color Picker</title>
<script language="JavaScript">
<!--
var firstname = prompt("What is your first name?", "");
function flipandalert(color_value) {
document.bgColor = color_value;
alert(firstname + ", the backgrou nd color has changed to " +
color_value + ".");
}
//-->
</script>
</head>
<body>
<center>
<form>
<p><input type="button" value="Red" onClick="flipandalert('red');"></p>
<p><input type="button" value="Green"
onClick="flipandalert('green');"></p>
<p><input type="button" value="Blue" onClick="flipandalert('blue');"></p>
<p><input type="button" value="White"
onClick="flipandalert('white');"></p>
</form>
</center>
</body>
</html>
#4: Our courseware makes learning and retaining the material enjoyable and easy
Written by our seasoned training staff, our courseware contains the complete instructional
content of the class, making it easy to review later what you have learned. And because
WestLake is vendor-neutral, you will always get a balanced perspective on each technology.
And the #1 reason students select WestLake as the Web Development Training Leader:
Students leave prepared to immediately apply what they have learned. Rather than sitting
through a boring lecture, you will spend a large portion of class time doing hands-on
development with the technology you are learning. Leave prepared to immediately tackle your
projects!
If you have any questions regarding our classes, please email [email protected] or call us toll-
free at 866.WESTLAKE (866.937.8525) and select option 1. You can register at the same
number or online at http://www.westlake.com/register/.
To have WestLake bring a class to you, please email [email protected] or call us toll-
free at 866.WESTLAKE (866.937.8525) and select option 2.