0% found this document useful (0 votes)
72 views

Y/Controlflow5.Html Beginner'S Javascript Tutorials: Introduction and A First Script

This document provides an introduction to using JavaScript scripts on web pages. It begins with an overview of what scripts are and how they can manipulate web pages beyond regular HTML and CSS. It then presents a "Hello World" script example to get started. The document explains where script tags go, and demonstrates changing the background color of a web page by clicking buttons and using the document object's bgColor property. It also shows how to display popup alert boxes with messages. Overall, the document serves as a basic tutorial for writing first JavaScript scripts and manipulating the document object.

Uploaded by

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

Y/Controlflow5.Html Beginner'S Javascript Tutorials: Introduction and A First Script

This document provides an introduction to using JavaScript scripts on web pages. It begins with an overview of what scripts are and how they can manipulate web pages beyond regular HTML and CSS. It then presents a "Hello World" script example to get started. The document explains where script tags go, and demonstrates changing the background color of a web page by clicking buttons and using the document object's bgColor property. It also shows how to display popup alert boxes with messages. Overall, the document serves as a basic tutorial for writing first JavaScript scripts and manipulating the document object.

Uploaded by

Nnanna John
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 40

http://homepage.ntlworld.com/kayseycarve y/controlflow5.

html Beginner's JavaScript Tutorials


Introduction and a First Script

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.

JavaScript Tutorials
Where to put the Script Tags

The Script Tag and HTML


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.

JavaScript Tutorials
The Document Object (Part One)

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.

JavaScript Tutorials
The Document Object (Part Two)

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.

JavaScript Tutorials
The Document Object (Part Three)

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 Tutorials
The Document Object (Part Four)

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 pop-up window. We'll do that real soon. The next part will look at another object that is widely used - the navigator object.

JavaScript Tutorials

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.

JavaScript Tutorials
The Window Object

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!

JavaScript Tutorials
Variables

Setting up variables in JavaScript


You have just learnt what a variable is (Screen height and width section), and that it is a little 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. We've 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 a number without a decimal point; if you absolutely insist on having a decimal point then the thing you want is called a floating point number; Boolean numbers are not really numbers at all but just a record of whether something is true or not true (think of a light switch - is it on or off?). Here's some examples of all three number types: Integer Floating Point Boolean 3 3.5 true 16 16.8 false 136 136.58 true To store one of those number types into a variable, just use the assignment operator ( = ). The number goes on the right hand side of the assignment operator, and your variable name goes on the left. Here's an example of how to store number types into variables: Number1 = 3 Number2 = 3.5 Number3 = true Number1, Number2, and Number3 are our variable names. We could have used anything we liked here. As long as we're not using the handful of words JavaScript reserves for itself, and not starting with a number, and not putting any spaces in the variable name, we're all right. Here's 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 var in front of them. Like this: var Number1 = 3 The word var is short for variable. It ensures that any variable with the same name elsewhere in your code doesn't overwrite it. Which is a pain, believe me. For clarity's sake, however, we'll 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 the 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. The four basic operators are these : + (Add) - (Subtract) * (Multiply) / (Divide)

Actually, the last two should be the first two. That's because Multiply ( * ) and Divide ( / ) are done first when JavaScript is doing its sums. But, anyway, here's the operators in action. Try 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 B=4 B=B-A alert(B) </SCRIPT> <SCRIPT Language = JavaScript> A=2 B=4 B=B/A alert(B) </SCRIPT> <SCRIPT Language = JavaScript> A=2 B=4 C=6 D = (B * C) / A alert(D) </SCRIPT>

So, how did you get on? The brackets in the last script are for sectioning off code that you want handled separately. Anything in brackets gets dealt with first. So B is multiplied by C first, then the total is divided by A. OK, let's do something a bit more useful. (Though not that much more useful!) The next part is all about adding numbers in text boxes

JavaScript Tutorials
Variables (continued)

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!

JavaScript Tutorials

Variables (part three)

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 Tutorials
Control Flow

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.

JavaScript Tutorials
If ... Else

if else statements
We saw in the last part of this Control Flow section that to test two conditions (true and false) two if statements were needed. But you don't have to use separate if statements. Instead, you can use the else word. This is ideal for Boolean values. Here's our code again, this time with an 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 statement to test for a false condition, we've used the word else. The format for an if else statement is 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, we'll check to see what number is in a text box. Depending on which number was typed in, we'll display an appropriate (or inappropriate) message. First, you're going to need a few more symbols to work with. You've already met the double equals symbol (==), and know that this 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 following form 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 section of 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( ) function. When the message( ) is called, it first stores the value in the text box into a variable called age. age = document.AgeTest.txtAge.value

Next, we need to test what is inside the age variable. We started the test with an if statement: 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 the 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 was this: 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 } It's just another if statement with the word else in front of it (type a space after the word else). You can add as many else if conditions as you want. You can also add an ordinary else statement at the end, just to trap anything not met by your conditions. After all, somebody might type text into your text box, or minus numbers, or nothing at all. In which case, this could solve your problems (though it's no substitute for more thorough error checking):

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") } We haven't finished with this part yet, so you need to click below to continue the lesson.

JavaScript Tutorials
Javascript Operators

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 Tutorials
For 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.

JavaScript Tutorials
For Loops (continued)

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:
Reset

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:
Reset

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!

You might also like