Java Script Basics
What is Java Script? For our purposes, Java Script is an
interpretive
computer language designed to be run by Web browsers for the purpose of
adding
extra functionality to Web pages. Unlike a normal programming language,
Java
Script is not compiled and turned into an executable program (.EXE) or
class
file. Instead, it is embeded as part of an HTML web page, then
downloaded
and executed by the browser.
Java Script itself looks like a mixture of HTML code
and Java code. You should use
Javascript to verify user input on web forms before the form is
sent to the server.
This removes load from the server and gives a prompt response to users
when
they make mistakes. Important note: since Java script is
executed by the browser your
Javascript may behave differently on various browsers. You'll
need to test your pages on Internet Explorer, FireFox, Chrome, and
Safari (and probably others).
Some good tutorials and information
can be found at:
As a beginner, you should think about
JavaScript
as being composed of :
- objects that hold data and have actions that can be
performed on them.
- every page has an window
object that refers to the browser window, and a document object that refers to the
active
page.
- functions that perform a sequence of JavaScript
commands
inorder to complete a task.
- events things that your HTML code can listen
for
and invoke functions when they occur. For example, OnMouseOver,
OnMouseOut, onClick, onFocus, onLoad.
Format of code:
- JavaScript can go into your html in three ways:
- between script tags <script TYPE="text/javascript"> ...
</script>
- you usually add browser comments around javascript code, that
way if the browser does not support javascript, then the script will
not
show on the user screen. <!-- and -->
- in separate files with a .js extension, use the src parameter
on the script tag to reference the file
- e.g. <script TYPE="text/javascript"
src="myscript.js"></script>
- and inside event parameters for html tages, e.g.
<body
onload = ".....">
- capitalization is important for identifier names in javascript,
but not important for HTML tags
- semicolons are optional in some places
- The format of JavaScript lines of code is like Java, with the
following
exceptions:
- Variables are not typed, therefore to declare a variable you
just
use the var keyword.
var x = 3;
var y = 4.0;
var s = "My Name";
- You can use <, >, and == to compare strings
- You can use either double quotes or single quotes to enclose
strings.
- If you want to know how many characters are in a string, just
use
.length (not .length())
Some useful JavaScript funtions:
- Popup a message to the user:
alert("the message to show");
- Popup a confirm dialog (with ok/cancel button), returns true if
ok
pressed, false if cancel pressed
answer = confirm("Do you want to
continue?");
- Ask the user to enter some text
answer =
prompt("Question","Default answer");
- Raise a number to a power
answer =
Math.pow(2,3); // raise 2 to the 3
- Convert a string to an integer
var i = parseInt("123");
- Convert a string to a float (there are no doubles)
var f = parseFloat("123.22");
Note: parseFloat and parseInt do
not generate exceptions, instead they return NaN as a value
- To limit the number of decimals shown in a float, use the toFixed
method (note, not supported by old browsers)
var f = 33.456678;
var s =
f.toFixed(3); // limit to 3 decimals, s = 33.457
- Determine if a string holds a number (returns true if is not a
number)
isNaN("123");
Note: isNaN will return
false for empty strings in some browsers, therefore to do a
complete test you need to check from an empty string as well, e.g.
if(isNaN(number.value) || number.value="")
{
// error
}
- Send the current page to the printer
window.print();
- Insert dynamic content into the current page.
document.write("add this to the
document");
Using document.write to create common
headers/trailers for web pages.
- HTML does not have an "include" or an "import" tag that would
allow you to create the header and trailer sections of your documents
in one file, then reuse them on all your pages. To get around
this you can create a .js file that contains a series of
document.write statements, each statement writes out a line of
html. Then use the script tag with the src parameter to include
it in your html files.
Creating JavaScript Functions
(methods):
- Functions can be declared between javascript tags, and usually
show
up in the header section of the web page.
- Functions can be called from Events code.
- Functions do not declare a return type
- Function parameters are not typed.
- Example:
<HEAD>
<script
TYPE="text/javascript">
<!--
//
// add x to y and return
the
result
//
function add(x, y)
{
return x+y;
}
// -->
</script>
</HEAD>
Accessing HTML form fields from within
functions:
- to access the value of an html form field (e.g. text, select, or
textarea), you reference the document object, then the form name,
then the field name. E.g.
<FORM NAME ="nameForm" METHOD=POST ACTION =
"url">
Last Name: <INPUT TYPE=TEXT NAME= "lastName"
SIZE = 20> <br>
First Name: <INPUT TYPE=TEXT NAME= "firstName"
SIZE = 20>
<INPUT TYPE =SUBMIT NAME="submitButton" VALUE="SUBMIT">
</form>
document.nameForm.lastName.value refers to the text typed in the
last name box
document.nameForm.firstName.value refers to the text typed in the
first name box
- If you are going to access many fields within a form, you can
save
some typing by using the with
specifier:
with(document.nameForm)
{
var lname = lastName.value;
alert("your last name is
"+lname);
var fname = firstName.value;
alert("your first name is
"+fname);
}
- To change the value in the form just put it on the left side of
the equals, e.g.
lastName.value = "Flintstone";
- You can change the text and background color of a form object by
changing the style attribute, e.g.
lastname.style.color = "red";
// text color is now red
lastname.style.background = "yellow"; // background is yellow
lastname.style.borderColor = "red"; // red background
if(lastname.value == "")
{
valid = false;
message = message + "last name
cannot be blank\n";
lastname.style.borderColor= "red";
lastname.style.borderWidth = 4;
}
else
{
lastname.style.borderColor =
"black";
lastname.style.borderWidth =
2;
}
JavaScript Events:
- Javascript code is run in response to events that occur during
the
course of loading, displaying, and interacting with the web page.
- Events are usually associated with the page's objects (document,
window, forms, form items, etc).
- There are many, many different events.
- Click here for a
list of
controls and the events they support.
- Here are some common events you may need to use and the control
they
are associated with:
- <BODY>
- onLoad add
initialization
code to be run as soon as the page has loaded
- <INPUT TYPE = TEXT ... >
- onFocus - add code to
execute when the control gets the focus
- onChange- add code to
be run when an text box has changed its contents (and has lost the
focus)
- <TEXTAREA>
- onFocus - add code to
execute when the control gets the focus
- onChange -add code to
be run when an text box has changed its contents (and has lost the
focus)
- <INPUT TYPE=SUBMIT ....>, <INPUT TYPE=BUTTON>,
<INPUT
TYPE=RESET>
- onClick - add code to
execute when the button is clicked, return true if button click is to
be
processed, false if it should be ignored.
- <SELECT ... >
- onChange -add code to
be run when the user changes the selection
- <FORM >
- onSubmit - add
code to intercept the submit button, this code must return true to
compelete
operation or false to abort the operation.
- in general, you can add verification code to the onChange events
(use the alert method to tell the user about errors), and the
onSubmit event to validate the contents of the form before sending to
the server.
Creating simple calculators
- Write a function for each calculation button, add these functions
to a javascript region in your header (or put them in a separate.js
file)
<script
TYPE="text/javascript">
//
// Add X to Y, place result in Answer
//
function add()
{
with(document.calculator)
{
if(isNaN(x.value)) // check x
{
x.style.color = "red";
alert('X must be a valid number');
return;
}
else
x.style.color = "black";
if(isNaN(y.value)) // check y
{
y.style.color = "red";
alert('Y must be a valid number');
return;
}
else
y.style.color = "black";
var numx = parseFloat(x.value); //
convert x to a number
var numy= parseFloat(y.value); //
convert y to a number
var numz =
numx+numy;
// add the numbers together
answer.value = numz.toFixed(3); // store
answer with 3 decimal places
return;
}
}
</script>
- Create your HTML form, using an <input type=button>
for
your function buttons, add the "onClick" event to the button to call
the javascript function
<input type="button" value=" +
" onClick="add();" />
Validating forms:
- First create a method that has the ability to validate the fields
on the form and returns true (good) or false (bad) when called.
- Then either add code to call this method from the onClick event
for the submit button or from the onSubmit
event for the
form.
- Either way, you must return true/false from the event to tell
the
browser whether or not the request is ok.
- You could also add checking code for the onchange event for
each control, but that wouldn't test for blank fields or prevent the
invalid
data from being sent to the server.
- here is an example that process the
onSubmit
event.
<HTML>
<HEAD>
<SCRIPT TYPE="text/javascript">
<!--
function checkForm()
{
var valid = true;
var message = "Errors: \n";
with(document.surveyForm)
{
if(name.value == "")
{
valid = false;
message = message + "name field is
blank\n";
}
if(street.value == "")
{
valid = false;
message = message + "street field
is blank\n";
}
if(city.value == "")
{
valid = false;
message = message + "city field is
blank\n";
}
if(state.value == "" || state.value.length !=
2)
{
valid = false;
message = message + "state field
is invalid\n";
}
if(zip.value == "" || isNaN(zip.value))
{
valid = false;
message = message + 'zip field is
invalid\n';
}
if(email.value == "")
{
valid = false;
message = message + "email field
is blank";
}
}
if(!valid)
alert(message);
return valid;
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H2>Information Request Form </H2>
<P><B><I>Please enter all information so that we can
better help you!</I></B></P>
<P><FORM METHOD="POST" ACTION="mailto:junk@nowhere.com" NAME =
"surveyForm"
onSubmit
= "return checkForm()"></P>
<TABLE>
<TR>
<TD>Name:</TD>
<TD><INPUT type="text" name="name" size=20
maxlength=30></TD>
</TR>
<TR>
<TD>Street Address :</TD>
<TD><INPUT type="text" name="street" size=20
maxlength=30></TD>
</TR>
<TR>
<TD>City:</TD>
<TD><INPUT type="text" name="city" size=20
maxlength=30></TD>
</TR>
<TR>
<TD>State:</TD>
<TD><INPUT type="text" name="state" size=3
maxlength=2></TD>
</TR>
<TR>
<TD>Zip:</TD>
<TD><INPUT type="text" name="zip" size=15
maxlength=15></TD>
</TR>
<TR>
<TD>Email Address:</TD>
<TD><INPUT type="text" name="email" size=30
maxlength=40></TD>
</TR>
</TABLE>
<P>Have you ever purchased from us before? <INPUT
type="checkbox" name="customer" value="yes"></P>
<P><BR>
Pet Type :
<INPUT
type="radio" name="PetType" Value="Cat"> Cat
<INPUT
type="radio" name="PetType" Value="Dog" Checked> Dog
<INPUT
type="radio" name="PetType" Value="Bird"> Bird
<INPUT
type="radio" name="PetType" Value="Reptile"> Reptile
<INPUT
type="radio" name="PetType" Value="Fish"> Tropical Fish
</P>
<P>Products you are interested in :</P>
<UL>
<P><SELECT NAME="Products" Size=4 MULTIPLE>
<OPTION Value="Pet Food">Pet Food
<OPTION VALUE="Collars/Leashes">Collars and Leashes
<OPTION VALUE="Medications">Medications
<OPTION VALUE="Treats">Treats
<OPTION VALUE="BOOKS">Books and Literature
<OPTION VALUE="Cages">Cages
<OPTION VALUE="Aquariums">Aquariums and supplies
</SELECT></P>
</UL>
<P>Enter questions or further information here:</P>
<P><TEXTAREA NAME="INFO Request" Rows=4 Cols=50>enter your
questions here</TEXTAREA></P>
<P>
<INPUT type="Submit" Name="action" Value="send">
<INPUT type="reset" Value="clear">
</FORM>
</BODY>
</HTML>
|
Calculator Example
<HTML>
<HEAD>
<SCRIPT TYPE="text/javascript">
<!--
function addXY()
{
with(document.calculator)
{
if(xfield.value.length == 0 || yfield.value.length
== 0)
{
alert("X and Y cannot be
blank");
return;
}
if(isNaN(xfield.value) || isNaN(yfield.value))
{
alert("Invalid value for x or y");
return;
}
var x = parseFloat(xfield.value);
var y = parseFloat(yfield.value);
var z = x + y;
answerfield.value = z.toFixed(3);
}
}
-->
</script>
<title>Calculator</title>
</HEAD>
<BODY>
<form name = "calculator">
X: <input type = "text" name = "xfield" size = 20><br>
Y: <input type = "text" name = "yfield" size = 20> <br>
answer: <input type = "text" name = "answerfield" size=
20><br>
<input type="button" value = "Add" onClick="addXY()">
</form>
</BODY>
</HTML>
|