Cs 101 Javascript: A Form - No Javascript Yet
Cs 101 Javascript: A Form - No Javascript Yet
JavaScript
This HTML makes a page that looks like the above — but the button doesn’t do anything.
<html>
<head>
<title>Arithmetic</title>
</head>
<body style = "background-color: rgb(80%, 90%, 100%)">
<form>
<p>
<input type = "button" value = "Compute"/>
Original
<input type = "text" size = "4" value = "3"/>
</p>
<p>
Square
<input type = "text" size = "8" value = "9"/>
Root
<input type = "text" size = "6" value = "1.732"/>
</p>
</form>
</body>
</html>
Input items such as the button and text boxes above must be located between form tags.
For Input items, the value option specifies the text that the user sees. The size option specifies the
width of a text box (in widths of an average letter — generally the same as the number of digits
that fit).
CS 101 JavaScript
<html>
<head>
<title>Arithmetic</title>
<script type = "text/javascript">
<!--
function calculate()
{
var n;
n = document.getElementById("original").value;
document.getElementById("square").value = n*n;
document.getElementById("root").value = Math.sqrt(n).toFixed(3);
}
-->
</script>
</head>
<body style = "background-color: rgb(80%, 90%, 100%)">
<form>
<p>
<input type = "button" value = "Compute" onclick = "calculate()"/>
Original
<input type = "text" id = "original" size = "4" value = "3"/>
</p>
<p>
Square
<input type = "text" id = "square" size = "8" value = "9"/>
Root
<input type = "text" id = "root" size = "6" value = "1.732"/>
</p>
</form>
</body>
</html>
You should enter this page and get it working. Be particularly careful of the capitalization and
punctuation of the items added for JavaScript and the JavaScript itself. The smallest change is
likely to be an error.
Finding Errors
FireFox, Mozilla, and Netscape have a JavaScript Console, an error reporting window which you
will want to use. These programs will show this window if you choose the Error Console from the
Tools menu (Mozilla and Netscape hide it under the sub-menu Web Development ).
Internet Explorer will show error messages if the display a notification of every script error box is
checked in the advanced sub-panel of the Internet Options panel under the Tools menu. When there
is an error, a yellow alert icon will appear at the left of the status line at the bottom of the page.
Clicking on this icon will display the error message. The messages are very much inferior to the
Firefox – Mozilla – Netscape messages though.
page 3
CS 101 JavaScript
The JavaScript language uses the word function to indicate the beginning of a named sequence of
instructions.
•
A named sequence of instructions is commonly called a function.
•
The name of a function is always followed by parentheses ‘(‘ and ‘)’.
•
The sequence of instructions appears between braces ‘{‘ and ‘}’.
•
Each instruction is followed by a semi-colon ‘;’.
2.
n = document.getElementById("original").value;
Copy to n ← the data found in this document, in original, in value.
3.
document.getElementById("square").value = n*n;
Copy to this document, in square, in value ← the product n × n.
In JavaScript, an asterisk ‘*’ is used to indicate multiplication.
4.
document.getElementById("root").value = Math.sqrt(n).toFixed(3);
Copy to this document, in root, in value ← the square root of n.
Math.sqrt means to compute a square root, toFixed(3) means to round off to 3 places.
page 4
CS 101 JavaScript
Most of the names built into JavaScript also follow this rule of capitalization. The names built into
JavaScript and used in the program above are:
function var Math sqrt toFixed
As you can see, except for Math, each of these follows the rule described above.
Generally, the collective name for a group of functions that is built into JavaScript has a name
starting with an upper case letter. Math is one of these. There are several dozen such collective
names, but we will use only a few.
Arithmetic Operators
JavaScript supports:
‘+’ addition
‘–’ subtraction
‘*’ multiplication
‘/’ division
‘%’ remainder of a division
7 + 3 → 10
7 – 3 → 4
7 * 3 → 21
7/3 → 2.33…
7%3→1
There is a potential problem with addition. Read the section on the next page — about numbers
and strings — before you start writing arithmetic expressions.
Math Functions
A few of the functions JavaScript has built in:
Math.sqrt(x)
square root of x
Math.abs(x)
absolute value of x
Math.pow(x, y)
xy x to the power y
Math.floor(x)
the greatest integer ≤ x
Math.ceil(x)
the smallest integer ≥ x
Math.random( )
a random fraction y such that 0 ≤ y < 1.
page 5
CS 101 JavaScript
if you don’t use quotes JavaScript will classify the value as a number.
57 and 3.14159 will be classified as numbers
Hello and Catch 22 are errors, non-numeric values must be contained in quotes.
Concatenating Strings
You can form long strings from short ones by concatenation. Concatenation is just a fancy word
for putting things together, one after the other. For example, after the following code, the variable
full will contain the string "Jane Doe".
var first, last, full;
first = "Jane";
last = "Doe";
full = first + " " + last;
A value obtained from a text box is considered to be a string. If you wish to perform addition with
a value from a text box, you must tell JavaScript that the value obtained is a number. The easiest
way to do this is to multiply by 1 or subtract 0. For example:
n = 1 * document.squareAndRoot.original.value;
document.squareAndRoot.tenMore.value = n + 10;
- or -
n = document.squareAndRoot.original.value − 0;
document.squareAndRoot.tenMore.value = n + 10;
This example will put a value 10 more than the value of original into a text box named tenMore.
If ‘1 *’ (or ‘− 0’) is omitted, the text box will contain the original number with ‘10’ tacked on the end.
page 6
CS 101 JavaScript
A Bit of Jargon
•
A single command in a computer language is called a statement.
•
When statements are carried out they are said to be executed.
•
A named sequence of statements is called a function, procedure, method or subroutine. These words
are often used almost interchangeably although they properly have slightly different meanings.
Control Structures
The statements in a computer program are executed in the order they appear except when control
structures are used. There are two types of control structures: selection and repetition. Most com-
puter languages have several control structures of each type. We will use the if and for structures
of JavaScript for selection and repetition respectively. The for structure appears much later in this
document.
The if control structure, sometimes called the conditional control structure, has the general form:
if (something which is true or false)
{
do this;
do that;
This and that are done if the something which is true or false is true.
}
The something which is true or false can be an expression such these examples:
if (x < 23) if (total >= 100) if (name == "George")
The available operators are:
< (less than)
<= (less than or equal to)
> (greater than)
>= (greater than or equal to)
== (equal to)
!= (not equal to)
The example above means “if x is not a number” — isNaN stands for “is not a number”. This is
rather arcane looking, but commonly used. A programmer commonly checks to see if the user has
typed a number.
The name isNaN comes from NaN which is what JavaScript prints if you print the result of an at-
tempt to perform arithmetic with a value that is not a number. The value NaN appears so com-
monly that the miss-capitalization of isNaN is rarely remarked upon.
A question such as isNaN is called a predicate or a boolean function. The term predicate is used by
logicians. The adjective boolean comes from the name George Boole, who developed important
concepts in mathematical logic — concepts put to use by computer programming languages.
page 7
CS 101 JavaScript
Extended if Structures
The if structure also has the extended form:
if (something which is true or false)
{
do this;
do that;
This and that are done if the something is true.
}
else
{
do these;
do those;
These and those are done if the something is false.
}
Nested if Structures
An if structure can be nested within another if structure:
if (something which is true or false)
{
do this;
do that;
This and that are done if the something is true.
if (a 2nd something which is true or false)
{
do thing 3;
do thing 4;
Thing 3 and Thing 4 are done if both somethings are true.
}
do thing 5;
do thing 6;
Thing 5 and thing 6 are done if the first something is true.
}
else
{
do thing 7;
do thing 8;
Thing 7 and thing 8 are done if the first something is false.
}
page 8
CS 101 JavaScript
function doSomething()
{
var number;
number = document.aForm.quantity.value;
if (isNaN(number))
{
alert("The quantity must be a number.");
return;
}
...
Stuff which is ignored when the user has not typed a number.
...
}