Press enter to skip the top menu

JavaScript

Arrays

Learning Outcomes

On completion of this section you will know:

Go to top

Introduction

In this lesson we shall be using a two dimensional array to store data about a construction firm' employees, their skills/qualifications and their current projects. This data is to be available online so that the firm's clients can also check up on the skills that the firm provides.

There are two parts to this project: building the user interface, which will be an online form, and designing and writing a program that can be queried from the form in order to provide answers for both management and clients.

We shall start with the form.

Go to top

Building the Form

Listing 1
                        <!DOCTYPE html>
                        <html lang="en">
                            <head>
                                <link href="Forms.css" rel="stylesheet" type="text/css">
                                <link rel="icon" href="favicon.png" type="image/x-icon">
                                <meta charset="UTF-8">
                                <script src="Arrays.js"  type='text/javascript'></script>
                            </head>
                            <body>
                                <main>
                                    <form >
                                        <legend style="margin-bottom: 20px;">Here you can search for construction workers by their qualifications, their name or the location they are currently working.</legend>
                                         <h4 style="text-align:center">Search by Qualification</h4>
                                        <select  id="qualification" onchange="searchData('qualification',1)" style="" >
                                            <option>Carpenter</option>
                                            <option>Plumber</option>
                                            <option>Roofer</option>
                                            <option>Drain Layer</option>
                                            <option>Electrician</option>
                                        </select>

                                        <h4 style="text-align:center">Search by Name</h4>
                                        <select id="worker" onchange="searchData('worker',0)">
                                            <option>John Smith</option>
                                            <option>Mike Jones</option>
                                            <option>Alistair Drummond</option>
                                            <option>Sam Saw</option>
                                            <option>Ned Nail</option>
                                            <option>Peter Plug</option>
                                            <option>Sean Sink</option>
                                            <option>Tom Tap</option>
                                            <option>Simon Spark</option>
                                            <option>Abel Cable</option>
                                        </select>

                                        <h4 style="text-align:center">Search by Work Location</h4>
                                        <select id="workLocation" onchange="searchData('workLocation',2)">
                                            <option>Aro St</option>
                                            <option>Cable Rd</option>
                                            <option>Mill Drive</option>
                                            <option>Lone Lane</option>
                                        </select>

                                    </form>
                                </main>
                                <footer>
                                </footer>
                            </body>
                        </html>

                    

We shall first examine the html code that spans lines 9 to 45. The <body> block consists entirely of a <form> element which spans lines 11 to 41.

At line 13 a <h4> header is created which is centered on the page and has the text "Search by Qualification". Lines 14 to 19 defines the combo box.

Line 14 defines the box by first giving it an id whose value is ‘qualification’ and whose onchange event calls the function searchData(). To this function it passes the parameters ‘qualification’ and 1. The first parameter is the id of the combo box so that searchData() will know which combo box called it. The second parameter is the number of the column that will be searched. The value of 1 means that searchData() will search for the value in the second column, i.e. the column that contains the job description of the workers.

The effect of the <option> tags that span lines 15 – 19 is to add the text between the opening and closing tags to the drop down list of the box.

Lines 21 to 40 define two other combo boxes but as the form of their definition is identical to the one we just described there is no need to discuss them.

This is what the three drop down lists look like.

This is the completed form.

Go to top

JavaScript Code

Now it is time to look at the JavaScript code below.

Listing 2
                         var arrStaff=[['Sam Saw','Carpenter','Aro St','Cert. Bld Construct','Massey','$25'],
                               ['Ned Nail','Carpenter','Aro St','Diploma in Carpentry','Victoria','$32'],
                               ['Peter Plug','Plumber','Cable Rd','Cert. in Plumbing','Whitireia','$30'],
                               ['Sean Sink','Plumber','Mill Drive','Adv Cert in Plumbing','Weltec','$30'],
                               ['Tom Tap','Plumber','Mill Drive','Cert. in Plumbing','Whitireia','$30'],
                               ['John Smith','Roofer','Lone Lane','BS Roofing','Victoria','$32'],
                               ['Mike Jones','Roofer','Lone Lane','BS Roofing','Victoria','$30'],
                               ['Alex Drummond','Drain Layer','Mill Drive','PhD Water systems', 'Weltec','$32'],
                               ['Simon Spark','Electrician','Aro St','MS Electrics','Massey','$30'],
                               ['Abel Cable','Electrician','Aro St','Diploma in Electrics','Weltec','$30']];
                         function searchData(dataType,dataPosition)
                         {
                            var e=document.getElementById(dataType);
                            if(e==null)
                               alert("Null");
                            else
                            {
                               var intCounter=0;
                               var blnFound=false;
                               while((intCounter<arrStaff.length)&&(!blnFound))
                               {
                                  if(e.value==arrStaff[intCounter][dataPosition])
                                     blnFound=true;
                                  else
                                     intCounter++;
                               }
                               if(blnFound)
                               {
                                  var myNewWindow=window.open("","ResultsWindow","width='900',height='600'");
                                  myNewWindow.document.writeln("<body style='background-color:antiquewhite'>");
                                  myNewWindow.document.writeln("<h1 style='text-align:center'>Search results for ");
                                  myNewWindow.document.writeln(e.value);
                                  myNewWindow.document.writeln("</h1>");
                                  myNewWindow.document.writeln("<table align='center' style='background-color:floralwhite;border:thin black solid;padding:20px'>");              
                                  myNewWindow.document.writeln("<tr style='font-weight:bold'><td style='border:thin solid black;'>Name</td><td  style='border:thin solid black;'>Profession</td><td  style='border:thin solid black;'>Location</td>");
                                  myNewWindow.document.writeln("<td  style='border:thin solid black;'>Qualification</td><td  style='border:thin solid black;'>Institution</td><td  style='border:thin solid black;'>Hourly Rate</td></tr>");  
                                  while(intCounter<arrStaff.length)
                                  {
                                     if(e.value==arrStaff[intCounter][dataPosition])
                                     {
                                        myNewWindow.document.writeln("<tr><td style='border:thin solid black;'>"+arrStaff[intCounter][0]+"</td>");
                                        myNewWindow.document.writeln("<td  style='border:thin solid black;'>"+arrStaff[intCounter][1]+"</td>");
                                        myNewWindow.document.writeln("<td style='border:thin solid black;'>"+arrStaff[intCounter][2]+"</td>");
                                        myNewWindow.document.writeln("<td style='border:thin solid black;'>"+arrStaff[intCounter][3]+"</td>");
                                        myNewWindow.document.writeln("<td style='border:thin solid black;'>"+arrStaff[intCounter][4]+"</td>");
                                        myNewWindow.document.writeln("<td style='border:thin solid black;'>"+arrStaff[intCounter][5]+"</td></tr>");
                                     }
                                     intCounter++;
                                  }
                                  myNewWindow.document.writeln("</table>");        
                                  myNewWindow.document.writeln("</body></html>");        
                               }
                               else
                                  alert(e.value+" was not found");
                            }
                         }

                    

Lines 1 to 10 are taken up with defining the two dimensional array arrStaff. It is built according to the layout shown below.

To reference any element of this array we have to use two index numbers, the row number and the column number. Thus arrStaff[3][4] would mean the value on row 3 of column 4, which would in this case be ‘Weltec’. Similarly arrStaff[5][1] would be ‘Roofer’.

The function searchData() which spans lines 11 to 56 is the second part of the code for this application. The function is passed two parameters, dataType and dataPosition. The first parameter, dataType is the id of the combo box that called the function and the second parameter is the column in the array where the function is to search. We shall follow this function through one set of processing from one combo box and with a specific value.

Supposing that the user selected the option ‘Roofer’ from the combo box that is defined at lines 14 to 20 of Listing 1, then the onchange attribute would call searchData() with the values ‘qualification’ and 1 in its parameters. Thus at line 13 the programme searches for the element whose id is ‘qualification’ and stores a pointer to that element in the variable e.

At line 14 the programme tests if e has a value of null, or in other words if there is an element on the page with an id of ‘qualifications’. If there is then the body of the if at line 15 is ignored and the else component at line 16 is executed. At lines 25 and 26 two variables intCounter and intCounter are initialised. The former will be used to determine which row of the table to search and the second will determine whether we have found the target or not.

The while loop which spans lines 20 to 26 uses the variables intCounter and blnFound to determine whether or not the value ‘Roofer’ exists in column 1, i.e. the second column, of our table. The loop iterates while the variable intCounter is less than the length of the two dimensional array arrStaff and the Boolean variable blnFound is false.

At line 22 the value of the variable e, i.e. ‘Roofer’ is tested against the value held in arrStaff[0][1]. This is the same as saying column 1 of row zero. As we can see from above this will give the value of ‘Carpenter’ – which is not what we are searching for. Consequently line 23 is skipped and line 25 is executed, thus incrementing intCounter to 1. The loop iterates again and this time column 1 of row 1 is tested.

This process continues until column 1 of row 5 is tested where we find the first match with ‘Roofer’. In this case the condition at line 22 will be true for the first time and thus the variable blnFound will be set to true. The loop will then terminate and control will pass to line 27.

Line 27 marks the start of the second part of the function searchData(). In the first part, i.e. lines 12 to 26, we werre searching for a data item in the array arrStaff[]. By the time we get to line 27, then if blnFound is true we have found our target and lines 28 to 52 are involved in creating a web page and building up HTML code that creates a table to present our data inside that page

Line 29 creates a new window called myNewWindow with a width and height of 900 and 600 pixels respectively. Line 30 uses html code to create to create a web page inside that window with the same dimensions as the window itself and with a antique white coloured background.

Lines 31 – 33 create a banner for the page which in our case will be ‘Search results for Roofer’

Line 34 creates a table which will be centered on the page, having a white background and a thin black border.

Lines 42 and 43 put a heading row on the table in bold lettering with the values Name, Profession, Location, Qualification, Institution and Hourly Rate.

Having found its first target at row 5 of the table, the programme will now commence to print out the values of that row and any subsequent row that has ‘Roofer’ in column 1.

At line 37 is a while loop that iterates while intCounter is less than the length of the array arrStaff. This loop will search the table from the row value where the first instance of ‘Roofer’ was found as far as the final row. In our case intCounter has a value of 5 and thus the body of the loop will be entered. Line 39 tests if the value of e is the same as the value in row 5, column 1. Again this is the case since both have a value of ‘Roofer’. Control therefore goes into the body of the if, i.e. lines 41 – 46. In the new window these lines will write the equivalent of:

<tr><td>John Smith</td><td>Roofer</td><td>Lone Lane</td><td>BS Roofing</td><td>Victoria</td><td>$32</td></tr>

Once this html code is written into the new window intCounter would be incremented to 6 at line 56 and the loop would iterate once more. At line 47 the condition would be true again since the combo box and column 1 of row 6 would still have the same value. The details of Mike Jones would therefore be printed in the same format as those of John Smith.

The loop would iterate three more times but lines 49 – 54 would not be executed since there are no more Roofers in the table.

Thus once the loop terminates control goes to line 50 which finishes off the closing tab of the <table> and then line 51 finishes off the closing tabs of both the <body> block and of the <html> itself.

Go to top

View the Application

This is a live version of the form and you can try searching any group you wish. If you use 'Search by Qualification' and select 'Roofer', your output should be like the result below.

Go to top