Part 3 - Creating Documents with JavaScript
Here's a fairly simple table.
Regular HTML for Table
The traditional way to create the table is to code all of it:
| Art | 62 |
58 | 120 |
| Communication | 312 |
298 | 610 |
| Criminal Justice | 388 |
359 | 747 |
| Geography | 212 |
234 | 446 |
| Psychology | 262 |
278 | 540 |
| Sociology | 94 |
87 | 181 |
JavaScript Functions
HTML code can be generated in JavaScript, with functions used to define actions to be repeated. Syntax for a function is:
function Name(parameter1, parameter2, parameter3) {
statement1;
statement2;
statement3;
}
Where Name is the name of the function, parameters are the values passed to the function, and statements are valid JavaScript commands.
JavaScript Code for Table
In the table example, the format for each row can be defined in a function which includes calculation of the total. The tags dividing columns can be assigned to a variable:
function PrtRow(major, fall, spring) {
newcol = "";
document.write(" | | ", major, newcol, fall, newcol,
spring, newcol, fall+spring, " |
\n") }
The function is then called for each row:
PrtRow("Art", 62, 58);
PrtRow("Communication", 312, 298);
PrtRow("Criminal Justice", 388, 359);
PrtRow("Geography", 212, 234);
PrtRow("Psychology", 262, 278);
PrtRow("Sociology", 94, 87);
The commands to define the table and print the headings would be placed in the document as regular HTML code, followed by the script:
With the script, you could add a new row with this command:
PrtRow("Speech", 52, 47);
The traditional way would be:
| Speech | 52 |
47 | 99 |
Changing Function to Add Average
By changing the function, the display can be changed to include an average:
function PrtRow(major, fall, spring) {
newcol = "";
document.write(" | | ", major, newcol, fall, newcol,
spring, newcol, fall+spring, newcol,
(fall+spring)/2, " |
\n") }
| Major | Fall | Spring | Annual | Average |
Highlighting Large Programs
Another change to the function can change the color of rows if the program has more than 500 students a year:
function PrtRow(major, fall, spring) {
newcol = "";
if ((fall+spring) > 500) {rowbg = " | "}
else {rowbg = "
"}
document.write(rowbg, "| ", major, newcol, fall, newcol,
spring, newcol, fall+spring, newcol,
(fall+spring)/2, " |
\n") }
| Major | Fall | Spring | Annual | Average |
Exercise 2
Create a function called ListGrades to put the grades for each student into a table. The function should list the name, the grades for each of three assignments, the total points earned, and the average.
| Name | Exam 1 | Exam 2 | Exam 2 |
Total | Average |
|
Your page should look like this.