views:

526

answers:

2

I'm writing the code for a basic GPA calculator. Basically, it's a 3-column-table, two text areas for the course name/credit hours and a dropdown list that contains letter grades (A+, C, B-) and their corresponding point values as the option value, like this

<td><select name="letterGrades">
<option value="0.7">A+</option>>
<option value="1.3">A-</option>>
<option value="2.7">C+</option>
</option>
</select>
</td>

I need to iterate through the rows, get the option value or "grade" for each course.

var table = document.getElementById(tableID);

for(var i=0; i<rowCount; i++) {

 grade = table.rows[i].cells[2].options[letterGrades.selectedIndex].id; //is this allowed?
 credits = parseFloat(table.rows[i].cells[1].value);
 totalHours += parseFloat(table.rows[i].cells[1].value);  
 perCourse += grade*credits

 } 

totalGPA = perCourse/totalHours;

I realize there are other ways to assign the letters to their point values (arrays?) but I still don't know how to iterate through the dropdown lists and get their option values.

+2  A: 

Get to the <select> items first. If that's possible, I suggest you use document.getElementsByTagName('select') to get the list of all <select> tags on your page. Then, with each <select> tag, call theSelectTag.getElementsByTagName('option') (where theSelectTag is an object from the returned node list). You can then access their value through the value property (ya rly), and their label through the textContent property.

getElementsByTagName returns a NodeList object, but you can pretty much treat it the same as an Array.

zneak
I'll try that, thank you.
Bassem Sameh
It worked, I had to use it to get the credit hours (textarea) too. Thanks again.
Bassem Sameh
A: 

I finally got everything to work thanks to zneak's answer. Here's how.

var select = document.getElementsByTagName('select');
var options = document.getElementsByTagName('option');
var textarea = document.getElementsByTagName('textarea');

for(var i=1; i<rowCount; i++) {  //i=1, starts at the second row, assuming you have a header
    var grades = select[i].options[select[i].options.selectedIndex].value; //gets the selected item for each select tag from the dropdownlist
    credits = parseFloat(textarea[i].value); //same goes for textareas
    totalHours += parseFloat(textarea[i].value);            
    perCourse += grades*credits;    
}       
totalGPA = perCourse/totalHours;
Bassem Sameh