Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Cs 101 Javascript: A Form - No Javascript Yet

This document discusses how JavaScript can be used to add interactivity to a basic HTML form. It provides an example of a form with input fields for an original number, its square, and its square root. By adding JavaScript code between script tags, the values can be automatically computed when the "Compute" button is clicked. The JavaScript code uses functions, variables, and DOM methods like getElementById to retrieve the input values, perform calculations, and update the output fields. Care must be taken with syntax, capitalization, and ensuring numbers are properly classified as the JavaScript language is case-sensitive.

Uploaded by

Ali Jawad
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Cs 101 Javascript: A Form - No Javascript Yet

This document discusses how JavaScript can be used to add interactivity to a basic HTML form. It provides an example of a form with input fields for an original number, its square, and its square root. By adding JavaScript code between script tags, the values can be automatically computed when the "Compute" button is clicked. The JavaScript code uses functions, variables, and DOM methods like getElementById to retrieve the input values, perform calculations, and update the output fields. Care must be taken with syntax, capitalization, and ensuring numbers are properly classified as the JavaScript language is case-sensitive.

Uploaded by

Ali Jawad
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CS 101

JavaScript

A Form — no JavaScript yet Arithmetic

To make a web page that looks like the one


at the right, requires only HTML. With the Compute Original 3
addition of JavaScript, the button will
‘work’, the square and square root of the
‘original’ number will be computed and Square 9 Root 1.732
placed in the appropriate boxes.

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).

Preparing for JavaScript


Additions are made to the HTML in preparation for the JavaScript. A completed version of the
page shown above appears on the next page with the additional HTML underlined.
• The id option is used to give names to the text boxes.
• The onclick option for the button specifies the name of the sequence of JavaScript instruc-
tions to be performed. The completed page uses the name calculate for the sequence of in-
structions.

Including the JavaScript


• A pair of script tags in the head of the HTML document enclose the JavaScript code.
page 2

CS 101 JavaScript

The Form with JavaScript


The finished page appears below. The underlined portions are HTML that has been added to the
example in the page above. The section in sans-serif type is the JavaScript. The rules for writing
JavaScript are wildly different from (and a great deal more complex than) the rules for writing
HTML.

<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

JavaScript and Capital Letters


JavaScript is case sensitive — JavaScript ‘thinks’ that the alphabet has 52 letters ‘a’…’z’ and
‘A’…’Z’. JavaScript sees no particular connection between any two of them. JavaScript has no idea
that there is any connection between ‘a’ and ‘A’, or ‘b’ and ‘B’ or … ‘z’ and ‘Z’.
This often frustrates beginners because they are not used to worrying about capitalization.

JavaScript, Brackets and Punctuation


JavaScript uses periods ‘.’, semi-colons ‘;’, parentheses ‘(‘ and ‘)’ and braces ‘{‘ and ‘}’ in very pre-
cise ways. You must be careful to use these in exactly the right ways. Be very careful to copy these
symbols exactly. Carelessness will lead to frustration since JavaScript will not give good error
messages when these symbols are misused. This is really the same sort of problem that arises
from careless capitalization.

The JavaScript Code in this Example


function calculate()
{
var n;
n = document.getElementById("original").value;
document.getElementById("square").value = n*n;
document.getElementById("root").value = Math.sqrt(n).toFixed(3);
}

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 ‘;’.

The instructions are:


1. var n;
Reserve a place to store some data, this place will be called n. Var is short for variable and a
data storage place such as this is called a variable.

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

Naming things in JavaScript


Generally speaking, names a programmer makes up for use in JavaScript programs should consist
of lower case letters unless they are compound words that would not be single words in English.
Such compound names have the first letter of each word after the first capitalized. The names
chosen for the program above are:
calculate n squareAndRoot original square root

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

Numbers and Strings


JavaScript keeps track of whether the data stored in a particular place is a number or a string (a
string is a bunch of not necessarily numeric keyboard characters). JavaScript often has a particular
piece of data classified as a string when, in fact, the characters represent a perfectly fine numeric
value.

How JavaScript classifies Numbers and Strings


When you write a value:
if you use quotes JavaScript will classify the value as a string.
"Hello" 'Catch 22' "57" and '3.14159' will be classified as strings.

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.

When a value is obtained from a text box it is classified as a string.

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;

Deciding between Concatenation and Addition


When JavaScript encounters a plus sign ‘+’, a decision must be made as to whether concatenation
or addition is to be performed. If the values on both sides of the ‘+’ are currently considered to be
numbers, addition will be performed. If either of the values is considered to be a string, then con-
catenation will be performed. Thus:
"34" + 10 → 3410 '34' + '10' → 3410 34 + '10' → 3410 34 + 10 → 44

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

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 something which is true or false can also be a question:


if (isNaN(x))

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.
}

and the more extended form:


if (something which is true or false)
{
do this;
do that; This and that are done if the something is true.
}
else if (a 2nd something which is true or false)
{
do thing 3; Thing 3 and Thing 4 are done if the something is false
do thing 4; and the 2nd something is true.
}
else
{
do thing 5;
do thing 6; Thing 5 and thing 6 are done if neither something is true.
}

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

Skipping the Last Portion of a Function — return


A function can be left (with the rest of its statements ignored) by using the statement return. In the
following example, if the user has not typed a number, the portion of the function after the return
is ignored.

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.
...
}

Functions as an Organizational Tool


Giving a name to each of several series of statements can often be used to make JavaScript easier
to read. The following example is intended to illustrate this.
function taxes()
{
var earnings;
earnings = document.aForm.earnings.value;
if (earnings < 20000)
{
smallTax();
}
else if (earnings < 100000)
{
mediumTax();
}
else
{
highTax();
}
}
function smallTax()
{
several dozen statements
}
function mediumTax()
{
several dozen statements
}
function highTax()
{
several dozen statements
}

You might also like