Press enter to skip the top menu

JavaScript

A basic Program

Learning Outcomes

On completion of this section you will:

Go to top

Introduction

If you are not familiar with html then you will not be able to learn JavaScript since both html and JavaScript are closely bound together. Thus if html is strange to you then I suggest that you first go through the section on html and then return back here once you have mastered the art of creating web pages.

If you are familiar with both html and any other programming language then carry on because you will add another language to your repertoire. Also you may skip down to the header ‘A simple Payroll Programme’ since the next part which explains programming variables will already be familiar to you.

If you are familiar with html but have never programmed then read the next part very carefully because a thorough knowledge of programming variables and how they resemble and how they differ from algebraic variables is the basic building block of programming.

Go to top

Variables

The manipulation of variables is at the heart of computer programming. To the non-programmer variables are associated with algebra. A typical algebraic problem would be as follows:

If x = 5, y = 9 and z=3, what is the value of 2x+3y-5z?

The solution to this of course is that if x is 5 then 2x is 10, if y is 9 then 3y is 27 and if z is 3 then 5z is 15. Thus the expression 2x+3y-5z equates to 10+27-15 which is 22.

We shall look at one more example of algebraic expression. In calculating a person’s pay we multiply the number of hours the person has worked with his hourly rate. Thus if a person has worked x hours and if his hourly rate is y, then his pay is xy. On a particular week if the person has worked 30 hours and if his rate is K8 per hour then we can state the problem as follows:

If x = 30 and y = 8, what is the value of xy?

In this case the solution is the same as above, i.e. if x is 30 and y is 8 then xy is 30 multiplied by 8, which is 240.

As stated earlier, programming a computer involves the manipulation of variables and they are manipulated in exactly the same way as they are manipulated in algebra. This means that we assign a value to each variable in the expression and then perform the calculation specified in that expression.

There are, however, a few differences between how we use variables in algebra and how we use them in programming. Some of the differences are as follows:

In algebra we use a single letter to denote a variable. The most common letters are x, y, z followed by a, b, c. In programming the names of the variables can be as long as we want them to be. Thus in our payroll example above, instead of If x = 30 and y = 8, what is the value of xy we would have the following: if hours = 30 and rate = 8, what is the value of hours * rate?

A computer programme would solve the problem as follows:

Listing 1
                        Hours = 30
                        Rate = 8
                        Gross = Hours * Rate
                        Print Gross
                    

In algebra we assign only numeric values to variables and we don’t care whether they are integers or real numbers. In programming we must be more precise. We must specify whether a variable is to hold an integer or a real number

In algebra, variables represent only numeric values. In programming, however, variables can certainly represent numeric values, but they can also represent text and a variety of other objects such as data stored in databases etc. We need not concern ourselves with this use of variables until later in the course.

Go to top

Events

Events are things that happen. Rugby matches, rock concerts, film premiers and celebrities visiting are all examples of everyday events. In the area of programming we have already encountered an event when we used the hover pseudoclass to change the appearance of a button or any other object that the mouse hovered over. Anyone filling in a form either on a desktop application or on a web page creates any number of events. Some examples are:

And the list goes on.

In this exercise here we shall be using the same form we used in the previous example, except that now we shall be actually making it perform calculations for us. Our basic work plan is to manually enter the values for the hours worked and the hourly rate in the appropriate text boxes and then with our mouse click on the button we named ‘Button 1’. The mouse click will cause the click event of the button to occur which will run the code for calculating the values of the gross, tax and nett and display those results in the appropriate text boxes.

Go to top

A Simple Program

Our modified web page is shown below in Listing 1. The <body> block is almost identical to the one we used in the previous section, i.e. it simply sets up the form with its labels, input boxes and a button. The big changes are in the <head> block. Here we have removed the styling to a .css file named JavaScriptStyles.css and in line 4 we have created a link to that file. The biggest change of all is that we have introduced a <script></script> which spans lines 7 – 19. Welcome to JavaScript!

We have just stated that the <body> block is almost identical to the previous version we encountered. The ‘almost’ is due to the fact that we have made a small, but very significant, change to line 46. Here we have added onClick=calculatePay() to the attributes of the button. The result of this is that when we click on that button the function calculatePay(), which spans lines 8 – 18 will run.

Listing 2
                        <!doctype html>
                        <html lang="en">
                            <head>
                                <link href="Forms.css" rel="stylesheet" type="text/css">
                                <script src="forms.js" type='text/javascript'></script>
                            </head>
                            <body>
                                <main>
                                   <a id="TopOfMain"></a>
                                    <h2>Forms</h2>
                                    <form>
                                        <legend>All fields marked with * are required<br>Fields with shadowed backgrounds are in error</legend>
                                        <fieldset>
                                            <p>
                                                <label for="Hours">Hours Worked *</label><input type="number" id="Hours" name="Hours" min = "10" max="60" value="40" required>
                                            </p>
                                            <p>
                                                <label for="Rate">Hourly Rate *</label><input type="number" id="Rate" name="Rate" min="20" max="80" value="30" required >
                                            </p>
                                            <p>
                                                <label for="Gross">Gross</label><input type="text" name="Gross" id="Gross" disabled  >
                                            </p>
                                            <p>
                                                <label for="Tax">Tax</label><input type="text" name="Tax" id="Tax" disabled >
                                            </p>
                                            <p>
                                                <label for="Net">Net</label><input type="text" name="Net" id="Net" disabled >
                                            </p>
                                        </fieldset>
                                        <input type="button" value="Calculate Pay"  onclick="calculatePay()">
                                    </form>
                                </main>
                            </body>
                        </html>

                    
Listing 3
                        form{
                            width: 450px;
                            border: 2px black solid;
                            border-radius: 20px;
                            margin-top: 20px;
                            margin: auto;
                            display: block;
                            padding: 20px;
                            background: antiquewhite;
                        }
                        form legend{
                            text-align: center;
                        }
                        form fieldset{border: none;}
                        label{
                            margin-right: 15px;
                            font-weight: bold;
                        }
                        input[type="number"]{
                            width: 200px;
                        }
                        input:invalid{
                            box-shadow: 0px 0px 8px black;
                        }
                        h2{ text-align: center}
                        input[type="text"]{font-weight: bold;}
                    
Form based on the html and css codes above
Fig 1
Listing 4
                        function calculatePay()
                             {      
                                sngHours=document.getElementById("Hours").value;
                                curRate=document.getElementById("Rate").value;
                                curGross=sngHours*curRate;
                                curTax=curGross * 0.25;
                                curNet=curGross - curTax;
                                document.getElementById("Gross").value=curGross;
                                document.getElementById("Tax").value=curTax;
                                document.getElementById("Net").value=curNet;
                             }
                    

The code for calculatePay() is shown above in Listing 4. For a novice programmer there is a lot to learn in those lines. We shall begin with line 3 which we have reproduced below.

sngHours=document.getElementById("HoursWorked").value;

Starting at the left we have sngHours. This is a variable. As its name inplies it will hold the value of the number of hours a person has worked.

Where does it get this value from? There is an equal to sign after it. This indicates that it gets its value from whatever is to the right of the equal to sign.

There are two main items to the right: document and getElementById.

The document refers to the web page that is defined in Listing 1 above.

We have added a number of elements to this document:

In line 3 the function getElementById() is given the parameter of “Hours” This is equivalent to telling the system to look among all the elements of the web page and find the element whose id is “Hours”.

The .value at the end refers to the contents of the input box whose id is “Hours”, or in other words the value that the user entered into that input box.

Thus line 3 is equivalent to the statement 'Find the value of the element in the current document whose id is “Hours” and store that value in the variable sngHours.

Thus if the user entered 20 into the box for hours, then 20 will end up being stored in the variable sngHours.

In the same way line 4 is equivalent to the statement 'Find the value of the element in the current document whose id is “Rate” and store that value in the variable curRate.

Again if the user entered 25 in the box for rate then 25 will end up being stored in the variable curRate.

Thus by the time lines 10 and 11 are complete the variables sngHours and curRate 20 and 25 stored in them provided that that is what the user entered in the input boxes.

Once we have the values for the hours worked and the hourly rate we can commence calculating the gross, tax and nett.

We calculate the gross by multiplying the hours by the rate. This is done at line 5.

curGross = sngHours * curRate;

This is very much like an algebraic equation and is equivalent to the statement 'Multiply the values stored in the variables sngHours and curRate and store the result in the variable curGross'.

Thus if sngHours had a value of 20 and curRate had a value of 25 then curGross would have a value of 20 multiplied by 25, which would be 500.

The tax is calculated at line 6

curTax = curGross * 0.25;

Again this is equivalent to saying 'Multiply the value stored in the variable curGross by 0.25 and store the result in curTax.'

Thus if curGross held a value of 500 then curTax would have a value of 125.

The nett is calculated at line 7 by subtracting the value of the tax from the value of the gross.

curNet=curGross – curTax;

This is equivalent to saying 'Subtract the value stored in curTax from the value stored in curGross and store the result in curNet.'

If curGross held a value of 500 and curTax a value of 125, then curNet would hold a value of 375.

Lines 8 – 10 work in the opposite direction to lines 3 – 7, in that they transfer values from the programme variables into the text boxes on the form. Thus line 8 can be read as transfer the value of the variable curGross into the input box in the current document whose id is “Gross”) To put it another way the line is displaying the calculated value of the gross in the text box reserved for displaying the same gross.

Lines 9 and 10 can be explained in exactly the same way.

Go to top

Input Process Output

Looking at lines 10 – 17 in Listing 1 we can see at first glance that they form three groups:

The first group of lines, 3 and 4, take data from the form’s text boxes into the programme area. Since this group’s function is to take data into the programme area they are referred to as the input section of the programme.

The second group uses the data taken in by the input section to calculate the values of the gross tax and nett. This is also referred to as processing the data. For this reason these group of lines are called the process section of the programme.

Lines 8 to 10 are involved in transferring copies of the data from the memory out to the form’s text boxes. For this reason they are referred to as the output section of the programme.

Every programme, regardless of size has these three sections in it. In fact in large complex programmes the input section itself can have its own input, process and output section. The same applies to the other two sections.

Go to top

The Working Program

All fields marked with * are required
Fields with shadowed backgrounds are in error

The above form is a working model of the one we have been discussing. Experiment with it by adding different values to hours and rate and then press the Calculate Pay button to perform the calculation.

Go to top