Introducing a New Product - SchoolNova

5 downloads 143 Views 216KB Size Report
http://www.tizag.com/javascriptT/javascriptarray.php. ○. Example: var students = new Array('Michael', 'Kathryn',. 'Ivan', 'Marina', 'Maxim', 'Ethan');. // same as.
IT101

JavaScript: Arrays and Document Object Model

Arrays ●





An array is a variable that can store many variables within it. The array is a special type of variable – it is an Object (more about it later). Values are stored into an array by using the array name and by stating the location where you wish to store the value in brackets. Example: myArray[2] = "Hello World";



Values in an array are accessed by the array name and location of the value. Example: myArray[2];



Array index starts with 0 (zero).



Arrays are often used with loops.



JavaScript has built-in properties and functions (object methods) for arrays, such as “length” and “sort()”, so check them out: http:// www.w3schools.com/jsref/jsref_obj_array.asp



Example: var students = new Array('Michael', 'Kathryn', 'Ivan', 'Marina', 'Maxim', 'Ethan'); // same as var students = ['Michael', 'Kathryn', 'Ivan', 'Marina', 'Maxim', 'Ethan']; // same as var students = new Array(); students[0] = 'Michael'; students[1] = 'Kathryn'; students[2] = 'Ivan';

http://www.tizag.com/javascriptT/javascriptarray.php

Document Object Model ●



When a web page is loaded, the browser creates a Document Object Model of the page. You can manipulate DOM through Javascript (create dynamic HTML): –

Change any HTML elements in the page



Change any HTML attributes in the page



Change any CSS styles in the page



React to all the events in the page

Example: document.getElementById('classTotal').innerHTML = 'Test'; document.getElementById('classTotal').style.backgroundColor = '#FF0000';

Example: Arrays, Loops & DOM Attendance var students = new Array('Michael', 'Kathryn', 'Ivan', 'Marina', 'Maxim', 'Ethan'); function sCheck() { var totInClass = 0; for (var i = 0; i < students.length; i++) { if (document.getElementById(students[i]).checked == true) { totInClass++; } } document.getElementById('classTotal').innerHTML = totInClass + " out of " + students.length; if (totInClass > students.length/2) { document.getElementById('classTotal').style.backgroundColor = '#00FF00'; } else { document.getElementById('classTotal').style.backgroundColor = '#FF0000'; } }

Attendance Sheet

for (var s = 0; s < students.length; s++) { document.writeln("" + students[s] + ": "); document.writeln("
"); }
Total:

Homework ●







Expand the class attendance example so that it tracks not just attendance, but also homeworks. In other words, there should be two checkboxes against each student's name: one for class attendance, another for homework completion. You will need to make sure that the checkboxes' ID's are unique. Don't forget to upload your homework to the server. If you do not remember how, send me an email: [email protected] Sample output: