Press enter to skip the top menu

JavaScript

Objects and Events

Learning Outcomes

On completion of this section you will know how to use to make a web page more interactive by:

Go to top

Introduction

In the previous section we looked at creating a simple payroll by reading data out of three input boxes and using this data to calculate the gross, tax, superannuation contribution and nett.

For calculating the superannuation we used a very roundabout and awkward method, i.e. supplying a superannuation code, from which the programme itself would work on the superannuation rate. This was a good way of illustrating the use of the switch construct, but as far as making the user’s job easier it fell very short of the ideal.

We shall use the payroll again for this lesson but, other than the hours and rate, all other data will be supplied by the user by clicking on either checkboxes or radio buttons.

An illustration of the completed user interface is shown below.

Notice that there is no button here to click on. This is because calculation occurs automatically after user inputting data. The data entries that would trigger calculation would be:

Any of the above activities that cause the automatic calculation of the payroll to occur is referred to as an event. to do some processing as a result of an event occurring is knows as event handling.

Go to top

The HTML File

We are introducing a new concept into the HTML code below: event handling. The rest of the code should be familiar to you, so we shall concentrate on the event handlers.

Listing 1
                        <!DOCTYPE html>
                        <html lang="en">
                            <head>
                                <link href="InstructionsCSS.css" rel="stylesheet" type="text/css">
                                <meta charset="UTF-8">
                                <link href="Forms.css" rel="stylesheet" type="text/css">
                                <script src="Objects%20Payroll.js" type="text/javascript"></script>
                            </head>
                            <body>
                                <main>
                                    <form style="height: 480px">
                                        <article style="width: 270px;float: left">
                                            <p>
                                                <label for="Hours">Hours Worked</label>
                                                <input type="number" max="60" min="10" id="Hours" name="Hours" required  onchange="calculatePay()">
                                            </p> 
                                            <p>
                                                <label for="Rate">Hourly Rate</label>
                                                <input type="number" max="80" min="20" id="Rate" name="Rate" required onchange="calculatePay() ">
                                            </p> 
                                            <p>
                                                <label for="Gross">Gross Pay</label>
                                                <input type="text" id="Gross" name="Gross" disabled>
                                            </p> 
                                            <p>
                                                <label for="UnionFees">Union Fees</label>
                                                <input type="text" id="UnionFees" name="UnionFees" disabled>
                                            </p> 
                                            <p>
                                                <label for="Superannuation">Super</label>
                                                <input type="text" id="Superannuation" name="Superannuation" disabled>
                                            </p> 
                                            <p>
                                                <label for="Tax">Tax</label>
                                                <input type="text" id="Tax" name="Tax" disabled>
                                            </p> 
                                            <p>
                                                <label for="Net">Net Pay</label>
                                                <input type="text" id="Net" name="Net" disabled>
                                            </p> 
                                        </article>
                                        <article style="float: right;width: 100px;">
                                            <p>
                                                <label for="Union">Union</label>
                                                <input type="checkbox" id="Union" name="Union" onchange="calculatePay()">
                                            </p>
                                            <p>
                                                <label for="Super">Super</label>
                                                <input type="checkbox" id="Super" name="Super" onchange="enableRadio()">
                                            </p>
                                            <p>
                                                <label for="fivep"><span id="fiveSpan">5%</span></label>
                                                <input type="radio" id="fivep" name="fivep" onchange="calculatePay()">
                                            </p>
                                            <p>
                                                <label for="tenp"><span id="tenSpan">10%</span></label>
                                                <input type="radio" id="tenp" name="fivep" onchange="calculatePay()">
                                            </p>
                                            <p>
                                                <label for="fifteenp"><span id="fifteenSpan">15%</span></label>
                                                <input type="radio" id="fifteenp" name="fivep" onchange="calculatePay()">
                                            </p>
                                            <p>
                                                <label for="twentyp"><span id="twentySpan">20%</span></label>
                                                <input type="radio" id="twentyp" name="fivep" onchange="calculatePay()">
                                            </p>
                                        </article>
                                    </form>
                                </main>

                            </body>
                        </html>

                    

The first two event handlers occur at lines 15 and 19. For clarity we shall reproduce line 15 here.

<input type="number" max="60" min="10" id="Hours" name="Hours" required onchange="calculatePay()">

Most of the above code should be familiar to you apart from the final part: 'onchange="calculatePay()"'

Change normally means something new happening. If the case of an input field that accepts user input, a change would mean changing the contents of the input.This would include adding data to it the first time or else modifying existing data. Either way when the user finishes entering data and leaves that input element, a change event occurs. Our html code will respond to that change by calling the function calculatePay(). This function is in our JavaScript file which we shall look at shortly. It simply calculates the pay from scratch based on what change was made to the value of hours worked.

What we have said about line 15 also applies to line 19, and so there is no need to discuss it.

The next event handler is at line 45. Here we handle the checkbox for union membership. Handling union membership is very simple in this case. A person is either a union member or they are not. If they are we deduct $10 from their pay as union contribution or else we don't. Whenever we switch membership on or off we have to recalculate the pay for the new membership state.

At line 49 we meet a slightly different use of the event handler. In this case we are dealing with superannuation contributions. Again this applies only to those who are signed up for superannuation payments. Thus one is a contributor or one is not. Clicking a checkbox on or off is all we need for this. However if the checkbox is on then there are four different ways of calculating the superannuation payments: 5%, 10%, 15% or 20%. This is facilitated by four different radio buttons, which are aligned down the right side of the form. The purpose of the function changeRadio() is to turn those radio buttons on or off.

Go to top

The JavaScript File

All of our JavaScript code is contained within one file. However it contains only two functions. Therefore for readability's sake the the file was broken into two listings: Listing 2 and Listing 2-1.

The listing below contains the function calculatePay().

Listing 2
                        function calculatePay()
                        {
                           sngHours=document.getElementById("Hours").value;
                           curRate=document.getElementById("Rate").value;
                           unionMember=document.getElementById("Union").checked;
                           superMember=document.getElementById("Super").checked;
                           curGross=sngHours*curRate;
                           if (curGross < 500)
                              curTax=curGross * 0.25;
                           else
                              curTax=125+(curGross-500)*0.33;
                           if(unionMember==true)
                              unionFees=10;
                           else
                              unionFees=0;
                           superPayments=0;
                           if(superMember==true)
                           {
                              if(document.getElementById("fivep").checked==true)
                                 superPayments=curGross*0.05;
                              if(document.getElementById("tenp").checked==true)
                                 superPayments=curGross*0.1;
                              if(document.getElementById("fifteenp").checked==true)
                                 superPayments=curGross*0.15;
                              if(document.getElementById("twentyp").checked==true)
                                 superPayments=curGross*0.2;
                           }
                           else
                              superPayments=0;
                           curNet=curGross-curTax - unionFees - superPayments;
                           document.getElementById("Gross").value=curGross;
                           document.getElementById("Tax").value=curTax;
                           document.getElementById("Superannuation").value=superPayments;
                           document.getElementById("UnionFees").value=unionFees;
                           document.getElementById("Net").value=curNet;
                        }
                    

Our file can be very easily broken up into its component sections: input, process and output.

The input spans lines 3 to 6.The raw data, i.e. hours worked, hourly rate union membership and superannuation membership

The processing section spans lines 7 to 29. Lines 7 to 11 calculate the gross and the tax.

Lines 12 to 15 calculate the union fees. No raw numerical data is used here. Instead the Boolean variable unionMember is tested for being true. If it is then the variable unionFees is set to 10, otherwise it is set to zero.

Lines 16 to 29 are involved in calculating the superannuation contribution. At line 17 the program tests if the employee is a member of the super scheme or not. If they are not then the if block is skipped and control passses to line 29 where a value of zero is given to the superannuation payments. If the employee is a superannuation contributor, then at lines 19 to 26 each of the four radio buttons are tested for being checked. Whichever one is checked its corresponding value is stored in the variable superPayments

Line 30 completes the processing by subtracting the values of the tax, union fees and superannuation contributions from the gross.

Lines 31 to 35 make up the output section. Here the values of the gross, tax, superannuation payments, union fees and net are stored in the apprropriate elments of the form.

Listing 2-1
                        function enableRadio()
                        {
                           var styleType;
                           if(document.getElementById("Super").checked==true)
                           {
                              document.getElementById("fivep").removeAttribute("disabled");
                              document.getElementById("tenp").removeAttribute("disabled");           
                              document.getElementById("fifteenp").removeAttribute("disabled");           
                              document.getElementById("twentyp").removeAttribute("disabled");
                              styleType="color:black";
                           }        
                           else
                           {    

                              document.getElementById("fivep").setAttribute("disabled", "true");
                              document.getElementById("tenp").setAttribute("disabled", "true");
                              document.getElementById("fifteenp").setAttribute("disabled", "true");
                              document.getElementById("twentyp").setAttribute("disabled", "true");
                              styleType="color:gray";
                           }
                           document.getElementById("fiveSpan").setAttribute("style",styleType);
                           document.getElementById("tenSpan").setAttribute("style",styleType);
                           document.getElementById("fifteenSpan").setAttribute("style",styleType);
                           document.getElementById("twentySpan").setAttribute("style",styleType);
                           calculatePay();     
                        }
                    

The function enableRadio() is a slight misnomer: it can enable radio buttons that have been disabled but it also can disable the same radio buttons that had been previously enabled. The name toggleRadio() would have been a more appropriate title.

More than half of the function's body is a if..else construct that spans lines 40 to 55.

At line 40 the program checks if the checkbox Super is checked. If it is then we want all of the radio buttons to be turned on. This is done at lines 42 to 45. To do this the program uses removeAttribute("disabled") to enable each of the radio buttons, or by interpeting the code literally to remove the diablement from them

On the other hand if the four radio buttons are to be disabled then lines 50 to 53 uses setAttribute("disabled", "true") to disable all four of them.

Lines 42 to 45 and 50 to 53 disable or enable only the radio buttons themselves. For a better visual presentation we want the labels for the same buttons to be gray or black depending on whether they are enabled or disabled. How do we do this.

Go back to Listing 1 which is our HTML file and check lines 52, 56, 60 and 64. Those are the lines where the labels for the radio buttons are marked up. Notice that each lable is enclosed in a <span>..</span> and that each span has its own unique id.

Now let us go back to Listing 2.1, line 46. The variable styleType is being set to "color:black". In the body of the else the same variable is being set to "color:gray".

At line 56 the colour of the span with the id of "fiveSpan" will have its colour sett to black or gray, depending on whether we are enabling or disableing the radio buttons and their labels.

Go to top

Live Form

Experiment with this form by entering various combinations of values for hours worked, hourly rate, union membership and different superannuation rates.

Go to top