You are on page 1of 17

ORB

Education

JavaScript
A Microsoft FrontPage 2000 Task

This document has been designed for use either


independently, or integrated with the following
publications (also available from ORB Education):

• Building a Website
• Designing a Form
• Learning HTML

Visit http://www.orbeducation.com for a range of printable teaching materials

Stages in JavaScript

Section A. Introduction to JavaScript


Section B. Using JavaScript
Section C. Variables
Section D. Strings
Section E. Prompts
Section F. The ‘if … else’ clause
Section G. Link events
Section H. Forms and functions
Section I. Password puzzle
Section J. String properties
Section K. Loops
Section L. Answers (separate file)

 Microsoft and FrontPage are either registered trademarks or trademarks of Microsoft Corp. in the United States and/or other countries.
Section A. Introduction to JavaScript

JavaScript makes things happen on a web page. The JavaScript programming language can be used:

• To change the colour of text when the mouse pointer is placed over it

• To swap one image for another

• To allow users to input information

• To perform calculations and display the answers

• To check the information entered into a form before it is submitted (form validation)

During this JavaScript project, we will be concentrating on the last 3 uses. We will learn how to accept information
from the user, process it in some way, and then display the results.

INPUT PROCESSING OUTPUT

Some points about JavaScript

1. JavaScript is a true programming language. Mistakes will cause an error message to be displayed, and the
web page to crash.

2. JavaScript works independently of the server. Many interactive effects seen on the Internet require
information to be sent backwards and forwards from the website (if you lose the connection to the Internet,
you cannot use the page). JavaScript will work on it’s own – it is built into the HTML.

3. JavaScript code can be run when the page is displayed, when a button is clicked, when a mouse is placed over
an object, or when a form is submitted.

4. JavaScript is very fussy. You have to get the code exactly right or it will not work. This can be frustrating at
times, especially due to the frequent use of the squiggly brackets { and }.

5. Some old web browsers do not understand JavaScript. It is a common practice to tell these browsers to
ignore the JavaScript, so that an error message does not appear.

6. The JavaScript interpreter (reader) in your browser ignores spaces and line breaks. You could write long,
complicated scripts on a single line, but they would be very difficult to read and understand for the human
programmer.

2  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


Section B. Using JavaScript

JavaScript is usually placed in the head section of the HTML.

NB. The tasks inside the boxes need to be carried out on your computer.

Task 1
a. Open FrontPage 2000. A blank page appears.
b. Click on the HTML tab at the bottom of the page.

Screen shot(s) reprinted by


permission from Microsoft
Corporation

c. Add the following code to the HTML that is already in place:

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Page 1</title>

<script LANGUAGE="JavaScript">
alert ("Hello");
</script>
This is the additional JavaScript code
</head>

<body>

</body>

</html>

d. Click on the ‘Preview’ tab to see what effect the JavaScript has

What does the code mean?

<script LANGUAGE="JavaScript"> - start using JavaScript (this is actually an HTML tag)


alert(“Hello”); - put up an ‘alert box’ which says “Hello”
</script> - stop using JavaScript

Task 2
Change the JavaScript code so that the message now reads “Hello, how are you today?”.

Task 3
Add to the code so that it now looks like the script below. What difference does it make in ‘Preview’?

<script LANGUAGE="JavaScript">
<!--
alert ("Hello, how are you today?");
//-->
</script>

 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 3


What does the new JavaScript do?
As mentioned previously, some old browsers do not understand JavaScript. Although these browsers are rarely used
these days, it is still good practice to take account of them. The additional lines of code tell old browsers to ignore
the script in between. Without these extra lines, an error message would appear. New browsers will simple ignore
these extra lines.

<!-- - old browsers should ignore the following JavaScript


alert(“Hello, how are you today?”); - put up the ‘alert box’
//--> - old browsers should stop ignoring the script now

Task 4
Add one final line to the code so that it looks like the one below. What effect does the new line have on the page
when it is displayed in ‘Preview’?

<script LANGUAGE="JavaScript">
<!-- New line of code
// The following script puts up an alert box
alert ("Hello, how are you today?");
//-->
</script>

Delete the line beginning with the ‘alert’ instruction and save the file as ‘stencil.htm’. Use this page as a base for
each new piece of work. This will save you having to write out the first and last 2 lines each time you produce
some JavaScript. Make sure you save the file as a different name when it has been changed. NB. You are also
encouraged to use the ‘cut’ and ‘paste’ functions frequently. This can save time and help reduce errors.

What does the extra line do?


JavaScript is a programming language. Like all programming languages, there are many ways of producing the same
result. You can also build long scripts to run complicated processes on your web pages. Frequently, programmers
return to their work a few months later only to find that they do not understand the code they have written. It is
even harder for other programmers who have to pick up and work with the code. It is therefore a good practice to
place comments in your scripts so that you (as well as other programmers) can understand what your JavaScript is
doing. Anything following a double forward slash ( // ) will be ignored by the browsers as they run the script.

Task 5 - What have we learned so far?

a. Where should JavaScript be placed in a web page? __________________________________________________

______________________________________________________________________________________________

b. Copy the HTML tags used to introduce and close JavaScripts ___________________________________________

______________________________________________________________________________________________

c. What code is used to stop old browsers from seeing the script? _________________________________________

______________________________________________________________________________________________

d. How do you write comments that will be ignored when the script is run?__________________________________

______________________________________________________________________________________________

e. What is an ‘Alert box’? _________________________________________________________________________

______________________________________________________________________________________________

4  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


Section C. Variables

Variables are a way of storing information. You often use the variables x and y in algebra, assigning a value to each
e.g. x = 2, and y = 4. We can also use variables in JavaScript, but you must declare them first using the term ‘var’.
Declaring a variable is a way of saying “a variable exists, and this is its name” e.g.

var valueX = 2
var valueY = 4
var valueZ

valueX is the name of a variable. It has been given the value 2.


valueY is the name of a variable. It has been given the value 4.
valueZ is the name of a variable. It has not yet been given a value.

You can then use these variables in calculations.

Task 1
Write down the value of the variable ‘valueZ’ in each case

a. valueZ = valueX + 3
b. valueZ = valueX * 2 (* is the symbol used for multiply)
c. valueZ = valueX / 2 (* is the symbol used for divide)
d. valueZ = valueX + valueY
e. valueZ = (valueX – valueY) * 7

Some rules concerning variables

1. They should be declared before use, using the term ‘var’


2. They must start with a letter or an underscore (e.g. FirstName rather than 1stName)
3. They can only contain letters, numbers and the underscore (e.g. Address_1).
4. They are case sensitive (valueZ is not the same as valuez)
5. Life will be easier if you choose names that mean something (e.g. ‘PeopleCount’ rather than ‘x7’)

Task 1
Add the following code to a new page and look at it in ‘Preview’ (remember that the JavaScript is placed between
the </title> and </head> tags.

<script LANGUAGE="JavaScript">
<!-- A semi-colon (;) is used at the end of
each statement
var valueX = 2;
var valueY = 4;
var valueZ = valueX + valueY;
alert(valueZ);
//-->
</script>

Task 2
Adjust the script so that it calculates and displays each of the following sums (there are many ways of achieving
the correct results). Write down the answers.

a. 2345 + 432 __________________

b. 25 * 378 __________________

c. 3578 / 72 __________________

d. (34 * 23) + 97 __________________

 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 5


Section D. Strings

Strings are pieces of text. Strings are usually enclosed in double quotes. The following are all examples of strings:

“This is a string”
“And another”
“2”

Strings are used in association with variables e.g.

Variable name String


var string_1 = “This is a string” string_1 This is a string
var string_2 = “And another” string_2 And another
var string_3 = “2” string_3 2

Task 1
Add the following code to a page and look at it in ‘Preview’ (use your stencil page as a starting point):

<script LANGUAGE="JavaScript">
<!--
var string_1 = "This is a string";
alert(string_1);
//-->
</script>

Task 2
We can use the ‘+’ sign to join two strings together. This is different to adding numeric values together.

a. Adjust the script so that it now looks like this:

<script LANGUAGE="JavaScript">
<!--
var string_2 = "And another";
var string_3 = "2";
var joinString = string_2 + string_3;
alert(joinString);
//-->
</script>

b. Write down the text exactly as it appears in ‘Preview’ _________________________________________

c. Change the fifth line so it now reads:

var joinString = string_2 + “ “ + string_3;

d. How have we changed the presentation of the sentence in ‘Preview’?

Task 3
Analyse the following JavaScript and write down the text that you think it will produce. _____________
After making your prediction, type in the code and see if you were correct.

<script LANGUAGE="JavaScript">
<!--
var valueX = "2";
var valueY = "4";
var total = valueX + valueY;
document.write(total);
//-->
</script>

6  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


Section E. Prompts

Prompts allow the user to input information e.g. they might ask the question “What country are you in?” and provide
a box for you to type the answer. The answer then becomes a variable that you can use in your JavaScript.

Task 1
a. Type the following code into a page and try it out in ‘Preview’:

<script LANGUAGE="JavaScript"> The word “prompt” must have a


<!—- lower case ‘p’.
prompt("What country are you in?","")
//-->
</script>

Where does the text from the first set of quotes appear? ______________________________________

b. Adjust the main statement so that it now looks like this:

prompt("What country are you in?","Mongolia")

What happens to the text from the second set of quotes? _____________________________________

Using variables and strings


The next stage in the process is to take the information from the prompt and use it. To do this we need to assign the
string from the prompt to a variable e.g.

var YourCountry = prompt("What country are you in?","Mongolia")

In this case we declared the variable ‘YourCountry’ , and then made it equal to the string collected from the prompt.

Task 2
a. Adjust the main statement from Task 1 so that it now looks like this:

var YourCountry = prompt("What country are you in?","Mongolia")


alert(YourCountry);

b. Try the alternative below to see a different output:

var YourCountry = prompt("What country are you in?","Mongolia")


document.write(YourCountry);

How is the second display different? _____________________________________________________

c. Improve the alert box by adding some text before the ‘YourCountry’ variable:

var YourCountry = prompt("What country are you in?","Mongolia")


alert(“Your country is “ + YourCountry);

Task 3
Write a script that asks the user their age, suggests an age of 16 as a default value, then puts the actual age
into an alert saying “Your age is 17 years old” (or whatever age is entered). Save the page as ‘Age.htm’.

 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 7


Section F. The ‘if … else’ clause

‘if’ statements allow you to produce different results depending on the input collected from the user. The simplest use
of the ‘if’ statement carries out an action if a certain condition is met:

if (something is true)
{
carry out action
}

Task 1
Type the following code into a page and try it out in ‘Preview’:

<script LANGUAGE="JavaScript">
<!—-
var YourPlanet = prompt("What planet are you from?","Earth");
if (YourPlanet != "Earth")
{
alert("ALIEN ALERT");
}
//-->
</script>

Experiment with the page in ‘Preview’. You can reload the page by clicking on ‘View’ and then selecting ‘Refresh’
from the menu (or you can simply press the F5 key at the top of your keyboard).

What do you think the term ‘!=’ means? __________________________________________

Save the file as “alien.htm”

Conditional Operators

!= is a conditional operator which means ‘is not equal to’. The fourth line of JavaScript therefore reads:

If the variable ‘YourPlanet’ is not equal to “Earth” then…

The list of conditional operators you are likely to need are as follows:

== - is equal to (NB. this is different to using ‘=’, which means ‘make equal to’).
!= - is not equal to
> - is greater than
< - is less than
>= - is greater than or equal to
<= - is less than or equal to

Task 2
a. Type a script that asks whether the user speaks French. Offer a default answer of “Yes”. If the user
enters the answer “Yes”, then put up an alert box saying “Bonjour”. Save this file as “French.htm”.

b. Type a script that asks the user for a number equal to 10 or less. If the user enters a number over 10,
then put up an alert box saying “Sorry, that number is too big”. Remember that the value should not
be in quotes i.e. 10 is a number, “10” is a string. Save the file as number.htm.

8  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


if … else statements
An ‘if…else’ statement produces one action if the condition is met, and a different action if it is not met:

if (something is true) {
carry out action 1
}
else {
carry out action 2
}

Task 3
Open your “alien.htm” file and change the main JavaScript so that it is like the following code. Try it out in
‘Preview’:

var YourPlanet = prompt("What planet are you from?","Earth");


if (YourPlanet != "Earth") {
alert("ALIEN ALERT");
}
else {
alert("Hello Earthling");
}

Task 4
Type a script that asks the user if they understand this project so far. Offer the default answer “Yes”. If the user
answers “Yes” then say “Well done. Please continue.”. If the user answers anything else, then say “Please ask for
help”. Save the file as “understand.htm”. What is the problem with this script?

if … else if…else statements


The problem with the script in Task 4 is that it does not cover all possible answers. If the user answered “Sure” or
“Definitely”, then it would still suggest they ask for help. We need to use the ‘else if’ statement.

if (something is true) {
carry out action 1
}
else if (something different is true) {
carry out action 2
}
else {
carry out action 3
}

You can use as many ‘else if’ statements as you like, to cover as many different answers as you need.

Task 5
Build on your answer to Task 4 so that the main JavaScript now looks like the one below. Test your script.

var Understand = prompt("Do you understand this project so far?","Yes or No");


if (Understand == "Yes") {
alert("Well done. Please continue.");
}
else if (Understand == "No") {
alert("Please ask for help");
}
else {
alert("Sorry, I don't understand your answer.");
}

Task 6
Write a script that asks whether the user prefers blue or red. If they enter “blue” put up an alert saying “I do
too”. If they enter “red” then put up the alert “Blue is better”. If they enter anything other than “blue” or “red”
then put up an alert saying “Sorry, that was not a choice”. Save the file as “colour.htm”.

 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 9


Section G. Link events

Now that we have learned a bit of JavaScript, it is time to look at how events are triggered in the web page. To
achieve this, we have to carefully place JavaScript commands inside normal HTML code.

Task 1
Open a new file in FrontPage. Add the following line of code to the HTML.

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Page 1</title>

</head> The is the additional code

<body>
<a href="#" onclick = "alert('Hello')">Click here</a>
</body>

</html>

Click on the ‘Preview’ tab and see what the new code does.

How does the code work?

<a href=”#” onclick=”alert(‘Hello’)”>Click here</a>

This HTML sets up a hyperlink. This text becomes the


The ‘#’ symbol tells the browser hyperlink. It could easily be
to ‘go nowhere’ when the link is replaced by an image.
clicked.

‘onclick’ is a special HTML An alert box will appear. Single


command. It tells the browser quotes are used because the
to run the following JavaScript JavaScript is inside a pair of
when the object is clicked. HTML double quotes.

Task 2
Replace the ‘onclick’ statement from the code above with each of the following link events, and write down the
effect of each.

a. onmouseover ________________________________________________________________________

b. onmouseout _________________________________________________________________________

c. onfocus _____________________________________________________________________________

d. onblur ______________________________________________________________________________

The last two are not very useful until we start linking them with text boxes and other form elements.

10  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


Section H. Forms and functions

We are now ready to use JavaScript in our form pages. We will be placing the JavaScript in ‘functions’. Functions are
pieces of code that perform a particular task. The JavaScript functions will be placed in the header section of the
HTML, where they will be ignored until we call them using ‘link events’.

a Function The interaction between the function and the forms is set up as follows:

1. Name the function


2. Name the form
3. Name the form elements in the form
4. ‘Call’ the JavaScript function using a link event (a)
Form
5. Use the information from the form elements in the function
b 6. Feedback using alert boxes, or by placing information back in the form (b)

Task 1
Open your stencil page and add the following code. You need to add the JavaScript function between the </title>
and </head> tags, as well as the HTML code in the ‘body’ section of the HTML.

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Page 1</title>

<script LANGUAGE = "JavaScript">


<!--
function OverTen() {
var Number = (Form1.Textbox1.value);
if (Number > 10) { Add this JavaScript code
alert("The number is too big");
}
}
//-->
</script>

</head>

<body>

<form name="Form1">
Enter a number less than or equal to 10
<input type="text" name="Textbox1"> Add this HTML
<input type="button" value=”Go” onclick="OverTen()">
</form>

</body>

</html>

Experiment in ‘Preview’ by submitting numbers less than, and over 10. Save as ‘overten.htm’.

 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 11


Task 2 - Questions

a. What does this code do? ______________________________________________________________________

_____________________________________________________________________________________________

_____________________________________________________________________________________________

b. What is the name of the function in this script? (ignore the brackets) ___________________________________

c. What is the name of the form? _________________________________________________________________

d. What is the name of the text box? ______________________________________________________________

e. Which link event is used to ‘call’ the function? _____________________________________________________

f. What is the name of the variable in the script? ____________________________________________________

g. What does the following line of JavaScript do?

var Number = (Form1.Textbox1.value);

____________________________________________________________________________________________

Task 3
Change the function so that it now looks like this:

function OverTen() {
var Number = (Form1.Textbox1.value);
if (Number > 10) {
alert("The number is too big");
(Form1.Textbox1.value)=10 Extra line
}
}

What is the effect of the extra line? _____________________________________________________________

Task 4
Add one more extra line, and find out what it does. Save the file when you have finished.

function OverTen() {
var Number = (Form1.Textbox1.value);
if (Number > 10) {
alert("The number is too big");
(Form1.Textbox1.value)=10
Form1.Textbox1.focus() Extra line
}
}

What is the effect of the extra line? _____________________________________________________________

Replace the word ‘focus’ with the word ‘select’. What does this command do?

_________________________________________________________________________________________

Task 5
Build a page which asks the question “What is 12 multiplied by 12?”. It should have the following properties:
• There should be a blank text box for the answer
• There should be a button to click when the answer has been typed
• If the answer is correct, an alert should say “Well done”
• If the answer is incorrect, an alert should say “Try again”, and their cursor should flash back in the box

Save the file as “multiply.htm”

12  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


Section I. Password puzzle

Often when you sign up to a service on the Internet (e.g. Yahoo) you have to provide a password for your account.
You are generally asked to type your chosen password into a text box. So that no one can see your password as you
type it, the box is usually a ‘password’ field, and each character appears as an asterisk (*) . To make sure that you
have typed exactly what you planned to type, you are usually asked to enter the password a second time.

The web page then checks that the two values are the same. If they are different, then the boxes are cleared and the
process has to be repeated.

Task 1
Your task is to produce a page that asks for a password twice, and then checks that the type entered is the same
in each text box. Use the following directions as a guide:

a. Open your stencil page, and save as “password.htm”. Save again regularly during the task.

b. Use the <form name=”Form1”> and </form> tags to place a form in the body section of the HTML.

c. Use HTML code such as:


<input type="password" name="PassBox1">
to place 2 password fields inside the form. Name the password fields “PassBox1” and “PassBox2”.

d. Create a JavaScript function called “PasswordCheck” in the header section of the HTML. Introduce the function
using the code:
function PasswordCheck()
and remember to enclose the whole function in a pair of squiggly brackets [i.e. { and }].

e. Collect the information from both password fields using code such as:
var Password1=(Form1.PassBox1.value);
where “Password1” is the variable assigned to the first password string.

f. Use an ‘if…else’ statement to produce 2 different alert boxes depending on whether the two passwords are the
same. You will need to use the code:
if (Password1 == Password2) or if (Password1 != Password2)
depending on how you structure your function.

g. If the passwords are the same, then bring up an alert box saying “Your passwords are the same”.

h. If the passwords are different, then produce an alert saying “Your passwords are different”. Clear both
password boxes using code such as:
(Form1.PassBox1.value) = ””;
The empty double quotes are basically saying “put nothing in the box”.
You should then place the cursor back in the first password box.

i. Use the link event ‘onblur’ in association with the second password field to call the function. The code may
look like this:
<input type="password" name="PassBox2" onblur=”PasswordCheck()”>
The ‘onblur’ command calls the function when the cursor leaves the text box.
You must click in, and then outside the second text box to call the function.

j. Check that your JavaScript has as many closing brackets [ ) or } ] as opening ones [ ( or { ] , and that
statements end with a semi-colon [ ; ]

k. Try the script in ‘Preview’. If you get an error box, then read the message carefully, and look at the line
number that the error is on. You can return to your HTML view, and use the line indicator in the bottom left
hand corner of the screen to help locate the problem.

l. In ‘Normal’ view (or otherwise), add some instructions and formatting to your page.

 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 13


Section J. String properties

The general focus of this project is the validation of information from forms. You may want to refuse data from forms
for any of the following reasons:

• There are too many or too few characters (e.g. for Usernames and passwords)
• The inclusion of unwanted characters (e.g. you may not want spaces in a telephone number field).
• A number that is either too high or too low has been entered

You may also want to take the information from the form fields and suggest a username or password (e.g. a
password made up of the first 4 characters of the name followed by the first 3 characters of the telephone number).

The string functions used in this task will help with all these validation rules.

Task 1
a. Type the following code into your stencil page:

<script LANGUAGE = "JavaScript">


<!--
var String1 = prompt("Please enter a word","");
var LengthString1 = String1.length;
alert("Your word was " + LengthString1 + " letters long");
//-->
</script>

b. Copy the line of JavaScript that calculates the number of characters in the string

__________________________________________________________________________________

Task 2
Try out this code:

<script LANGUAGE = "JavaScript">


<!--
var String1 = prompt("Please enter a word of at least 3 letters","");
var Letter2 = String1.charAt(1);
alert("The second letter is " + Letter2);
//-->
</script>

In this case the ‘charAt’ property has been used. The number (or index) of the character you want to select is
in the brackets, starting at 0 i.e. (0) would identify the first letter, (1) the second, (2) the third etc.

Task 3
a. Now test the following code:

<script LANGUAGE = "JavaScript">


<!--
var String1 = prompt("Please enter a word in lower case letters","");
var Upper1 = String1.toUpperCase();
alert(Upper1);
//-->
</script>

b. Produce a similar script using the ‘toLowerCase’ property

14  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


Task 4
a. Type the following code into your stencil page:

<script LANGUAGE = "JavaScript">


<!--
var String1 = prompt("Please enter a word of 7 or more letters","");

var First3 = String1.substr(0,3);


alert("The first 3 letters are " + First3);

var Next4 = String1.substr(3,4);


alert("The next 4 letters are " + Next4);
//-->
</script>

A ‘substring’ is part of a string e.g. ‘art’ is a substring of the word ‘party’. The ‘substr’ property is
followed by two integers in brackets. These integers are called arguments.

The first argument is the index of the starting letter you want to identify (starting at 0 for the first
letter).
The second argument is the length in characters of the string you want to identify.

To ‘cut’ the substring ‘art’ from the string ‘party’ we would need the following code:

var OriginalString = “party”


var OurString = OriginalString.substr(1,3);

1 is the starting letter (p=0, a=1, r=2, t=3, y=4), and 3 is the number of characters we wish to cut.

b. Write similar code to extract the letters ‘day’ from the string “yesterday”.

_______________________________________________________________________________

_______________________________________________________________________________

Task 5
Develop a piece of code that will identify the last 3 letters of a word collected from a prompt. Follow these
guidelines:

a. Put up a prompt asking for a word with 4 letters or more.

b. Use the ‘StringName.length’ property to calculate the number of characters in the word

c. Subtract 3 from this number to get the position of the starting letter.

d. Use the ‘StringName.substr(a,b)’ property to cut the last 3 letters from the string.

e. Put up an alert box stating what the last 3 letters are. Save the file as “last3.htm”

String property list

We have used the following string properties:

string.length - calculates the number of characters in the string

string.charAt(a) - identifies a single character from a string

string.toUpperCase() - changes all characters to upper case

string.toLowerCase() - changes all characters to lower case

string.substr(a,b) - identifies part of a string (called a substring)


 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 15
Section K. Loops

Loops help us perform a task repeatedly. Although many tasks can be performed using loops, we are going to
concentrate on form validation.

For example, you may want to make sure that an email address has one ‘@’ symbol in it. The method our JavaScript
will use is as follows:

a. Find out the number of characters in the email address (e.g. the address ‘jon@bee.com’ has 11 characters).
b. Start our @ count at 0
c. Look at the first character. If it is an @ symbol then add one to our count.
d. Repeat the test for the other 10 characters in the email address (i.e. loop until we have done the test 11 times).
e. If there is not exactly one ‘@’ symbol then ask the user to check their email address.

The looping section of this code will be carried out using a ‘while loop’. This has the following structure:

while (condition is true) {


carry out action
}

Everything in the ‘while loop’ will continually repeat until the condition is false.

Task 1
a. Type the following JavaScript function into your stencil page. Save the file frequently as “email.htm”.

function CheckEmail() {

var EmailAddress = (Form1.Textbox1.value);


var Length = EmailAddress.length;
var Count = 0;
var Loop = 0;
var Character

while (Loop < Length) {

Character = EmailAddress.charAt(Loop);

if (Character == "@") {
Count = Count + 1;
}

Loop = Loop + 1;
}

if (Count != 1) {
alert("Please check your email address");
Form1.Textbox1.select();
}
else {
alert("Your email address has one '@' symbol")
}
}

b. Include the following form in the body section of the page:

<form name="Form1">
Enter your email address
<input type="text" name="Textbox1">
<input type="button" value="Test" onclick="CheckEmail()">
</form>

c. Test the script in ‘Preview’.

16  ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials


Understanding the Script

1 function CheckEmail() { - Set up function and open function bracket


2
3 var EmailAddress = (Form1.Textbox1.value); - Collect email address from text box
4 var Length = EmailAddress.length; - Calculate the length of the email address
5 var Count = 0; - Set the ‘@’ count to 0
6 var Loop = 0; - Set the loop number to 0
7 var Character - Declare the ‘Character’ variable
8
9 while (Loop < Length) { - Set up ‘while loop’ to repeat until we have
10 looped once for each character
11 Character = EmailAddress.charAt(Loop); - Choose the character to analyse
12
13 if (Character == "@") { - Find out if the character is an ‘@’ symbol
14 Count = Count + 1; - If it is an ‘@’ symbol, add 1 to the count
15 } - Close the ‘if’ clause
16
17 Loop = Loop + 1; - Move to the next loop number
18 } - Close our ‘while loop’
19
20 if (Count != 1) { - Find out if there is one ‘@’ symbol
21 alert("Please check your email address"); - Alert in the case that there is not one
22 Form1.Textbox1.select(); - Select email address in text box
23 } - Close the ‘if’ clause
24 else { - Set up ‘else’ condition
25 alert("Your email address has one '@' symbol") - Alert if there is exactly one ‘@’ symbol
26 } - Close ‘else’ clause
27 } - Close function

Task 2

a. List the 5 variables used ______________________________________________________________________

b. How many of these variables will be strings? ______________________________________________________

Task 3
Change line 14 so it now reads “Count++” instead of “Count = Count + 1” . There should be no difference in
the effect, because this “Count++” is simply a piece of shorthand. Change line 17 in a similar way, and save your
file again.

Task 4
Adapt the code so that you are checking for the presence of at least one ‘dot’ (period/decimal point) in an email
address (there may be more than one this time, so you will need to change the conditions). Save as ‘dot.htm’.

Task 5
Change the conditions so that a ‘dot’ will not be accepted. Save as “nodot.htm”

Task 6
Adapt the code so that the user is entering a phone number, but the number must not contain any spaces. Save
the file as “phone.htm”.

Task 7
Adapt the code so that the user is entering a phone number, but the number must not contain the curved brackets
‘(‘ and ‘)’. The test for the opening bracket will be similar to the last examples. You must then make the variable
‘Loop’ = 0 and repeat the whole loop section of the code for the closing bracket. Use the ‘Copy’ and ‘Paste’
functions to speed up this process. Save as “nobrackets.htm”.

 ORB Education Visit http://www.orbeducation.com for a range of printable teaching materials 17