Sunteți pe pagina 1din 79

Introduction

The Javascript tutorials are intended for complete beginners to the subject. If you've never done any programming before in your life, then this is the place to be. Complete the entire course and you'll have a very good understanding of prgramming in general, and Javascript in particular.

How to Study
You should take things slowly when studying any new computer course. The concepts can be difficult at first, so it's important not to do too much at once. Take your time, and don't be put off if at first you don't undertand the lessons. Come back to the lesson later, and it may seem a little easier. And don't forget to bookmark this site!

Projects
Throughout this course, there are a number of exercises to complete. You should try to do all the exercises, as they are designed to increase your understanding of the subject matter. And don't forget to download any course files along the way!

Software Requirements for the Course


No extra software is needed for this course. As long as you have a browser (Internet Explorer, Firefox, or Mozilla are ideal) then you have everything you need. But a text editor like the Windows Notepad, or HTML editor will make things easier. Windows users can download my free HTML Editor by clicking the link below: Go to the HTML Editor Download page Linux users should have any number of text editors already installed. The scripts have been tested with the Firefox and Konqueror Browsers. (The test machine was running Mandrake 9.1 with the KDE desktop.) Most scripts work, except the events in Mozilla, but we explain why this is, and what you have to do to overcome the problem.

Introduction

This course deals with Scripts. A Script is a segment of code that manipulates the browser and its contents in ways that is not possible with ordinary HTML or Cascading Style Sheets. By using a script in your web pages, you can gain more control of how the page looks and behaves: dates and times can be added to the page, form elements validated before the contents are sent, browser details checked, cookies set, even simple games can be added to a web page - all with a scripting language. The learning curve for scripting is a lot a steeper than HTML and Style Sheets. But you can learn the basics, and use scripts on your own pages, without it causing you too much trouble. The scripting language covered in these pages is meant to get you started on the subject, and is not intended as an in-depth study. We're going to study the JavaScript programming language, because it is a widely-used scripting language for web pages. All the scripts in these pages have been tested with modern versions of a wide variety of browsers. If you're ready, then, let's make a start.

A First Script
Let's jump right in with a bit of code. Fire up whatever HTML Editor you use (you can use our free Editor by clicking here: Download the free editor ). With your editor open, copy the following code. When you're done copying it, save your work and load it into your browser. <HTML> <HEAD> <TITLE>A First Script</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE = JavaScript> document.write("Hello World") </SCRIPT> </BODY> </HTML> All right, how did you get on? All that typing should have gotten you this in the browser: "Hello World" Granted, that's a heck of a lot of trouble to go to just to write "Hello World". But it's a start. Let's explain what's going on. When you're writing your scripts, you enclose them between two <SCRIPT> tags, an opening one and a closing one. The opening one should tell the browser what language the script is written in:

<SCRIPT LANGUAGE = JavaScript> The closing Script tag is just the word SCRIPT in between two angle brackets with a forward slash: </SCRIPT> Most of your JavaScript will go between these two tags. So what's all that "document dot write" bit? document.write("Hello World") Document is part of something called the Document Object Model. Document refers to all the text and HTML elements between the two BODY tags. And that includes any attributes inside the BODY tag itself. Like BGCOLOR. Write( ) is a method of Document. A method is a bit of code that actually does something. As opposed to a Property, which IS something. Methods are usually Verbs, and Properties usually Nouns. The Write( ) method writes text (and numbers as well) between the two BODY tags on your page. For all you English language experts out there who might be protesting about the lack of capital letters, Document is spelt with a lowercase "d", and Write with a lowercase "w". Try changing your code to this and see what happens: Document.Write("Hello World") JavaScript is damned picky about capital letters - it doesn't like them at all! The part or parts between the two brackets of write( ) are what will be written to your page. Direct text goes between two double quotes; Variables don't need any. Whoops, we haven't done variables yet. We'll get to them. So the whole line reads "Write the text Hello World between the two BODY tags of the web page." Don't worry if you don't understand some of that - the main point is that you are up and running, and you've written your first script. The journey has just started.

At the moment, we have our script between the two BODY tags. And it works perfectly well here. It's quite happy where it is. However, SCRIPTS are best kept in the HEAD section of your HTML. This is because any code in the HEAD section will be dealt with first by the browser. And besides, it's neater up there. You're not cluttering up your HTML code with lots of JavaScript. So, cut your script out of the BODY section, and paste it into the HEAD section. Like this:

<HTML> <HEAD> <TITLE>A First Script</TITLE> <SCRIPT LANGUAGE = JavaScript> document.write("Hello World") </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Save your work, and then view the results in your browser. Did it make a difference? No, it did not. But rest assured that your script was dealt with before anything in the BODY section. You can also put your scripts into HTML tags. Here's the document.write() code inserted into a Form's Button code: <BODY> <INPUT TYPE = Button VALUE = "Click Me" OnClick = "document.write('Hello World')"> </BODY> Looks a bit messy, but then scripting languages can get like that. Notice, however, that we've shifted the document code to our button: OnClick = "document.write('Hello World')" OnClick is an event that can be applied to buttons (amongst other things.) We'll get to Events later, but for now, note that the same code we wrote earlier then goes after an equals sign ( = ). Or is it the same code? Have you spotted the difference? Yes, Hello World is now in single quotes! That's because we used up our double quotes surrounding the document.write() part. And JavaScript doesn't like you using two sets of double quotes in the same bit of code. There's a lot of things that JavaScript doesn't like. Get used to it.

So what have we learnt so far? We've learnt this: Scripting code is written between a pair of <SCRIPT> </SCRIPT> tags You can refer to the two BODY tags by using the word "document" You can use the write( ) method of document to insert stuff onto your web pages JavaScript is very picky about the way you spell things

The Pop-up message box


We've seen one way to display text - with the write() method of document. Another way to display text (and numbers) is with a little pop-up box. These are called Alert boxes in JavaScript, and they are ideal for nagging your users when they don't fill in your forms correctly. Here's a picture of one:

The code for an Alert box is quite simple. It's this: alert("That was not a proper email address") Notice the cunning use of "alert" for an alert box? The message you want to get over to your users goes between the two brackets. Surround your text message with double quotes, or single quotes if you're putting it after an equals sign in a HTML element. OnClick = "alert('That was not a proper email address')" All right, now that we know how to nag our users with pop-up boxes and written messages, what else can we do? Lots, actually. Let's have a look at that document thing again.

That Document Thing


As was mentioned, document is a part of the Document Object Model. We saw a method that can be used with document, but here's a couple more (Properties and Methods). Properties

bgColor fgColor title

location images forms

Methods

open() close() write() writeln()

There are quite a few more Properties and Methods you can use with document, but these are enough for us. Let's see how you can use them in your own scripts. Start a new web page in your HTML Editor (Or use an old one, if you like - waste not, want not!) Then add this to the BODY section of your page: <BODY> <INPUT TYPE = Button VALUE = "Colour One" Onclick = "document.bgColor = 'Red'"> <INPUT TYPE = Button VALUE = "Colour Two" Onclick = "document.bgColor = 'Blue'"> <INPUT TYPE = Button VALUE = "Colour Three" Onclick = "document.bgColor = 'Green'"> </BODY> Remember, when you're typing the OnClick code that this bit "document.bgColor = " is surrounded by double quotes, and this bit: 'Green' is surrounded by single quotes. And the whole thing is a confusion of single and double quotes: Onclick = "document.bgColor = 'Green'" When you're done, save your work and view the results in your browser. Click the button and see what happens. Well, how did you get on? That should impress the neighbours, hey? If it doesn't, you have some very strange people living next-door to you. Try moving house until you find some neighbours who are impressed. The background colour of your web page should have changed colour when you clicked a button. It did this because of the bgColor poperty of the document object. document.bgColor = After the equals sign, you can either type a name of a colour, or better use an Hexadecimal value:

document.bgColor = #FF0000 document.bgColor = #0000FF document.bgColor = #00FF00 The fgColor property is similar to the bgColor property. Except it will change the colour of any foreground text on your page. Try it out and see how it works. You only need to change the "b" of "bgColor" to an "f". And type some text.

The document Title Property


The Title of a web page appears at the very top of the browser window. You set it by typing some text between the two <TITLE> tags. You can use JavaScript to either get the Title or to set a new one. Here's a script that pops up the Title in an alert box. Try it out and see it in action: <HTML> <HEAD> <TITLE>The title of this web page</TITLE> <SCRIPT LANGUAGE = JavaScript> alert(document.title) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> You can also reset the title of the web page. Change you alert code to this: alert(document.title = "Now I've changed it") The equals sign in there doesn't actually mean equals. It means "assign the value". So what we're saying is "Assign the value of 'Now I've changed it' to the title of the document." Any direct text that you type after the "assignment operator" (the equals sign) needs to go inside double quotes. Load up your new code in your browser, and watch what happens. First, you'll get an alert box: Netscape/Mozilla Alert Box

Internet Explorer Alert Box

But that's not the only thing that happens. If you look at the very top of your browser, the title should have change from "The title of this web page" to "Now I've changed it." Here's the changed version in the two most popular browsers:

Now that you're an expert with alert boxes, here's a little exercise.

Exercise

Use an alert box to test out the location property of document.

In the next part, we'll see how to set up an easy rollover using JavaScript and images.

A JavaScript Rollover
For this part, you may need these two images. Right click on the images, and save them to your own computer:

Now we can begin. A useful property of document is images. The images property tells you if any images are loaded. If the answer is yes, and your HTML images have a NAME attribute, document.images can gain access to them. Why is this useful? Well, let's see. Examine this HTML code for an image: <BODY>

<IMG SRC = "pointer1.jpg" NAME = "but1"> </BODY> Simple enough, because it's just standard HTML Image code. We can turn the image into a link by surrounding it with an Anchor tag: <BODY> <A HREF = "page2.html"> <IMG SRC = "pointer1.jpg" NAME = "but1" Border = 0> </A> </BODY> Still, simple enough: now we've just added the HREF tag and switched the borders off in the image. However, we can add a bit of JavaScript to the Anchor link. This bit of JavaScript uses the images property of document. Like this: <BODY> <A HREF = "page2.html" OnMouseOver = "document.images.but1.src= 'pointer2.jpg'"> <IMG SRC = "pointer1.jpg" NAME = "but1" Border = 0> </A> </BODY> That code looks a bit messy spread over two lines. Notice, though, what was added to the HREF code. It was this: OnMouseOver = "document.images.but1.src= 'pointer2.jpg'" Remember the OnClick event of the button you did? Well, OnMouseOver is another event you can use. This event does something when the user places the mouse over a link, or an image, or whatever. After the equals sign (assignment operator, if you please), we write the code (not forgetting all those awfully messy double and single quotes): "document.images.but1.src= 'pointer2.jpg'" See what we're pointing at? The document.images part is pointing to our image that has the NAME but1. We're then saying access the SOURCE (src), and change it to 'pointer2.jpg'. To see the effect that all this code has, move your mouse over the image below. Move it away and then back again.

Neat, hey? Are the neighbours impressed yet? Blimey, they're a tough crowd. The code for the "dancing hand" uses an event related to the OnMouseOver event - the OnMouseOut event. The code is then exactly the same, except you're resetting the image back to pointer2: OnMouseOut ="document.images.but1.src='pointer2.jpg'"

So by using the images property of document you can create a rollover effect. This is not, however, the recommended way to create a rollover. The standard way is to pre-load the images in the head section of the web page, then use something called a function to switch the images around. Another property of document is forms. We're going to use the Form property of document to validate user input. For that, we need to delve a little deeper into the JavaScript, so we'll leave it till later.

JavaScript Methods and Events


Let's have a look at those document Methods. They were: open( ), close( ), write( ), writeln( ). We've already done write( ), and writeln( ) is the same as write( ) except that you get a line break. So we'll look (briefly) at open( ) and close( )

open( )
We're not going to be using this method, but for reference purposes here's what it does. The default for document.write( ) is to write stuff in the current document window - the browser window. It doesn't need to open a new window, because it already has one to work with. You can use document.open( ) to create a new document and send it things like HTML code. You could send the HTML code with document.write( ) document.open( ) document.write("<H1>Hello</H1>")

close( )
This method is used to close the document you created with the open( ) method.

Events
Two useful document Events you can use are these: onLoad = onUnload =

These are typically used in the BODY section of the HTML code. Here's two pieces of code that will annoy visitors to your site: <BODY onLoad = "alert('Welcome to my web page')"> Or when they leave your site, there's this: <BODY onUnoad = "alert('Goodbye - Have a nice day')"> We'll see another way to annoy your visitors when we create a popup window. We'll do that real soon. The next part will look at another object that is widely used - the navigator object.

Testing your Visitor's Browser


The document object dealt with code between the BODY tags. The navigator object is used to reveal information about the browser your visitors are using. Because some browsers can't deal with certain things (like the document.images code we wrote), the navigator object is typically used to help divert these users away from any code that they can't handle. Two Properties of the navigator object are: appName userAgent Let's use an alert box to test them out. If you don't want to open a new page for this exercise, you can just comment out any old code between SCRIPT tags. Like this: // document.open() // document.write("<H1>Hello</H1>") The two forward slashes mean "please ignore this code". Whether you decide to create a new web page, or use an old one, type this code in the HEAD section of the page: <SCRIPT LANGUAGE = JavaScript> alert(navigator.appName) </SCRIPT> If you're using Internet Explorer, you'll get this before the page loads:

Whereas, if you're using Netscape/Mozilla, you'll get this before the page loads:

Try changing the alert box to this: <SCRIPT LANGUAGE = JavaScript> alert("Your Browser is: " + navigator.appName) </SCRIPT> The plus sign (+) is used to combine things. Here, we're combining the direct text "Your Browser is:" with whatever value is returned from navigator.appName. Note that the direct text has double quotes surrounding it, and navigator.appName doesn't. Save your work and load the web page again. You should get something like this (in Netscape):

OK, so we can tell which browser our visitor is using. But there are many different versions of Netscape and Internet Explorer. An early version of Netscape won't be able to do as much as the latest version, and therefore may not be able to run our scripts. If we just use navigator.appName we won't be able to tell if our user has an early version or the latest version. To solve the problem, we can use navigator.userAgent. Change your alert box to this: alert(navigator.userAgent) Now reload your web page. Internet Explorer will give you something like this:

The part that's useful to us is MSIE 5.01. This tells us that our visitor is using Microsoft Internet Explorer version 5.01. Here's the Netscape version:

The information we're looking for is now on the end: Netscape 6 By using navigator.userAgent we can return all of that text and store it in a variable. We'd then use a JavaScript function to strip out the bit we're looking for. An IF statement is then typically used to execute code depending on what the browser is. In the next part, we'll take a look at how to get the size of the screen your visitor is using, and take a little history lesson.

Screen Size, the History Property


The window object is actually at the top of the DOM tree. It's the boss man of the Document Object Model. If we we're being strictly accurate, we should have been using this: window.document.write("Hello") And this: window.navigator.userAgent But for convenience sake, window is usually left off. This is because most of your code will be written in the current browser window, and not some other window that you haven't told your browser about. The window object has some other useful tricks up its sleeve, though. You can find out information about the screen your visitor is using. By using the screen Property of window, you can add Properties that screen has. Like this: window.screen.height Some other properties of screen are: width, availHeight, availWidth, colorDepth. Let's use width and height to get the size of the screen our visitors are using. After all, they might have a tiny monitor and have to scroll way to the left to see our fancy web page. We could then redirect them to another page, if they have a small monitor.

Screen Size
Copy this code into your editor. Place it in the HEAD section of your HTML. Save your work and test the script in your browser: <Script language = JavaScript>

UserWidth = window.screen.width UserHeight = window.screen.height UserWidth = "Screen Width = " + UserWidth UserHeight = " Screen Height = " + UserHeight alert(UserWidth + UserHeight) </Script> The code is a little more complicated than before. But not too complicated. First, we're storing the value in width to something called a variable: UserWidth = window.screen.width A variable is a little storage area. Think of it as a little cupboard or drawer. Instead of putting socks or underwear in the drawer, you're putting text or number into it. Your little storage area needs a name (else how could you tell which drawer held the socks and which your underwear?). The variable name is UserWidth. This is a name we made up ourselves. You can use just about anything you want as a variable name. (But there are a number of words JavaScript likes to keep for itself.) To put something in your drawer (variable) you type an assignment operator (the equals sign), then type whatever you want to put into the drawer (variable). If you putting text into the variable, surround the text with double quotes: UserWidth = "This will hold a width" If you're putting numbers into the variable, don't surround the numbers with double quotes: UserWidth = 600 Or you can combine the two with the plus sign (+): UserWidth = "This will hold a width of " + 600 You can also put the value held in another variable into your new variable. Like we did for our code: UserWidth = window.screen.width The value held in the last bit (width), is now stored in our variable with the name UserWidth. Then we just combine direct text with the value we've just stored in UserWidth: UserWidth = "Screen Width = " + UserWidth Finally, we combine the two variables in an alert box: alert(UserWidth + UserHeight) When you load your web page, you should see a message box like this one:

Exercise
Use availHeight, availWidth, colorDepth to find out the available height of your own screen, the available width of your own screen, and the colour depth of your screen. Display the results in an alert box like this one (Netscape):

You can start a new line by adding "\n" to the end of your variable declaration. Like this: AHeight = window.screen.availHeight + "\n"

The history object


The history object can be added to window. The history object can be used to move your user back or forward. The result is exactly the same as clicking the Back and Forward buttons on the browser toolbar. You can also use history.go() to move your users a specified number of pages either backwards or forwards. The history object works like this: <Script language = JavaScript> alert("Sorry, this page is under construction") window.history.back() </Script> That script could go in say page2.html. On page1.html, there might be a link leading to page2.html. When the link is clicked, the above script will be executed in page2.html. The results is that first the alert box displays. Then the second line of code gets executed. This uses the back() method of the history object to take the user back to where they came from. The forward() method the same way, except your user will be taken forward one page in the browsing history.

To use the go() method of the history object, just type a number in between those two brackets. Like this: window.history.go( -2 ) The minus two means back two pages. To go forward, just remove the minus sign (-). OK, we've explored a fair bit of the Document Object Model. You should, by now, have a good idea of what can be done with it. To do anything more, though, we're going to need to delve a little deeper into the JavaScript language. So a word of warning - programming starts here!

Setting up variables in JavaScript

You have just learnt what a variable is (Screen height and width section), and that it is storage area for text and numbers. Let's explore variables a bit more.

Variables

For our purposes, variables can hold two types of information: Numbers, and Strings. W seen how strings work (strings are text), so let's have a go at number variables. Number variables in JavaScript can be integers, floating point, or Boolean. An integer is number without a decimal point; if you absolutely insist on having a decimal point then thing you want is called a floating point number; Boolean numbers are not really numb but just a record of whether something is true or not true (think of a light switch - is it o off?). Here's some examples of all three number types:

Integer 3 16 136

Floating Point 3.5 16.8 136.58

Boolean true false true

To store one of those number types into a variable, just use the assignment operator ( = ). The number goes o hand side of the assignment operator, and your variable name goes on the left. Here's an example of how to s number types into variables: Number1 = 3 Number2 = 3.5 Number3 = true Number1, Number2, and Number3 are our variable names. We could have used anythi liked here. As long as we're not using the handful of words JavaScript reserves for itsel starting with a number, and not putting any spaces in the variable name, we're all righ some valid and invalid variable names BobsNumber = 3 (valid variable name) Bobs Number = 3 (invalid variable name - space) 3bobsnumber = 3 (invalid variable name - starts with a number) A good idea when declaring variables, and putting values into them, is to use the word front of them. Like this: var Number1 = 3 The word var is short for variable. It ensures that any variable with the same name els in your code doesn't overwrite it. Which is a pain, believe me. For clarity's sake, howev leave var out of our declarations. You can store the value in one variable name in another variable. Take this as an example: A=2 B=A Here, the variable "A" is assigned a value of 2. The value inside "A" is then assigned to variable "B". So what's inside "B"? Not the letter "A", but the number 2, of course. If you want to add, subtract, multiply, and divide your values, you'll need the operators four basic operators are these : + (Add) - (Subtract) * (Multiply) / (Divide) Actually, the last two should be the first two. That's because Multiply ( * ) and Divide ( done first when JavaScript is doing its sums. But, anyway, here's the operators in actio these scripts out in a web page, and see how you get on: <SCRIPT Language = JavaScript> A=2 B=A C=B+A alert(C) </SCRIPT> <SCRIPT Language = JavaScript> A=2 B=4 C=B*A alert(C) </SCRIPT> <SCRIPT Language = JavaScript> A=2

Adding numbers in textboxes


We'll design a web page with a three text boxes and a command button. When the command button is clicked, any numbers in the first two boxes will be added together. The answer will appear in the third text box. Here's what your form will look like when it's finished (The button doesn't do anything yet, if you click it): Number One: Number Two: Total: So you type a number into the Number One text box, and type a number into the Number Two text box. When the "Add Numbers" button is clicked, the total will appear in the "Total" box. Let's design the HTML Form first (You can copy and paste this). <FORM NAME = frmOne> Number One: <INPUT TYPE = Text NAME = txtFirstNumber SIZE = 5 value =""> Number Two: <INPUT TYPE = Text NAME = txtSecondNumber SIZE = 5 value =""> <P> Total: <INPUT TYPE = Text NAME = txtThirdNumber SIZE = 5 value = ""> <P> <Input Type = Button NAME = b1 VALUE = "Add Numbers" onClick = calculate()> </FORM> OK, it might look a bit messy, but it's just a standard HTML form. You can use your HTML Editor to design it. Note a few things about the form, though. First, that the form has a NAME: <FORM NAME = frmOne> When we're writing the code, we need to tell the browser which form we're talking about. Our form is called "frmOne". For the very same reason, all three text boxes have NAMES: txtFirstNumber txtSecondNumber txtThirdNumber Note, too, that all three text boxes have a VALUE attribute. The button has an onClick event that is crucial to the operation: onClick = calculate( ) Remember that name - calculate( ). We're going to be seeing that in the SCRIPT section. So, in the HEAD section of your web page, write the following script:

<SCRIPT language = JavaScript> function calculate() { A = document.frmOne.txtFirstNumber.value B = document.frmOne.txtSecondNumber.value C = (A + B) document.frmOne.txtThirdNumber.value = C } </SCRIPT> A function is a way to group together a section of code. This function will calculate the two numbers from our text boxes, and pop the answer in the third text box. The syntax for a JavaScript function is this: function FunctionName() { } Our FunctionName was calculate(), which was the one from the command button. When the button is clicked, the browser will try to find a function called calculate(). Note that when setting up a function you need a lowercase "f" and not a capital "F". After the name of your function, type a pair of round brackets. You can put something called an argument in between the round brackets. But our function has no arguments, so we just leave them empty. After the round brackets, type a space, then type a left curly bracket { . The code for the function itself goes next (on a new line), and then you type a right curly bracket }. Here's our function again: function calculate() { A = document.frmOne.txtFirstNumber.value B = document.frmOne.txtSecondNumber.value C = (A + B) document.frmOne.txtThirdNumber.value = C } The first line of the code is this: A = document.frmOne.txtFirstNumber.value The value we're putting in the variable called "A" is coming from the first text box. The part on the right of the equals sign ( = ) might look a bit long and complicated, but all we're doing is telling the browser which text box we're referring to. We're saying this: "In the document there is a form called frmOne. This form has a text box called txtFirstNumber. Whatever value has been typed into this text box, store it in the variable called A." We do the same for the second text box, storing its value in the variable called B.

The third line of code adds together the two values A and B. The total is then stored in the variable called C. Once we have our answer in C, we then need to store it in the third text box on the form. So we have to say "Assign the value in the variable called C to the text box called txtThirdNumber." document.frmOne.txtThirdNumber.value = C To finish it all off, we type our right curly bracket }. So, after you've finished typing all that code, load it into your browser and give it a try. Test out the boxes and button below, to see what yours should do. Enter a 2 in the first box, and a 2 in the second box. Then click the Add Numbers button. You should get 22! Number One: Number Two: Total: To find out what went wrong, read the next part!

Adding numbers in textboxes (continued)


Whoops! Something has clearly gone wrong with our adding machine from the previous part of this javascript tutorial. Two plus two does not equal twenty two! Our programme seems to have joined our two numbers together, rather than adding them together. The problem lies in those text boxes. Not surprisingly, what you get form a text box is text. So when we typed in the number 2, the programme thought it was text. When we told the programme to add the numbers we did it like this: C = (A + B) Because the programme thinks there is text in the variables A and B, it will join them together instead of adding them up. When you tried to add up 2 + 2, you got 22 and not 4. So what's the solution? One solution is to force the programme to recognise the text as a number. We can use the JavaScript function eval(). Like this: A = eval(document.frmOne.txtFirstNumber.value) B = eval(document.frmOne.txtSecondNumber.value) In other words, surround your document code with the round brackets of the eval() function. Just the first two, A and B. Another, neater, solution is to use JavaScript's in-built Number() function: A = document.frmOne.txtFirstNumber.value B = document.frmOne.txtSecondNumber.value A = Number(A) B = Number(B)

Make sure Number has a capital "N", and not a lowercase "n". This will force JavaScript to recognize the value from a text box as a number. Using this method, however, will get you a "NaN" in the your answer text box, if your user enters a string (two + two instead of 2 + 2. NaN stands for Not a Number). So you need to do some error checking for this, which we'll get to later. For now, pretend that your users are all well behaved, and wouldn't dream of spoiling your code by entering text instead of numbers! When you've amended your code, try your programme again. It should work properly now. Ok, here's a little exercise. Have a go at this.

Exercise
Add a second button to your form. When this button is clicked, the two numbers in the first and second text boxes should be multiplied together. The answer should appear in the third text box. You will need to write a second function below the first one you have just wrote. When you're done, your code should work like the one below. Enter some numbers in the boxes below, then click the button to test out the scripts. Number One: Number Two: Total: Right, that should have given you lots of practice with variables. Not to mention practice with getting things from text boxes on forms. We'll move on to Control Flow now. We'll use loops to turn our little programme into a "times table" calculator, and we'll use if statements to help us evaluate things.

Javascript If Statements
To write more complex programmes in any language, you need something called control flow. This is just controlling the direction of the programme so that it's not so linear. Instead of reading your code line by line, and every single line, you can skip lines of code depending on certain conditions. For example, if you're using an OK and Cancel alert box, and the user clicks OK, you can execute one piece of code. If, however, the user clicks Cancel, you can have a different segment of code executed. This is called Control Flow. Don't worry if none of that makes sense - it will become clearer when you follow the examples. Programming is, after all, about doing, and not yakking.

If Statement
If statements are the backbone of programming. Some people even go so far as to say that in a sense, all programming is a series of If statements. To get you started on just what an If statement is, type this code into the HEAD section of a HTML page, then test it out: <SCRIPT language = JavaScript> ConfirmStatus = confirm("Format Your Hard Drive?") if (ConfirmStatus == true) { alert("Formatting Hard Drive Now ") } </SCRIPT> The first line of code is what gives you a new type of message box -confirm. It looks like this in Internet Explorer (NOTE: We're not actually going to format anything!)

The programme then waits until you click either the OK button or the Cancel button. ConfirmStatus = confirm("Format Your Hard Drive?") Whichever button you click, the answer will be stored in the variable ConfirmStatus. The answer, in this case, is a Boolean value: it's either True or False. If you click OK on a confirm box, the answer will be true; if you click Cancel on a confirm box, the answer will be false. What you as a programmer have to do next is to check which button the user clicked. Was OK clicked or was Cancel clicked? If the OK button was clicked, you'll want to do one thing; if the Cancel button was clicked, you'll want to do another thing. So you need to test what is inside the variable ConfirmStatus. You do the testing with an if statement. Our if statement was as simple as if statement get. It was this: if (ConfirmStatus == true) { alert("Formatting Hard Drive Now ") } Note the format for an if statement: if (condition to test) { Your statement here

First you type the word if (in lowercase letters) Next, type a space, then your condition inside round brackets Type another space, then type a left curly bracket { On a new line, type your statement (what you want to happen) Finish with a right curly bracket }

If you're checking what's inside a variable, JavaScript requires a double equals sign (==). It means "has a value of". In our condition to test, we wanted to check whether the variable ConfirmStatus was true or false. So we did this: ConfirmStatus == true We're saying "If ConfirmStatus has a value of true" then execute the next line of code. The next line of code was an alert box: alert("Formatting Hard Drive Now ") The main point to bear in mind here is that you would only get the alert message IF you clicked the OK button. Because then the variable ConfirmStatus would be true. But what if the user clicked Cancel? What happens then? If the Cancel button is clicked, the ConfirmStatus variable will be false. In that case, our alert box statement doesn't get executed the programme will just ignore that line and move on to the next line of code. We can, however, add another statement to check for a false condition. Change your code to this: <SCRIPT language = JavaScript> ConfirmStatus = confirm("Format Your Hard Drive?") if (ConfirmStatus == true) { alert("Formatting Hard Drive Now ") } if (ConfirmStatus == false) { alert("Tough! Formatting Hard Drive anyway") } </SCRIPT> The new code is in bold. All we've done is add a second if statement to check for a false condition. If ConfirmStatus is false (the Cancel button was clicked), then the second alert box is displayed. All you're saying with if statement is this: "If it's true, do one thing; if it's false do another thing" You can add as many if statements as you need, and you can nest one if statement inside another. For example, you could add another confirm box inside the second statement, and nest another if condition. Like this: if (ConfirmStatus == false) {

nested = confirm("Ah, go on! Let me format your hard drive") if (nested == true) { alert("Thanks!") } if (nested == false) { alert("Spoil Sport!") } } When you're nesting if statement like that, things can get a little complicated. To move on to if ... else statements, click the link below.

if else statements

We saw in the last part of this Control Flow section that to test two conditions (true and two if statements were needed. But you don't have to use separate if statements. Inste can use the else word. This is ideal for Boolean values. Here's our code again, this time if else statement. ConfirmStatus = confirm("Format Your Hard Drive?") if (ConfirmStatus == true) { alert("Formatting Hard Drive Now") } else { alert("Tough! Formatting Hard Drive anyway") } The first if statement is exactly the same. Now, though, instead of our second if statem test for a false condition, we've used the word else. The format for an if else statem this: if (condition to test) { Statement 1 } else { Statement 2 } So if the first statement isn't true, the code beneath else gets executed.

if else if

If you need multiple if statements, then if else if is the one to use. In the code below check to see what number is in a text box. Depending on which number was typed in, display an appropriate (or inappropriate) message. First, you're going to need a few m symbols to work with. You've already met the double equals symbol (==), and know th means "has a value of". Here's some more.

> < <= >= != && ||

Greater than Less than Less than or equal to Greater than or equal to Not equal to Evaluation And Evaluation Or

We'll see how these operators work with our next little programme. So design an HTML page with the follow on it. <FORM NAME = "AgeTest"> Type in your age, then click the button: <INPUT TYPE = Text NAME = txtAge Size = 15> <INPUT TYPE = Button NAME = "b1" VALUE = "Age Tester" onClick = message()> </FORM> Once you've typed the HTML code for the form, type this JavaScript code in the HEAD s your page: <SCRIPT language = javascript> function message() { age = document.AgeTest.txtAge.value if (age < 16) { alert("How's school these days?") } else if(age > 16) { alert("It's tough being an adult") } } </SCRIPT> We had another onClick event for our command button, which called the message( ) f When the message( ) is called, it first stores the value in the text box into a variable ca age = document.AgeTest.txtAge.value Next, we need to test what is inside the age variable. We started the test with an if sta if (age < 16) { alert("How's school these days?") } Notice one of our new symbols in the "condition to test": age < 16 If the value stored in the variable age is less than 16, then the condition will be true. If condition is true then our statement will get executed. The statement was an alert box alert("How's school these days?") Next, because we're checking for multiple values, we have the else if condition. Ours w if (age < 16) { alert("How's school these days?") } else if(age > 16) { alert("It's tough being an adult") } The format for the else if part is this: if (condition to test) { statement 1 } else if(condition to test) { statement 1 }

The Operators, And, Or


Notice in that last code that the second age test uses the Greater Than symbol ( > ). Try entering the number 16 in your text box, and then click your button. What happened? If you haven't added the final else statement, then nothing will happen. This is because we're testing for Less Than 16 in the first if statement, and then testing for Greater Than 16 in the first else statement. We're not testing for exactly 16. So none of our statements will be true. What we need is another of our symbols. Either >= (Greater Than or Equal to) or <= (Less Than or Equal to). So, change your code. Take out either the Less Than symbol ( < ) or the Greater Than symbol ( > ). In it's place, insert either <= or >= to see what happens. Play about with the symbols to see how they work. What happens if you put both in? Like this: if (age <= 16) { alert("How's school these days?") } else if(age >= 16) { alert("It's tough being an adult") } else { alert("Please try again") }

Exercise
Add a few more else if statements, and test for these ages groups: 17 to 25 26 to 40 41 to 65 66 and over Add a suitable alert message for when the command button is clicked. With an exercise like the one above, it's really handy to use the AND operator (&&) and the OR operator ( || ). Here's how to use them.

AND and OR

These two operators will return a Boolean value. You use them when you want to test two or more conditions. For example, if you wanted to test if someone was over 65 and had a buss pass, use AND; if you wanted to test if someone was over 65 or had a buss pass, use OR. Like this: if (Age >= 65 && BusPass == false) { alert("Pensioners - Get your free bus pass now!") } If BOTH conditions are true then the IF Statement is true. If just one of them is false, then the entire IF Statement is false. Note the format (and where the round brackets are): if (condition1 && condition2) { Code if true here } Contrast that with the OR operator: if (Age >= 65 || BusPass == false) { alert("Pensioners - Get your free bus pass now!") } This time, if just one of your conditions is true then the entire IF statement is true. They both need to be false for the entire IF Statement to be false. The format (syntax) is the same, except for the two pipe characters ( || ) in place of the two ampersands (&&).

Not a Number
Let's use the AND operator to solve our little problem from a previous lesson. You'll remember what that problem was - if a user enters text into our text boxes, then we get the "NaN" error message in our answer text box. Here's the problem form. Click the Add Numbers button and see what happens: Number One: Number Two: Total: What we need to do is to check the text in the text box. If they are both numbers, then we can go ahead and add them up; if just one of them isn't, then we can display an alert box to tell the user to try again. Our original code was this: <SCRIPT LANGUAGE = JavaScript> A = document.frmOne.txtFirstNumber.value B = document.frmOne.txtSecondNumber.value A = Number(A) B = Number(B) C= A + B document.frmOne.txtThirdNumber.value = C </SCRIPT>

We can insert an If statement on the third line of the code which will check if the user entered a number. Only then will we do the adding up. The if statement we can use is this: if (Number(A) && Number(B)) { A = Number(A) B = Number(B) C=A+B document.frmOne.txtThirdNumber.value = C } else { alert("Please enter a number in both boxes") } Notice the use of the AND operator (&&). What we're saying is: "If it's true that A is a number AND if its true that B is a number, then execute the code below; otherwise, display an alert box." Amend your code to include the if .. else statement, and test it out in a browser. It should work all right now. Except! Try entering two zeros in the text boxes and see what happens. Can you think of a solution? When you've solved the problem, you can move on to Loops.

JavaScript For Loops


So what's a loop then? A loop is something that goes round and round. If I told you to move a finger around in a loop, you'd have no problem with the order (unless you have no fingers!) In programming, it's exactly the same. Except a programming loop will go round and round until you tell it to stop. You also need to tell the programme two other things - where to start your loop, and what to do after it's finished one lap (known as the update expression). There are three types of loops in JavaScript: for loops, while loops, and do while loops. We'll start with the most common type - the for loop.

For Loops
Here's a JavaScript for loop in a little script. Type, or copy and paste, it into the HEAD section of web page (along with the script tags) and test it out. counter = 0 for(start = 1; start < 10; start++) { counter = counter + 1 document.write("start = " + start + " counter = " + counter

+ "<BR>") } How did you get on? You should have this printed on your page: start = 1 counter = 1 start = 2 counter = 2 start = 3 counter = 3 start = 4 counter = 4 start = 5 counter = 5 start = 6 counter = 6 start = 7 counter = 7 start = 8 counter = 8 start = 9 counter = 9 start = 10 counter = 10 The format for a for loop is this: for (start value; end value; update expression) { } The first thing you need to do is type the name of the loop you're using, in this case for (in lower case letters). In between round brackets, you then type your three conditions: Start Value The first condition is where you tell JavaScript the initial value of your loop. In other words, start the loop at what number? We used this: start = 1 We're assigning a value of 1 to a variable called start. Like all variables, you can make up your own name. A popular name for the initial variable is the letter i . You can set the initial condition before the loop begins. Like this: start = 1 for(start; start < 11; start++) { The result is the same - the start number for the loop is 1 End Value Next, you have to tell JavaScript when to end your loop. This can be a number, a Boolean value, a string, etc. Here, we're telling JavaScript to bail out of the loop when the value of the variable start is Less Than 11. Update Expression Loops need a way of getting the next number in a series. If the loop couldn't update the starting value, it would be stuck on the starting value. If we didn't update our start value, our loop would get stuck on 1. In other words, you need to tell the loop how it is to go round and round. We used this: start++

In the java programming language the double plus symbol (++) means increment (increase the value by one). It's just a short way of saying this: start = start + 1 You can go down by one (decrement) by using the double minus symbol (--), but we won't go into that. So our whole loop reads "Starting at a value of 1, keep going round and round until the start value is less than 11. Increase the starting value by one each time round the loop." Every time the loop goes round, the code between our two curly brackets { } gets executed: counter = counter + 1 document.write("start = " + start + " counter = " + counter + "<BR>") Notice that we're just incrementing the counter variable by 1 each time round the loop, exactly the same as what we're doing with the start variable. So we could have put this instead: counter++ The effect would be the same. As an experiment, try setting the value of the counter to 11 outside the loop (it's currently counter = 0). Then inside the loop, use counter- - (the double minus sign). OK, all that theory might be getting a bit heavy. Time to write our little "times table" programme, that was mentioned in the last section.

A Times Table Programme


Design a web page that looks like the one below. (It's just basic HTML and shouldn't cause you too much trouble. Though, if you want to copy and paste all the code, you can click this link:) Click here for the HTML code Start Number: End Number: Multiply By: Once you've designed your form, you can start the programming. The programme is quite simple: when the "Times Table" button is clicked, the times table specified in the "Multiply By" text box will appear in the Text Area below it (1 time 2 = 2, 2 times 2 = 4, 3 times 4 = 12, etc). The Programme at the top of the page didn't do anything when you clicked the "Times Table" button. Here's one that does. Click the button to see what we're going to be programming: Start Number: End Number: Multiply By:

The numbers in the first two text boxes (1 and 10) will be used for the start and end value of our for loop. So, here's the code: Add it to the HEAD section of your web page. Test it out and then move on to the explanation. function calculate() { start = document.frmOne.txtStart.value end = document.frmOne.txtEnd.value times = document.frmOne.txtTimes.value if(Number(start) && Number(end) && Number(times)) { start = Number(start) end = Number(end) times = Number(times) result = document.frmOne.taOne for(i = start; i <= end; i++) { answer = i * times result.value = result.value + (i + " times " + times + " = " + answer + "\n") } } else { alert("Please enter numbers in the boxes") } } Granted, it might look a touch long and complicated, but it's not really - you can handle it. To help you, let's break it down and see what's going on. We start by passing the values from the three text boxes into three variables: start = document.frmOne.txtStart.value end = document.frmOne.txtEnd.value times = document.frmOne.txtTimes.value Next, we set up an if else statement to check that our user is typing numbers into our text boxes: if(Number(start) && Number(end) && Number(times)) { else { } The thing you need to be careful of here is that you have all the round brackets in place. Otherwise your programme won't work. But once we have our if else statement set up we can enter our statements in between the curly brackets. If the user has indeed entered all numbers, we need code to make the programme work. We start with these three lines:

start = Number(start) end = Number(end) times = Number(times) All we're doing here is ensuring that JavaScript gets the point that they are actually numbers in the text box and not strings. The next line is a bit new to you: result = document.frmOne.taOne The code document.frmOne.taOne is the Text Area on our form. All we're doing is storing the text area object itself into a variable called result. This is to save us having to type out document.frmOne.taOne.value = every time we need it. Now, we can just type result.value = and JavaScript will know what we mean. And then we have our for loop. Here it is, minus the code that will display the result in the text area: for(i = start; i <= end; i++) { answer = i * times } In the round brackets of the for loop, we're saying, "Assign the value in the variable called start to the variable called i (i = start). Stop looping when the value in the variable called end is Less than or Equal to the value in the variable called i (i <= end). Every time round the loop, add one to the variable called i (i++)." The code inside the for loop, the code that gets executed each time round the loop, is this: answer = i * times Remember, the variable times holds the times table, the 2 times table by default. This is being multiplied by whatever is inside the variable i. Each time round the loop, i will have a different value first 1, then 2, then 3, etc. The answer is then stored in the variable that we called answer. Finally, we displayed the result in our text area with this rather long line: result.value = result.value + (i + " times " + times + " = " + answer + "\n") It would have been even longer if we hadn't stored the text area into the variable called result. If we hadn't, the line would be this long: document.frmOne.taOne.value = document.frmOne.taOne.value + (i + " times " + times + " = " + answer + "\n") Which is very messy indeed. But all the line is doing is joining the various bits together: the variable i is joined with some direct text ("times "), which is joined with the variable times, which is joined with an equals sign ( " = " ), which is joined with the variable answer, which is joined with the new line character ( "\n" ). Phew!

And it doesn't end there, because we need to keep whatever is already in the text area: result.value = result.value + The only thing left to do is write the code for the else statement. Fortunately, there not much to do there except display an alert box inviting the user to try again: else { alert("Please enter numbers in the boxes") } And that's it - your very own times table generator. If you have children, show them the programme you wrote. They'll be very impressed and tell you how brilliant you are. Children are like that. Of course, your programme is not perfect, which I'm sure the children will discover. Especially if they enter a 10 as the start number and a 1 as the end number. Anything you can do to trap this error? Another if statement somewhere, perhaps? In the next part, we'll deal with while and do loops. We'll keep it short!

JavaScript While and Do Loops

While Loops
Instead of using a for loop, you have the option to use a while loop. The structure of a while loop is more simple than a for loop, because you're only evaluating the one condition. The loop goes round and round while the condition is true. When the condition is false, the programme breaks out of the while loop. Here's the syntax for a while loop: while (condition) { statement } And here's some code to try. All it does is increment a variable called counter: counter = 1 while (counter < 11) { document.write(" counter = " + counter + "<BR>") counter++ } The condition to test for is counter < 11. Each time round the while loop, that condition is checked. If counter is less than eleven then the condition is true. When counter is greater than eleven then the

condition is false. A while loop will stop going round and round when a condition is false. If you use a while loop, be careful that you don't create an infinite loop. You'd create one of these if you didn't provide a way for you condition to be evaluated as true. We can create an infinite loop with the while loop above. All we have to do is comment out the line where the counter variable is incremented. Like this: counter = 1 while (counter < 11) { document.write(" counter = " + counter + "<BR>") //counter++ } Notice the two forward slashes before counter++. This line will now be ignored. Because the loop is going round and round while counter is less than 11, the loop will never end - counter will always be 1. Here's the times table programme again, only now we've used a while loop instead of a for loop (the lines that write the result to the text area have been left out): start = 1 end = 1 times = 2 answer = 0 while (end < 11) { answer = start * times start++ end++ } The while loop calculates the 2 times tables, up to a ten times 2. Can you see what's going on? Make sure you understand the code. If not, it's a good idea to go back and read this section again. You won't be considered a failure. Honest.

Do ... While loops


This type is loop is almost identical to the while loop, except that the condition comes at the end: do statement while (condition) The difference is that your statement gets executed at least once. In a normal while loop, the condition could be met before your statement gets executed. Don't worry too much about do while loops. In the next part, we'll take a look at how to break free of a loop, and have a good look at something called a switch statement.

Break and Switch Statements in JavaScript

The Break Statement


There are times when you need to break out of a loop before the whole thing gets executed. Or, you want to break out of the loop because of an error your user made. In which case, you can use the break statement. Fortunately, this involves nothing more than typing the word break. Here's some not very useful code that demonstrates the use of the break statement: TeacherInterrupts = true counter = 1 while (counter < 11) { document.write(" counter = " + counter + "<BR>") if (TeacherInterrupts == true) break counter++ } Try the code out and see what happens.

Switch Statements
These types of statements can be very useful. A switch statement is used when you want to choose just one of several possible outcomes. Our age tester was a good example. We had several ages groups that we were testing for, and a person could be in only one of them. We used a series of if statements to test which one our user belonged to. A better way to do the testing is with a switch statement. Here, the value in Age is coming from a drop-down combo box on a form called frmOne: Age = document.frmOne.cmbAge.value switch (Age) { case "1": alert("still at school") break case "2": alert("still young") break case "3": alert("start lying")

break case "4": alert("start saving") break default: alert("undetermined") } The switch statement starts with the word switch. What you are testing for comes next, in round brackets. In the code above, we're testing what is inside the variable Age. Next, type a curly bracket {, then on a new line, you set a series of values that could be in the variable Age. Each value that could be in your variable is preceded by the word case. A colon comes after the value. If the value is going to be text, then use double quotes; if the value is going to be a number, don't use the quotes: case "1": All we're saying is, "If it is the case that the variable Age holds the value "1", then we've found a winner." Once a match has been found, any code after the colon ( : ) will be executed. For us, that was an alert box: alert("still at school") You have to tell JavaScript to break out of the switch statement. Just use the break statement, otherwise the next case down will get executed as well: case "1": alert("still at school") break It was mentioned that the value in Age was coming from a dropdown box on a form. Here's the HTML code for that: <FORM NAME = frmOne> <select name = cmbAge> <option value = 1>5 to 16</option> <option value = 2>17 to 30</option> <option value = 3>31 to 45</option> <option value = 4>46+</option> </select> </Form> We have four options in the drop down box, each with a value 1 to 4. It's this value that is going into the variable Age. Because the value from a HTML drop-down box will be a string (text) and not a number, each value for the case was surrounded by double quotes. Switch statements are an ideal way to check the value returned from a drop down box on a form. Instead of having an alert box in the case statement, you could direct your users to another web page. Like this:

page = document.frmOne.cmbAge.value switch (page) { case "1": document.URL = "page1.html" break case "2": document.URL = "page2.html" break case "3": document.URL = "page3.html" break case "4": document.URL = "page4.html" break default: alert("An error occurred so we're staying here") } The default is what you get when none of your case statements are true. All right, that's enough about Control Flow. By now, you should have a good idea of how things like if statements, for loops, and switches work. Of course, we can't expect you to have mastered the subject, so you may well have to revise this section until the knowledge sinks in. There is a steep learning curve here, so don't get too frustrated if you're having problems. We'll now move on to another tricky subject - arrays.

Hurray for Arrays!


You know what a variable is - just a little drawer in your computer's memory. Instead of holding socks or underwear, variables hold text and numbers. Except, a variable will hold only one value. You can store a single number in a variable, or a single string. An array is a variable that holds more than one number, or more than one string. Let's make a start on explaining how arrays work.

Setting up an Array
To set up an array in JavaScript you have to create an array object. This, for us, involves nothing more complicated that using the word new. Like this: Seasons = new Array(3)

The above code would set up an array that could hold four different values in it (arrays start at zero). To put something into each "slot" in the array, you'd just do this: Seasons[0] = "Winter" Seasons[1] = "Spring" Seasons[2] = "Summer" Seasons[3] = "Autumn" Our array is called Seasons. In between round brackets, we had an upper limit for the array - 3. (The number in round brackets is called the Index). When we're assigning values to each position in the array, we just type the name of the array, and then one of the numbers in square brackets. After typing the assignment operator (=), we type the value we want to go into that "slot" of the array. Another way to set up an array is to have all the values inside the round brackets of the word Array. Like this: Seasons = new Array("Winter", "Spring", "Summer", "Autumn") We still have an array with four values in it, but we've fixed the values inside of the round brackets. To get at the value inside an array, just use its index number. Like this: So putting that altogether in a script would give us this: <SCRIPT language=JavaScript> Seasons = new Array(3) Seasons[0] = "Winter" Seasons[1] = "Spring" Seasons[2] = "Summer" Seasons[3] = "Autumn" alert(Seasons[2]) </SCRIPT> Test out the script in a web page and see how it works. Change the value of the index from 2 to one of the other numbers and see what happens. Change the value of the index to a number higher than 3 and see what happens.

Array Methods
Here's another thing you can try. Add this line just before the alert box (on a line of its own): Seasons.sort() Now type in 3 as the index number in your alert box. The alert box will now display "Winter". Despite the fact that our array has Winter at position 0. The reason why it does this is because we used a

method for on our array - sort(). Because Array is now an object, we only need the array name followed by a full stop. After the full stop type the method you want to use. The sort() method will sort your array alphabetically. You can sort your array in reverse order with this: Seasons.reverse() In which case, the value in the last position will become the first value, the second last position will become the second value, etc. We can use another method of arrays to see this more clearly. Add this line after the sort() method: Seasons.join() So you should have this as your code: Seasons = new Array(3) Seasons[0] = "Winter" Seasons[1] = "Spring" Seasons[2] = "Summer" Seasons[3] = "Autumn" Seasons.sort() Seasons.join() alert(Seasons) When you test this code out, you should get a message box like this one:

However, if you use Seasons.reverse() instead of Seasons.sort() you'll get a message box something like this one:

There are a few more array methods you can use, but they are a touch advanced for us at this stage. For the record, they are: concat, pop, push, shift, slice, unshift. But try not to worry about them. In the next part, we'll take a look a closer look at that number in round brackets - the index number of an array.

The index number of an array

Arrays really come in to their own when you access their index numbers. You can use a variable in place of the index number. Then, if you increment the variable, you can access the elements in your array. As an example, try this script in a web page. For the web page, create a form called frmOne. Put a button on the form, and a text box called txtSeason. If you prefer, copy and paste this one: <FORM name = frmOne> <INPUT Type = text name = txtData> <INPUT Type = button value = " Seasons " onClick = GetSeasons()> </FORM> When you've got the form in place, add this script to the HEAD section of your code: <SCRIPT language=JavaScript> inc = 0 function GetSeasons () { Seasons = new Array(3) Seasons[0] = "Winter" Seasons[1] = "Spring" Seasons[2] = "Summer" Seasons[3] = "Autumn" document.frmOne.txtData.value = Seasons[inc] inc++ } </SCRIPT> We're setting up the array in exactly the same way. Now, though, we're calling a function with the onClick event of the button in the Form: onClick = GetSeasons() The function will set up the array. It also puts a value in our text box. But note what the value is - it's one of our elements in the array. But which element is it? document.frmOne.txtData.value = Seasons[inc] The inc is a variable. It was set up outside the function, making it global (all your functions can see a global variable): inc = 0 So the first value put into our text box is this: document.frmOne.txtData.value = Seasons[0] In the final line of the code, we then increment the variable: inc++ So every time the button is clicked, 1 will get added to the inc variable. The next time you click the button, the code is really this: document.frmOne.txtData.value = Seasons[1] When the value in the inc variable goes above 3, you'll get this in the text box: undefined

That's because we don't have a position number 4 in our array. You can reset the inc variable like this: if (inc > 3) inc = 0 That should prevent "undefined" from displaying in the text box. Arrays are used a lot inside loops. We're going to see how that works now by creating a lottery number generator. But before continuing you should ensure that you have a good understanding of how for loops work. If not, go back and revise. In the next part, we'll start work on a lottery programme.

Arrays and Loops


If you want to assign a value to a position in an array, you can just do this: Array[9] = "Hello World" To display the value, just access its index number again: alert(Array[9]) The fact that you can access the index number of an array to assign values makes them very handy in loops. To start our lottery number generator (UK lottery), we're going to create an array of 49 numbers. Number 1 will be at position 1 in the array, number 2 at position 2, etc. We could do this for all 49 numbers: Lottery = new Array(49) Lottery[1] = 1 Lottery[2] = 2 Lottery[3] = 3 Lottery[4] = 4 But we'd have a laborious job typing all the array positions out, and all the values for them. Instead, we can use a loop to fill our array with the numbers 1 to 49. Here's the loop we can use: for (i = 1; i < 50; i++) { Lottery[i] = i } Isn't that easier? But how does it work? Well, first we set a start position for our for loop by assigning 1 to the variable called i (i = 1). The end position for our loop is when the variable i is not less than 50 (i < 50). Every time round the loop 1 gets added to i (i++). Then we assign the value of i to a position in our array: Lottery[i] = i At first, the value in i is 1. Which gives us this in reality: Lottery[1] = 1 The next time round the loop, 1 gets add to the variable i. So we'd then have this:

Lottery[2] = 2 By the time the loop ends, all 49 positions in our array would be filled with the numbers 1 to 49. And that's all there is to it - a couple of lines of code has saved us reams of typing! To demonstrate that it does indeed work, create this form on a new web page: <Form name = frmOne> <textarea name = taAll rows = 10 cols = 15></textarea> <INPUT Type = button Value = " Get Lottery Numbers" onClick = getNumbers()> </form> Make sure your form has the NAME frmOne, and that your TEXTAREA has the NAME taAll. For the button, you're adding a onClick event which calls the function getNumbers(). When you have your form in place, add this script to the HEAD section of your web page: <SCRIPT Language = JavaScript> function getNumbers() { TA = document.frmOne.taAll lottery = new Array(49) for (i = 1; i < 50; i++) { lottery[i] = i TA.value = TA.value + lottery[i] + "\n" } } </SCRIPT> To see what your programme should do, click this link (opens in a new window): Click here for the Script in action We've started the script with a function: function getNumbers() { } The first line inside the function is just assigning the text area on our form to a variable call TA. This will make things easier for us, and we won't have to keep typing it all out when we want to add things to the text area: TA = document.frmOne.taAll On the next line, we set up our array: lottery = new Array(49) Next comes our for loop: for (i = 1; i < 50; i++) { lottery[i] = i TA.value = TA.value + lottery[i] + "\n" } Notice the line that has been added to the for loop: TA.value = TA.value + lottery[i] + "\n"

All that line is doing is adding the values in our array to the text area. We want to keep whatever is inside the text area, so we have to say: TA.value = TA.value + Then we add the value from the array, with a new line character at the end: lottery[i] + "\n" When you've finished adding the code to the HEAD section, test it out. When you click the button, the numbers 1 to 49 will be added to your text area. For a lottery, though, we need to shuffle all the numbers. Otherwise, everybody would win!

Shuffling the numbers in an Array


OK, the next thing we want to do is shuffle our numbers up. Once the numbers are shuffled up, we can just peel off the first six for our lottery numbers. Again, we'll use arrays inside loops to do this for us. The code that shuffle the numbers up might be a tad complex at this stage of your programming career. The code is this: for (i = 1; i < 50; i++) { newnumber = (Math.random() * 49) + 1 newnumber = parseInt(newnumber, 10) temp = lottery[i] lottery[i] = lottery[newnumber] lottery[newnumber] = temp } When you add it to your other code, your script should look like this (new code is in red bold text): <SCRIPT Language = JavaScript> function getNumbers() { temp = 0 newnumber = 0 document.frmOne.taAll.value = "" TA = document.frmOne.taAll lottery = new Array(49) for (i = 1; i < 50; i++) { lottery[i] = i } for (i = 1; i < 50; i++) { newnumber = (Math.random() * 49) + 1 newnumber = parseInt(newnumber, 10) temp = lottery[i]

lottery[i] = lottery[newnumber] lottery[newnumber] = temp } } </SCRIPT> The first few new lines are just setting up variables temp and newnumber, and clearing the text area: temp = 0 newnumber = 0 document.frmOne.taAll.value = "" Notice, too, that the code that inserted numbers into the text area has now been cut. We'll use another for loop to display the shuffled numbers. So our first for loop is just this: for (i = 1; i < 50; i++) { lottery[i] = i } That's the for loop that puts the numbers 1 to 49 into our array. But they are in a nice orderly fashion. What we want is to shuffle them up a bit. Hence our rather complex second for loop: The idea behind our shuffle code is this: Grab a random number from 1 to 49. Store the current array value in a temp variable. Get the array[Random Number] value and put this into the current array value. Swap the current array value with the array[Random Number] value. That explanation might not be quite so crystal clear, but all the code is doing is swapping numbers around. The first two lines in the for loop get us our random number: newnumber = (Math.random() * 49) + 1 newnumber = parseInt(newnumber, 10) The code Math.random() gets you a random number between 0 and 1. We're then multiplying that random number by 49, then adding 1. This will ensure that we get a random number between 1 and 49. Except, the number will be a floating point number. A rather long one. Something like this: 12.34528569 To chop off the part after the point, we can use the in-built function parseInt(). We need only pass it the number and what numerical base we want (10 will get you decimal). The rest of the code works like this (assuming the random number generated is 12) temp = lottery[1] lottery[1] = lottery[12] lottery[12] = temp In other words, the numbers 1 and 12 have swapped places. Don't worry if you don't understand what's going on. The rest of the code is a lot easier.

OK, we've found a way to jumble up all our nice, orderly numbers. Now what? Well, we can use a loop to display the results of all that jumbling. Add this for loop underneath the code that shuffled the numbers: for (i = 1; i < 50; i++) { TA.value = TA.value + "lottery[" + i + "] = " + lottery[i] + "\n" } All the code inside that loop is doing is putting the array values into the text area. It's adding a bit of text along side the values as well. Try it out and see what happens. You should now see something like this in your text area (click the link to test out the programme so far): Click here for the Script in action As you can see, our 49 numbers are nicely shuffled. All we need to do now is peel off the first six numbers and we have our very own lottery number generator. Which brings us neatly to an exercise.

Exercise
Write the code that peels off the first six numbers. Display the results in a separate text area on the web page. Click here to see what your script should do

Exercise
Amend your lottery programme to include the following:

Six text boxes for entering lottery numbers One text box to display how many numbers came up One text box to display the number of draws

The finished programme might look something like this: Click here to see what your Lottery Programme might look like For this exercise, you're writing a programme that checks the lottery numbers from the six text boxes. The numbers in the six text boxes will be checked against those drawn in the text area under "winning lottery numbers". Display how many numbers were correctly guessed. Display how many draws there have been. (This number will be incremented every time the "Get Lottery Numbers" button is clicked.) You have already written most of the programme. To check the numbers in the text boxes against the winning numbers, you'll need

one for loop inside another. Add a counter to record the number of winnings numbers. And that wraps up this section on the basics of programming. You can move on to the next section, which is all about javascript Events, and javascript functions.

Javascript Events - Browser Detection


You have already met a few JavaScript events that you can use in your code. The one you're most familiar with is onClick. You have also met the onMouseOver event and the onMouseOut event. These events are just special in-built instructions to the browser. The browser sees the event name, and knows that some code is coming up that it needs to execute. You don't really have to worry about how the browser executes the events. With JavaScript, what you should concentrate on is what the events do, and how you use them. Here, then, is a list of (some) events you can use with JavaScript: onClick onDblClick onDragDrop onKeyDown KeyPress KeyUp MouseDown MouseMove MouseOut MouseOver MouseUp Move Resize onLoad onUnload onChange onReset onSelect onSubmit The problem is that although most browsers recognise those events, the event itself can be quite torturous to use, especially since Netscape came up with the Event Object. The Event Object is a way for the window itself to record events. For example, if the mouse was clicked in the window you can record the position of the mouse pointer. But Internet Explorer doesn't recognise this Event Object of

Netscape's. So any code you write which uses the Netscape's Event Object will cause an error if the page is loaded into Internet Explorer. The standard way round this is to write code which detects the browser type. Because there are a lot of other things that one browser can do that the other can't, browser detection is considered good practice. In this next segment, we'll look at one way to detect which browser the user has (Netscape or Internet Explorer), and then direct them to the relevant code. The code they'll get tells them the mouse position on the screen. You'd better hang on to your hats, though, because this could be quite a bumpy ride!

Browser Detection
We start detecting the browser with the navigator object. You met this object earlier. It's quite simple: Browser = navigator.appName The appName property will tell us whether the user has Netscape or Internet Explorer (we're assuming just these two are used). The variable Browser will then hold either the text "Netscape" or "Microsoft Internet Explorer". Next, we need to search that text for either the word "Netscape" or the word "Microsoft". Net = Browser.indexOf("Netscape") Micro = Browser.indexOf("Microsoft") One way you can search text is with the in-built function indexOf. Remember, our variable Browser is holding the text. After typing a full stop, you type indexOf followed by a pair of round brackets. Inside the round brackets you put the text you're looking for. The text you're looking for goes in double quotes if it's direct text. (No quotes are used if the text you're looking for is in a variable.) Browser.indexOf("Netscape") All that means is, "Search whatever is inside the variable Browser and find out if the word Netscape is there." If Netscape is there, what will be returned is the position of the first letter of the word Netscape. The search starts at position zero. If the word Netscape is not found, what will be returned is the number minus one (-1). Our two variables, Net and Micro, will then hold either zero or greater, or minus one. Net = Browser.indexOf("Netscape") Micro = Browser.indexOf("Microsoft")

We can use an if statement to test which one holds the minus one, and which one doesn't: Here's the entire script. Place it in the HEAD section of a web page and try it out. <Script language = javascript> Browser = navigator.appName Net = Browser.indexOf("Netscape") Micro = Browser.indexOf("Microsoft") Netscape = false IE = false if(Net >= 0) { Netscape = true alert("You're using Netscape") } if(Micro >= 0) { IE = true alert("You're using Internet Explorer") } </script> And that's it - a simple (ish) way detect which browser is being used. However, more code would usually need to be added. This is because some older versions of Netscape or Internet Explorer wouldn't be able to process this next code. So you would need to get which version of Netscape or Internet Explorer was being used. You'd use navigator.appversion for this. But as this is supposed to be as section on events, we'll leave that aside. In the next part, we'll explore the onMouseDown event.

JavaScript Events - OnMouseDown


What we'll do in the pages that follow is to detect the position of the mouse pointer when the user clicks on the screen. To do that, you need to find the X coordinate and the Y coordinate.

The X coordinate tells you how far left of the screen you are The Y coordinate tells you how far down the screen you are.

Both Netscape and Internet Explorer use the screenX and screenY property. If you're sure that your users will all have Internet Explorer, then the task is fairly easy. Here's the script: <HEAD> <TITLE>XY Coordinates</TITLE> <SCRIPT Language = javascript> function XYpos() { xPos = event.screenX

yPos = event.screenY alert(xPos + " left " + yPos + " down") } </Script> </HEAD> <BODY onMouseDown = XYpos()> You can click the link below to see what the script does (opens in a new window): Click here to see the script in action The BODY section of the HTML is where we put the event handler onMouseDown. Now, every time the mouse is clicked anywhere in the Body of the web page, the function XYpos() gets called. Inside the function, the property screenX and the property screenY (which are both properties of event) are put inside two variables: xPos = event.screenX yPos = event.screenY So xPos will hold how far left the mouse pointer is when the page is clicked; and yPos will hold far down the mouse pointer is when the page is clicked. Both coordinates are then displayed in an alert box: alert(xPos + " left " + yPos + " down") If you have Netscape, however, the code will point blank refuse to work! If we add our Browser detector code to the script above, though, we can get Netscape to display an error message. Try changing you code to this: <Script language = javascript> Browser = navigator.appName Net = Browser.indexOf("Netscape") Micro = Browser.indexOf("Microsoft") Netscape = false IE = false if(Net >= 0) { Netscape = true } if(Micro >= 0) { IE = true } function XYpos() { if (IE == true) { xPos = event.screenX yPos = event.screenY alert(xPos + " left " + yPos + " down") } else if (Netscape == true) { alert("Script won't work: " + "\n" + "You're using Netscape")

} } </script> Click here to try the script out (especially if you have Netscape/Mozilla) After the browser detection code, we've added our XYpos() function. This time, we've put some if statements in it. If the user has Internet Explorer, we're all right; if the user has Netscape, display the message: function XYpos() { if (IE == true) { xPos = event.screenX yPos = event.screenY alert(xPos + " left " + yPos + " down") } else if (Netscape == true) { alert("Script only works with Internet Explorer - sorry!") } } So Internet Explorer's way to get the coordinates of the mouse pointer is not too difficult. The reason why the script is so long is simply because Netscape refuses to cooperate. We therefore have to add browser detection code and do one thing for Internet Explorer and do another thing for Netscape. If you want to detect the mousedown event with Netscape then the process is quite complicated. We won't go into here, but you can click the link below to see the script in action. To view the source code, click View > Source in Internet Explorer. Netscape/Mozilla users should click View > Page Source. When you see the code, you'll know why we didn't go into it! Click here to see the Netscape/Mozilla version But that's enough of complicated events. I'm sure you've had your fill. In the next part, we'll take a look at some simple events, as we go through the list. (Shawn sent me the following in an email, for which I thank him. This works in both IE and FireFox/Mozilla. Try it, if you have both browsers: function XYpos(event){ alert(event.screenX + " left " + event.screenY + " down") } <body onClick= XYpos(event) bgcolor = white> As he says, Much simpler!)

JavaScript Events

onClick
We've already used this event quite a lot. But you can use it with buttons, images, links, radio buttons, check boxes. Here's a simple onClick event used with an image: <IMG SRC = red.jpg onClick = "alert('No stealing the images!')">

onDblClick
Same as above, really. Try inserting Dbl into onClick and see what happens.

onKeyDown
This events fires when a key on your keyboard is pressed. It applies to buttons, textboxes, text areas, and links. If you had a search box on a form, for example, you might want to activate the search when the user presses the Return/Enter key on the keyboard. For Netscape users, though, you need to use this: window.captureEvents(Event.KEYPRESS) And that's only the start of your problems! An easier example of the KeyDown event that works in both browsers is this: <INPUT type = text onKeyDown = "alert('Key pressed')">

onMouseOver
You've seen this in action already when we wrote the script for the "dancing hand". Associated events are onMouseOut and onMouseDown. They are mainly used for links and images. A typical use of onMouseOver is to swap images around when creating a rollover effect.

Onblur
This event takes places when objects lose focus. If you click inside one text box then click outside it the textbox has lost focus. That's when the onBlur event fires.

<INPUT TYPE = text onBlur = "alert('Lost focus')"> Here's an example. Click inside the first text box, then click inside the second one. When you move away from the textbox, you should see the alert box. You can write code to check if something like an email address is correct. If not, you can reset the text box to a blank string.

onSubmit
This is a very useful event that can be used for data validation on a form. You can use this event with a Submit button. The details on the form can then be checked for errors. If you catch any errors, you can then stop the form's details from being submitted. Here's an example. Note the use of the word return. This is set to a Boolean value. If return is false then the form doesn't get submitted; if it's true then the form is submitted. (More about return in the next section.) <FORM name = f1 onSubmit = "return Validate()"> <INPUT Type = Submit Value = " Send "> </FORM> The form is not much good because it only has a submit button. But notice where the onSubmit event is - in the FORM tag, and not with the Submit button. Here's the Validate() function. It doesn't do any checking. All it does is to display an alert message. function Validate() { Details = false if (Details == false) { alert("errors detected") return false } if (Details == true) { alert("Form Submitted") return true } } In the function, we've set a variable (Details) to false. This is just for testing purposes, and means the user has filled out the form incorrectly. Look at the two return values, though. If the Details are false then return gets set to false, and the form isn't submitted; if the Details are true then return is true, and the form is submitted.

If you want, add a Method and an Action to your Form. Like this one: <form name = f1 onSubmit = "return Validate()" Method = post Action="Mailto:MyEmailAddress@MyISP.com" Enctype="text/plain"> (The Enctype will send the details in plain text that's much easier to read.) Test out the code on a web page. Change the Details variable to true and click the button. We're going to do some real error checking in the next section, and we'll meet onSubmit again. Speaking of that next section - let's get right to it.

JavaScript Functions
We've already used functions a fair bit in these pages. We're going to explore them a bit further. Functions, if you remember, are simply sectioned-off pieces of code. When you want to use your code segment, call it by its name and it will come running. We're now going to design a little calculator. It's limited in what it can do, as it only calculates two numbers at a time. It can add, divide, multiply and subtract. To save you time designing the HTML for this calculator, you can get a copy by clicking the link below. When the web page opens, click File > Save and save it to your hard drive. Click here for the HTML code Nice, isn't it? Only the HTML is included in the code for the web page. All the script tags have been taken out, so it won't work. But we'll see how functions work with this calculator. Off we go then. To work the calculator, press a number. Then press an operator (plus, times, subtract, or divide). Press another number, then press the equals button (=). If you want to clear the display, click the cls button.

Passing a value to a function


So far with functions, we have just been doing this sort of thing: function add() { Our code segment here } The name of the function is add. Immediately following the name are a pair of round brackets ( ). To call (use) our functions, we've doing this:

<Input Type = button onClick = add()> Inside the round brackets, we haven't put anything. They have been empty brackets. But functions are given extra power by putting something inside the brackets. This "something" is called an argument. An argument is really just a variable. What you're doing by giving your function an argument is passing a value to your function. We're going to do that with our calculator. Our first function will accept one argument. The value being passed to our function comes from the number buttons on our calculator. If you have a look at the HTML calculator code in the page you saved, you'll see this for the buttons: <Input type = button name = b1 value = " 3 " onClick =calculate(3)> The value above is the text on the button face. This is the number three button. When this is clicked, the number three will appear in the display. Look at the onClick event: onClick =calculate(3) The onClick event is calling our function, which has the name calculate(). However, we've now put something inside of the round brackets. We've put the number three in there, which is the value of our button. Here's the function we're going to add, minus any code: function calculate(number) { } Our function now accepts an argument - number. This is a variable into which we can place values. When the 3 button is clicked on the calculator, a value of 3 will be placed into the number variable. If another button is clicked, the 7 button for example, a value of 7 will be passed to the number variable. We can then use this number variable in our code for the function: function calculate(number) { frm = document.frmOne.txtDisplay frm.value = frm.value + number } You should be able to work out what the code for the function does, but here's an explanation. The Display textbox is first put into a variable called frm. We then add whatever is in the variable number (our argument) to whatever is already in the display text box. Here, add means "join together". So if you wanted 22 in the Display text box you would click the 2 button twice. This is a nice, simple function that display numbers in a text box. You can add the function to your calculator. Either type or copy and paste the function into the HEAD section of your code. OK, now that we know how to pass a value to a function, we can set up a second function to deal with the operators. When you click one of the operator buttons (plus, minus, etc) you can pass the operator

to a new function in the same way you've just done. First, set up the onClick event in the HTML form (this has already been done): <Input Type = Button value = " plus " onClick = operator("+")> Notice the name of our new function, and the value we are going to pass to it when the "plus" button is clicked: onClick = operator("+") What we're passing to our new function is the plus symbol ( + ). We're passing it as a string, hence the double quotes surrounding it. For the divide button, we have this for the onClick event: onClick = operator("/") In other words, a different symbol will be passed to our new function depending on which operator button is clicked. Here's the code for the function: function operator(opval) { TheOperator = opval total = document.frmOne.txtDisplay.value document.frmOne.txtDisplay.value = "" } This time, the variable inside our function is called opval. This is our argument. When an operator button is clicked, opval will contain one of our four symbols. Inside the function we then pass this value to a variable which we have called TheOperator. Besides passing the operator symbol to a variable, this function also gets the value from the display and passes it to a variable called total. The text box is then cleared ready for another number to be entered. So add this new function to your script, just below the first one. However, the variables total and TheOperator need to have their values read from another function. So we have to make them global. We do this by declaring them at the top of the code, just before the first function: <SCRIPT Language = JavaScript> var total = 0 var TheOperator = 0 function calculate(number) { frm = document.frmOne.txtDisplay frm.value = frm.value + number } function operator(opval) { TheOperator = opval total = document.frmOne.txtDisplay.value document.frmOne.txtDisplay.value = "" } </SCRIPT> With our two global variables set up, we can now do the calculating part. The calculating is done when the equals sign is clicked on the

calculator. Again, we do this with an onClick event. This time from the equals button on the form: <Input Type = Button value = " = " onClick = equals()> We don't need to pass anything to our equals function (it's a simple little code segment), so we're back to the empty round brackets. This means that it's a function that doesn't accept arguments. Here's the entire function that does the calculating: function equals() { CurentDisplayValue = eval(document.frmOne.txtDisplay.value) PreviousDisplayValue = eval(total) if(TheOperator =="+") { answer = PreviousDisplayValue + CurentDisplayValue } else if(TheOperator == "*") { answer = PreviousDisplayValue * CurentDisplayValue } else if(TheOperator == "-") { answer = PreviousDisplayValue - CurentDisplayValue } else if(TheOperator == "/") { answer = PreviousDisplayValue / CurentDisplayValue } document.frmOne.txtDisplay.value = answer } The code looks a tad messy, but that because of the variable names we've chosen to use. First, we pass whatever is currently in the Display text box to a variable called CurentDisplaValue: CurentDisplayValue = eval(document.frmOne.txtDisplay.value) The eval() part just ensures that JavaScript doesn't try to concatenate when we want to add up. The second line of our code gets the value stored in our global variable total and passes it to the new variable called PreviousDisplayValue: PreviousDisplayValue = eval(total) The rest of the code just uses if statements to check what is inside our other global variable TheOperator. The final line just pops the answer into the Display text box. And that's it. A very simple calculator that demonstrates how to pass values to functions by setting up arguments. You can pass more than one argument at a time to a function. But we've kept things simple by using only one argument with each function. Add the new code to your calculator and see it in action. When you get it working, it should be like the one in this link below: See the Working Calculator In the next part, we'll see how to use functions to validate data on a form.

Calling other functions within a function


Functions can call other functions, and have a value passed back to the calling line. We'll see how that works now. Once you have grasped the concept, what we're then going to do is write code to validate data that a user might enter on a form. First, though, here's an example of a function being called inside another function. To test it out, create a web page with a button on it. Set the onClick event for the button to this: onClick = GetValue() Once you have your web page with a button on it, add this code to the HEAD section of the page: <Script language = JavaScript> function GetValue() { returnvalue() } function returnvalue() { n1 = 10 n2 = 5 answer = n1 - n2 return false } </SCRIPT> When the button on your page is clicked, it calls the function GetValue(). The only line of code in the GetValue() function calls the second function: returnvalue() When this second function is called, all the code inside it is executed. Control then passes back to the first function. Any other lines for the first function are then executed. Notice the line of code that reads return false. We really should have had this return word at the end of all our functions. It's actually a question: "Does the function return a value?" In other words, Are we finished with this function or not? If the function does return a value you can either use return true, or more likely you can return a value back to the first function. In our second function, we were subtracting one number from another and putting the answer into a variable called answer. But we weren't doing anything with this variable, so nobody would be able to see what the answer was. In this next example, we'll return the answer to the first function: function GetValue() {

total = returnvalue() alert(total) } function returnvalue() { n1 = 10 n2 = 5 answer = n1 - n2 return answer } The first function now does something slightly different. The call to the second function, returnvalue(), has gone on the right hand side of an equals sign (= ). On the left hand side of the equals sign we have a variable called total. What we're saying here is "Assign the value of returnvalue() to the total variable." But the same thing happens: the second function is called and has its code executed. However, we've now told the second function to return a value: return answer And what's inside the answer variable? The answer to the sum 10 5. This is the value that gets passed back to the calling line, which was: total = returnvalue() Now the variable total will hold the value from the function. Finally, we've displayed the result in an alert box. Run the code and see how it works.

Passing values to a function


When we called the second function above, we didn't pass any values to it. The round brackets of our function were entirely empty: total = returnvalue() They were empty because the second function accepted no arguments. Here's the same code again, but this time the second function does accept an argument. In fact, it accepts two arguments: function GetValue() { total = returnvalue(10, 2) alert(total) } function returnvalue(num1, num2) { answer = num1 - num2 return answer } The function returnvalue() is now this: returnvalue(num1, num2)

We've set up two variable inside the round brackets called num1 and num2. When we call the second function from the GetValue() function we put something into those two variables: total = returnvalue(10, 2) Now, the numbers 10 and 2 will be passed to the second function. These values will be stored in the two variables. The 10 will be stored in num1 and the 2 will be stored in num2. Once the values are in the second function, you can do something with them. All we did was subtract one from the other, and stored the result in the variable answer. The value in answer was then returned to the calling line: return answer OK, now you know how to call function, and have one function call anther, we can do some work on form validation.

JavaScript Form Validation


The form you'll work with is quite simple. It will be used only for your visitors to leave their name, email address and some comments. They will be invited to say what they liked about the site, and what they didn't like. This will be done with check boxes. The form we're going to use can be copied to your own computer by clicking the link below. When the web page loads, save a copy to your hard drive. So load it up and let's do some coding. Click here to see and save the Form When the Submit button on the form is clicked, we'll use functions to validate the form. If we detect anything not quite right, we'll invite the user to try again. If the form is OK, we'll send it to an email address. The first thing to do is to set up a function to handle the onSubmit event. This function will call other functions: one function to check the Name text box, one to check the email address, and so on. So open up the code for the form. Notice the names of our form elements: Form Name: f1 Name textbox: Name Email textbox: Email Comments text area: Comments Likes Checkboxes: Liked Dislikes Checkboxes: Hated Submit Button Event: Validate() And here's the function for the Submit event: function Validate() {

Message = "" Message = Message + CheckName() Message = Message + CheckEmail() Message = Message + CheckComments() Message = Message + CheckLikes() Message = Message + CheckHates() if (Message == "") { return true } else { alert(Message) return false } } All we're going to be doing is building up a variable called Message. At the start, Message is set to a blank string: Message = "" If, after all our functions have been called, Message is still a blank string, then no errors have occurred. If no errors have occurred, we can set return to true. Setting return to true will ensure that the form gets sent. If an error has occurred, then a function will insert some text into the Message variable. If Message contains any text, then return gets set to false. When return is false the form doesn't get sent, and the message itself will be displayed in an alert box: if (Message == "") { return true } else { alert(Message) return false } Look at the lines that call the functions, though. Here's the first one, the function that checks the Name textbox: Message = Message + CheckName() So we're saying "Put into the variable Message the value returned from the function CheckName(). Keep what was originally in the variable Message." Here's the function to add to your code: function CheckName() { UserName = document.f1.Name.value if (UserName == "") { Message = "Something's wrong with your name" + "\n" } else { Message = "" }

return Message } First, we put the value from the Name textbox into a variable called UserName: UserName = document.f1.Name.value Then we have an if statement to check what is inside of UserName. If the textbox is blank then the user hasn't entered a name, and the variable UserName will be a blank string. In which case it's an error. If there is something in the textbox then no error has occurred and we can set the Message variable to a blank string. if (UserName == "") { Message = "Something's wrong with your name" + "\n" } else { Message = "" } Finally, we tell the function to return whatever is inside the Message variable: return Message So after the first function call we'd really have either this: Message = "Something's wrong with your name" + "\n" Or this: Message = "" If it's the first one, the form won't get sent; if it's the second one, then the user filled the name in correctly. In the next part, we'll continue with the functions on our form. We'll tackle email addresses next.

Using JavaScript to Validate an Email Address


Checking for a valid email address is a little more difficult. We have to make sure that the user typed an "at" sign ( @ ). But we also have to make sure that there's "dot" something at the end: .com, .co.uk, .net or whatever. But we also have to check that these are in the right place. If we don't, then the user could enter this: My.com@FooledYou instead of something like this: FooledYou@MyISP.com In order to check the email address, we can use the in-built JavaScript functions indexOf() and its brother function lastIndexOf(). The syntax for the functions is this: stringName.indexOf(searchValue, [fromIndex])

Here's an example: Email = "FooledYou@MyISP.com" AtPos = Email.indexOf("@") Email is the String Name, the text we want to search. The function indexOf() will then search that text for you. But you have to tell it what to search for. In the example, we told it to search for an "at" sign ("@"). We could have told the function what position in the string to start the search [fromIndex]. But you can leave that out if you want to search all the string. The function will then start the search from the beginning of your string. If the function indexOf() finds our "at" sign, it will return a number. The number is the position in the string where the "at" sign was found. If it doesn't find it, minus one (-1) will be returned. The related function lastIndexOf() does exactly the same thing, except it starts the search from the last character in your string and works backwards. Let's build our function to check for a valid email address. We can start with this: function CheckEmail() { email = document.f1.email.value AtPos = email.indexOf("@") StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { Message = "Not a valid email address" } } We start by passing the email address from the text box to a variable called email: email = document.f1.email.value We then use the indexOf() function to check if the email contains an "at" sign: AtPos = email.indexOf("@") We can then use the lastIndexOf() function to get the position of the last full stop: StopPos= email.lastIndexOf(".") If the two functions have found something, the two variable AtPos and StopPos will both contain numbers greater than minus one (-1). We add an if statement to check what is inside of these two variables: if (AtPos == -1 || StopPos == -1) { Message = "Not a valid email address" } In the if statement, we're saying "if the variable AtPos has a value of -1 OR ( | | ) if the variable StopPos has a value of -1 THEN put some text into the variable Message. Set the return value of the function to false."

Remember: the OR operator (| |) will return a value of true if any one of its conditions are met. When an if statement is true, the code inside the curly brackets will get executed. OK, once we're satisfied that the email does contain an "at" sign and a full stop, we can add another if statement to check whereabouts these two symbols are in the email address. We don't want the user to enter something like this: My.com@FooledYou In the above email address, there is a full stop and an "at" symbol. So the function lastIndexOf() will have returned the position of the last full stop, and the function indexOf() will have returned the position of the "at" sign. However, the email address is not a proper email address. We can prevent this error with our second if statement: if (StopPos < AtPos) { Message = "Not a valid email address" } The variable StopPos is recording the position of the last full stop in the email address. If this position is less than the position of the "at" symbol, then we have an error. In which case the Message variable will contain some text. Another thing we can check for is this type of error: FooledYou@.com In the address above, the last full stop comes after the "at" sign. Our two previous if statement will not have picked this up. However, the email address is still invalid: there is no address to send it to! We can add another if statement to check for this: if (StopPos - AtPos == 1) { Message = "Not a valid email address" } The above if statement will check the numerical difference between the full stop position and the "at" position. If the difference is only 1, then we've caught the error. And that's about it for our email checker. There are still one or two things you'd need to check about the email address. These two addresses for example will slip through the net: @FooledYou.com Me@FooledYou. So you might want to (and should now be able to) write if statements to check for these errors. function CheckEmail() { email = document.f1.Email.value AtPos = email.indexOf("@") StopPos = email.lastIndexOf(".") Message = ""

if (email == "") { Message = "Not a valid Email address" + "\n" } if (AtPos == -1 || StopPos == -1) { Message = "Not a valid email address" } if (StopPos < AtPos) { Message = "Not a valid email address" } if (StopPos - AtPos == 1) { Message = "Not a valid email address" } return Message } We've added another if statement to the function. All it does is check to see if there is anything in the email text box at all: if (email == "") { Message = "Not a valid Email address" + "\n" } A new line character has also been added ("\n" ). In the next part, we'll see how to validate and return checkboxes values.

JavaScript and Checkboxes


The only thing we're going to do with our check boxes on our form is to see if they have been ticked or not. If a box has been ticked, then no errors have occurred; if none of the boxes have been ticked, then an error has occurred, and the user will get an alert box. So our check box validation is a "yes" or "no" affair: Have they ticked a box or not? What we're not doing is returned the text from the check boxes. The text for our check boxes was "Cool layout", "Easy to Navigate", etc. We're not passing these values back when the Submit button is clicked. All the same, we'll see how this is done. On our Form, the Check box HTML code was this: <input type="checkbox" name="Liked" value="Cool Layout">Cool Layout <input type="checkbox" name="Liked" value="Easy to Navigate">Easy to Navigate <input type="checkbox" name="Liked" value="Great Contents">Great Contents The NAME value is crucial. For all our check boxes, the NAME is the same - "Liked". The text that people see on the page comes after

the right angle bracket ( > ). The VALUE of the checkbox is the same as the text that people see on the page. (But it doesn't have to be). With this in mind, here's our Check Box function: function CheckLikes() { boxes = document.f1.Liked.length txt = "" for (i = 0; i < boxes; i++) { if (document.f1.Liked[i].checked) { txt = txt + document.f1.Liked[i].value + " " } } if (txt == "") { Message = "No Boxes ticked" } else { Message = "" } return Message } We start the function by getting the length of the check boxes: boxes = document.f1.Liked.length The length here means "How many Check Boxes are there". So our code reads "Of all the check boxes in the form called f1, how many are there with the name Liked?" The answer will be inserted into a variable called boxes. After we set a variable called txt to a blank string (txt = "") we add a for loop to check all of the boxes with the NAME Liked: for (i = 0; i < boxes; i++) { if (document.f1.Liked[i].checked) { txt = txt + document.f1.Liked[i].value + " " } } Because we've given all of our checkboxes the same NAME, the browser can see them as an array of checkboxes. With an array, we can loop round checking values. The for loop is set to start at zero, and the end condition is that value we put into the variable boxes - the number of checkboxes on our form. Inside the loop, we can access the index number of each check box: if (document.f1.Liked[i].checked) Because the for loop started at zero, the check box Liked[0] will be examined first. If it has been checked, a true value is returned. The statement below is then executed: txt = txt + document.f1.Liked[i].value + " "

The VALUE from the check box Liked[0] is added to the variable called txt. Next time round the loop, the variable i will be 1. So the second check box will be examined to see if it was checked or not. If it has been, the VALUE of the checkbox is added to the txt variable. And we go round and around examining the checkboxes called Liked. At the end of the loop, the variable txt will either hold the values from the check boxes, or it will still be a blank string. Depending on which it is, we can return a value for our function: if (txt == "") { Message = "No Boxes ticked" } else { Message = "" } return Message Again, we're building up our Message variable. Or not building it up, if no boxes have been ticked. The function for our second lot of check boxes, the ones called "Hated", works in exactly the same way as the function above. Except you would changed the "Liked" to "Hated". And that concludes our script to check form elements for errors. Once you add all the code, and test it out, you'd get a message box when the form is submitted but nothing has been entered. Try out the code by clicking the link below. Leave everything blank, then click submit. Click here to see the Form with all the code added To see all the code, click View > Source (in Internet Explorer). In the next few parts, we'll take a look at how to validate other form elements: drop down boxes, list boxes, and Radio Buttons.

Using JavaScript to Validate a Drop Down Box


A drop down box on a form allows you to select one option among many. It looks like this: Here's the HTML code for the above drop down box: <SELECT NAME = s1> <OPTION VALUE = "NE" selected >North East</OPTION> <OPTION VALUE = "NW">North West</OPTION> <OPTION VALUE = "SE">South East</OPTION> <OPTION VALUE = "SW">South West</OPTION>

<OPTION VALUE = "Midlands">Midlands</OPTION> </SELECT> Notice the NAME of our Select box (as the drop down box is called in HTML world). The NAME we've chosen is s1. The name of our form is f1. So here's a function that gets which item the user selected: function GetSelectedItem() { len = document.f1.s1.length i=0 chosen = "none" for (i = 0; i < len; i++) { if (document.f1.s1[i].selected) { chosen = document.f1.s1[i].value } } return chosen } The code is similar to the check box code. We set the length of the select box (length is how many items in the list, minus 1 item): len = document.f1.s1.length Then inside the loop, we again access the index number of the SELECT object: document.f1.s1[i].selected So, s1[0] is the first item in the list, s1[1] the second item, s1[2] the third, and so on. Once the selected item has been detected, you access it's value property and pop it into a variable: chosen = document.f1.s1[i].value You can test out the script by selecting an item from the box below. What we've done with this box is to add an event to the select box. The event calls the function: <SELECT NAME = s1 onChange = GetSelectedItem()> In the next part, we'll see how to get at which items have been selected in a list box.

Using JavaScript to Validate a List Box


A form element closely related to the Select element is the Multiple select. This time, the elements is a list box where you can select more than one item. You select more than one item by holding down the Ctrl key on your keyboard and then clicking items with your left mouse button. Here's what they look like:

To get which items have been selected, we can use the same code we used for the drop down list. The only difference is the line inside the if statement: function GetSelectedItem() { len = document.f1.s1.length i=0 chosen = "" for (i = 0; i < len; i++) { if (document.f1.s1[i].selected) { chosen = chosen + document.f1.s1[i].value + "\n" } } return chosen } The main thing that's changed is this line: chosen = chosen + document.f1.s1[i].value + "\n" And the only thing we're doing different is adding the selected item to whatever is already inside the variable called chosen and we've added the new line character to the end. Also changed is chosen = "" insted of "none", As a matter of interest, the HTML code for a Multiple select list box is this: <SELECT NAME = s1 size = 5 multiple> SIZE is how many items in the list (starting at 1). Then you just add the word multiple. The rest of the HTML code is the same as the SELECT box. You can test out the script by selecting a few items from the box below. Then click the button. In the final part of the Form Validation section, we'll take a look at how to validate Radio Buttons.

Using JavaScript to Validate Radio Buttons


Radio buttons are closely related to check boxes. Only, with a radio button you get just the one choice from a list of options. With a check box you can tick all the boxes, if you wanted. Here's what radio buttons look like on a form: Your Location: North East North West South East South West Midlands If you clicked another option, the one already selected is deselected. Here's the HTML code for our radio buttons:

<Input type = radio Name = r1 Value = "NE">North East <Input type = radio Name = r1 Value = "NW">North West <Input type = radio Name = r1 Value = "SE">South East <Input type = radio Name = r1 Value = "SW">South West <Input type = radio Name = r1 Value = "midlands">Midlands Notice that the NAME of all the radio buttons is the same - r1. We use this name in our JavaScript function. Again, we're assuming the NAME of our form is f1. Here's a function which checks which radio button was selected: function GetSelectedItem() { chosen = "" len = document.f1.r1.length for (i = 0; i <len; i++) { if (document.f1.r1[i].checked) { chosen = document.f1.r1[i].value } } if (chosen == "") { alert("No Location Chosen") } else { alert(chosen) } } Again. We're just looping round and checking which item is selected. This time, we're using the checked property of the radio button: if (document.f1.r1[i].checked) If a checked item is found, the value of the radio button clicked will be put into our chosen variable: chosen = document.f1.r1[i].value Try out the Radio Buttons again. Select an option and see what happens Your Location: North East North West South East South West Midlands And with radio buttons tested, we can leave this Form validation section for good. You need never return again, if you don't want to. You can move on the final section of this course - String manipulation.

Substring() and Split()

For this last section of the Javascript course, we're going to look at manipulating text with Javascript's own in-built functions. These inbuilt functions can really make your life easier, and if you're serious about learning the Javascript language you just have to know them. The ones we're going to cover are these: substring() charAt() split () and join() toUpperCase() toLowerCase() We're going to learn about substring() and split() first. To get the hang of these functions, we'll create a simple little game. Off we go.

A Name Swapper Game


The game we'll create is this: A name is entered in a text box. When a button is clicked, a function will swap the first two letters of the surname with the first two letters of the first name, and vice versa. If that's not too clear, here's the little programme we're going to write. Click the button below and see what happens. The "Ga" of Gates is now the "Bi" of Bill; and the "Bi" of Bill is now the "Ga" of Gates. So, create a web page with a button and a text box on it, just like above. Put the textbox and button inside of FORM tags. Call the form f1 and the text box t1. Add an onClick() event to the button. The onClick event will call our function: onClick = jumble() function jumble() { } The first thing we need to do in our function is get the name from the text box. function jumble() { fname = document.f1.t1.value }

split()
Next, we need to split the name entered into a first name and a second name. We can use the split() function for that: function jumble() { fname = document.f1.t1.value SplitName = fname.split(" ") }

The split() function splits text and puts the pieces into an array, with each piece taking up one slot in the array. For example, if you were to split "This is some text", the split() function would create an array with four slots (zero to 3). The first slot in the array would contain "This", the second slot would contain "is", the third "some" and the fourth "text". The syntax for the split() function is this: String.split([separator]) String is the text you want to split. You then type a full stop followed by split(). Inside the round brackets you type the character that you want the function to use when it's doing the splitting (the separator). In our function we typed a space surrounded by double quotes: SplitName = fname.split(" ") So we're telling the function to look for a single space in the variable fname. When it finds a single space, use that to add an item to the array. When it finishes splitting, our variable SplitName will be an array. You can access all the "pieces" in the array by referring to the index number. You can do it very simply, like this: SplitName[0] SplitName[1] Or you can use a loop, like this: for (num = 0; num < SplitName.length; num++) { document.write(SplitName[num]) } The length of SplitName is how many slots in the array - the length of the array, in other words. We'll do it the simple way, because we know we only want to manipulate a first name and a second name. fname = document.f1.t1.value sname = fname.split(" ") first = sname[0] second = sname[1] So first will now hold the first name from the text box, and second will hold the surname from the text box. Before we go any further, a function related to split() is join(). The join function will join together strings in an array. The syntax is this: arrayname.join(separator) Here's an example of how to use it: aryText = new Array("This", "is", "some", "text") t1 = artText.join() t2 = artText.join(" ") t3 = artText.join(" - ") The empty round brackets of t1 gets you a comma as a separator (the default); the t2 puts in spaces as a separator; the t3 puts in a minus sign as a separator. So the three variables will now be this:

t1 = This, is, some, text t2 = This is some text t3 = This-is-some-text But back to our little programme. We have just got the first and surnames and put them into variables. Now what? Well, we now have to chop our two names up a bit. Remember: we're swapping the first two characters of each name. We'll do them one at a time. Let's chop the first name up.

substring()
We need to grab the first two characters of our first name, and separate them from the rest of the name. We can use the function substring() to do this. first1 = first.substring(0, 2) first2 = first.substring(2, first.length) The syntax for substring() is this: stringname.substring(indexA, indexB) After typing the string you want to manipulate, you type a full stop. The name of the function comes next: substring(). In between the round brackets, you need two numbers: where you want to start the search (IndexA), and where you want to end the search (IndexB). Look at how we used the function: first1 = first.substring(0, 2) So we're saying, "Search the variable called first. Start the search at position zero (zero is the first character of the string). End the search at position 2." The function will then strip the characters specified and put them into the variable first1. So, if we started with the first name of "Bill", the code above would put "Bi" into the variable first1. To get the rest of the name, we did this: first2 = first.substring(2, first.length) Now, we're starting the search from position 2. We're ending at the length of the variable first. Again, if we started with the first name of "Bill", the code above would put "ll" into the variable first2. You can use substring() to strip character from right to left, instead of left to right as we did. All you need to do is make indexB a smaller number than indexA. So if we did this: first1 = first.substring(2, 0) the function substring() would start the search on the right hand side, at character zero. It would then grab characters up to indexA, which is set at two above. In other words, it would grab two characters starting from the right. Had it been 5, 0 it would grab five character from the right.

OK, we've found a way to chop our first name up. We can do the same for the surname: second1 = second.substring(0, 2) second2 = second.substring(2, second.length) The only thing left to do now is joined the jumbled pieces together and display the result in the text box: fname = second1 + first2 + " " + first1 + second2 document.f1.t1.value = fname The entire code for our jumble() function is then this: function jumble() { fname = document.f1.t1.value sname = fname.split(" ") first = sname[0] second = sname[1] first1 = first.substring(0, 2) first2 = first.substring(2, first.length) second1 = second.substring(0, 2) second2 = second.substring(2, second.length) fname = second1 + first2 + " " + first1 + second2 document.f1.t1.value = fname } Add it to your web page and test it out. When Bill Gates is entered into your text box, you should get "Gall Bites" when the button is clicked.

Using the charat() function


Another useful in-built JavaScript function is chartAt(). We'll see how this works by creating an anagram programme. We'll keep the same format of text box and button. But this time, when the button is clicked, the programme will create an anagram of the name in the text box. Try it out by clicking the button below (though you might need to click the button a few times before you get anything useful):

An Anagram Programme
To create your own anagram programme, you need a button and a text box on a your web page. The form is called f1, and the text box is called t2. The onClick event of the button is this: onClick = anagram() Again, we start our function by getting the name from the text box: function anagram() {

fname = document.f1.t2.value } Once we've got the name, the technique we're going to use is this:

Put all the individual letters (and spaces) into an array Use a shuffle algorithm to jumble up the letters in the array Display the jumbled letters in the text box

Before we tackle the first step, let's use a simple in-built function to convert all the letters in the name: function anagram() { fname = document.f1.t2.value fname = fname.toLowerCase() } The two inbuilt JavaScript function toLowerCase() and toUppercase() do exactly what you'd expect them to do: convert all the characters to either lower case letters or to uppercase letters. The string you're trying to convert comes first. In the code above, we wanted to convert whatever was in the variable fname to lowercase letters. Now that we've got the name from the text box, and converted the letters to lowercase, we can tackle the first step of our three on the list: Put all the individual letters (and spaces) into an array. We set up the array like this: function anagram() { fname = document.f1.t2.value fname = fname.toLowerCase() aryText = new Array(fname.length) } All we're doing here is setting up an array called aryText. The number of slots (positions) in the array is set by fname.length. This will get you how many characters are in the variable fname. The number of characters is also the size of the array - one slot for each character. Once we've created the array, we can fill all the slots with the characters from our text box. First we get the length of the array: len = aryText.length We then use the length as the upper boundary for a for loop: for (i = 0; i < len; i++) { aryText[i] = fname.charAt(i) } Notice the line that is filling our new array: aryText[i] = fname.charAt(i) We are accessing each slot in the array with aryText[i]. We're setting the value of each slot to a character from our text box:

= fname.charAt(i) And there's the charAt() function. The charAt() function returns the position of character in a string.

charat()
The syntax for the charat() function is this: stringname.charAt(index) First you type the string you want the function to search. After a full stop, you type the name of the function: charAt(). In between the round brackets, you type a number (index). This number is used by the function to search your string. The search will start at 0. So if you type charAt(5), the function will tell you what character is at this position. For example: Text = "Some text" OneCharacter = Text.charAt(5) The variable OneCharacter will hold the letter "t" of text. We used the charAt() function like this: = fname.charAt(i) The sting fname will be searched by the function. We've set the search position to our loop number. So what we're really doing is this: = fname.charAt(0) = fname.charAt(1) = fname.charAt(2) = fname.charAt(3) The character at these positions is then transferred to a slot in our array: aryText[i] = fname.charAt(i) And that will fill the array with each character from our text box. Once the array is filled, we can move on to step two - Use a shuffle algorithm to jumble up the letters in the array. This is not as complicated as it sounds. In fact, you've already met the shuffle algorithm. We used one when we created the lottery programme. We can use the same one again: for (i = 1; i < len; i++) { newnumber = (Math.random() * len) newnumber = parseInt(newnumber, 10) temp = aryText[i] aryText[i] = aryText[newnumber] aryText[newnumber] = temp } The last time we met this, we selected a random number from 1 to 49, which corresponded to a lottery number. This time, we want a random number from zero to

the length of our array. We've already got the length of the array in the len variable. So we can use that to grab a random number: newnumber = (Math.random() * len) Remember: the Math.random() function gets you a random number from zero to 1. If we multiply this by the length of our array, we can use this number as an index. But the random number will be a floating point number. So we have to chop off all the .342678 bit. That's what this does: newnumber = parseInt(newnumber, 10) Once we have our index number, we can use it to swap the letters around in our array: temp = aryText[i] aryText[i] = aryText[newnumber] aryText[newnumber] = temp Now that we've jumbled up all the letters in our array, we can use the join() function to join all the separate letters in the array. When we've done that, we'll have one single name again, and we can display it in the text box: NewName = "" NewName = aryText.join("") document.f1.t2.value = NewName Notice the join() function: aryText.join("") We're saying join all the elements in the array, but don't use anything as a separator. That's we've put a pair of double quotes in between the round brackets. But the double quotes have no space between them. Finally, display the new name in the text box: document.f1.t2.value = NewName And that's it - our own little anagram generator. Here's the entire code, in case you want to copy and paste it: <SCRIPT Language = JavaScript> function anagram() { fname = document.f1.t1.value fname = fname.toLowerCase() aryText = new Array(fname.length) len = aryText.length for (i = 0; i < len; i++) { aryText[i] = fname.charAt(i) } newnumber = "" temp = "" i=0 for (i = 1; i < len; i++) { newnumber = (Math.random() * len) newnumber = parseInt(newnumber, 10)

temp = aryText[i] aryText[i] = aryText[newnumber] aryText[newnumber] = temp } NewName = "" NewName = aryText.join("") document.f1.t1.value = NewName } </SCRIPT> Now that you know a thing or two about string manipulation, we can end this section. In fact, the entire javascript course is coming to an end. You should now have the skills to take your programming further, and develop better scripts than the ones you've learned with us. Good luck - and have fun with your JavaScript programming.

S-ar putea să vă placă și